2

我有一个定时器,每 5 分钟做一些东西。问题是我应该在哪里添加这个方法?因为如果我将它添加到“on create”方法中,我的 Timer 方法只会在我的应用程序启动时执行。我想每 5 分钟执行一次。谢谢指教!

 private void timer() {
    final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    service.scheduleWithFixedDelay(new Runnable() {
      @Override
      public void run() {
        // fetching file
        tcpClient.execute();
      }
    }, 0, 60, TimeUnit.SECONDS);
  }

编辑:看起来我需要一个 AlarmManager,正如 Peter Birdsall 和 Aleksander Lidtke 所说 EDIT2:现在我设置了一个 AlarmManager,但我仍然不能每 5 分钟运行一次该方法,我是 Android 新手,我应该在哪里打电话这些东西 ?如果我将它添加到 on create 方法中,它只会执行 1 次,但我希望它永远执行一次,每 5 分钟一次。

这救了我https://github.com/rakeshcusat/Code4Reference/blob/master/AndroidProjects/AlarmManagerExample/AndroidManifest.xml

4

4 回答 4

6

把它放在oncreate中,它不仅会执行一次,我绝对是肯定的。

            Timer myTimer = new Timer();
            myTimer.schedule(new TimerTask() {
               @Override
               public void run() {
                   tcpClient.execute();
               }
            }, 0, 300000);
于 2013-09-05T13:05:01.630 回答
1

我正在开发一个类似类型的应用程序。我使用广播接收器和使用警报管理器安排它的服务,这样你就没有太多开销,比如运行一个必须保持活动状态的计时器。

这是我的主要活动。我用按钮启动序列。

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ...

}



Button.OnClickListener btnOnClickListener = new Button.OnClickListener() {

    @Override
    public void onClick(View v) {

        if (v == btn_splash) {
                initiateAlarm(true);
                Toast.makeText(MainActivity.this, " alarm scheduled", Toast.LENGTH_LONG).show();
            }
            } else if (v == btn_cancel)
                {

                initiateAlarm(false);

                Toast.makeText(MainActivity.this, " alarm stopped", Toast.LENGTH_LONG).show();
                }
    }

};



} 

public void initiateAlarm(Boolean bactive) {
      alarmUp = false;
        alarmUp = (PendingIntent.getBroadcast(getBaseContext(), 0, 
               new Intent(this, YourService.class), 
               PendingIntent.FLAG_NO_CREATE) != null);
                if (alarmUp)
                    {
                    Log.d("myTag", "Alarm is already active");
                    Toast.makeText(this, " before scheduling Alarm is already active", Toast.LENGTH_LONG).show();
                    } else {

                        YourReceiver.scheduleAlarms(this, prefDuration, bactive);
                        Toast.makeText(this, "alarms were just scheduled", Toast.LENGTH_LONG).show();
                    }


         alarmUp = false;
         alarmUp = (PendingIntent.getBroadcast(getBaseContext(), 0, 
                new Intent(this, YourService.class), 
                PendingIntent.FLAG_NO_CREATE) != null);
                if (alarmUp)
                    {
                    Log.d("myTag", "Alarm is already active");
                    Toast.makeText(this, " after scheduling Alarm is already active", Toast.LENGTH_LONG).show();
                    }
}

}

这是在警报管理器中安排服务的 YourReceiver。

public class YourReciever extends BroadcastReceiver {

private static final String TAG = "YourReciever";



@Override
public void onReceive(Context ctxt, Intent i) {
  context = ctxt;

  scheduleAlarms(ctxt, (long) 3600001, true);  // 1 hour - not used

 }

 static void scheduleAlarms(Context ctxt, Long duration, Boolean bactive) {

  Log.e(TAG, " ... scheduleAlarms ");
  SharedPreferences preferences; 

  preferences = PreferenceManager.getDefaultSharedPreferences(ctxt); 
  prefDuration = preferences.getLong(PREF_DURATION, 3600000);  // 1 hour
  Log.e(TAG, " ... onReceive ... duration: " + duration);  

AlarmManager mgr=
    (AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(ctxt, YourService.class);
PendingIntent pi=PendingIntent.getService(ctxt, 0, i, 0);


mgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,
                 SystemClock.elapsedRealtime() + duration, duration, pi);
if (bactive == false) {
    mgr.cancel(pi);
}


 }

}

最后是服务类

public class YourService extends IntentService {




public YourService() {
    super("YourService");
    Log.e(TAG, " ... YourService");

}


@Override
protected void onHandleIntent(Intent intent) {


//
//  The action you want to perform.
//


}

}

像这样的东西需要在清单中。

 <service
        android:name="com.yourpackagename.YourService"
        android:exported="true"/>

希望这可以帮助。

祝你有美好的一天。

于 2013-09-05T15:50:38.823 回答
0

尝试使用动作时间滴答广播。这是一篇文章,它将向您展示如何。很简单。

http://androidbridge.blogspot.ca/2011/08/how-to-use-actiontimetick-broadcast.html

每分钟都在滴答作响,所以在接收者中你只想包含类似的东西

tick++
if(tick>=5)
{
    //Do what you want to do here

    tick=0;
}
else
{
    return;
}
于 2013-09-05T13:37:06.927 回答
-1

使用此代码将帮助您调用函数根据您的要求对其进行修改

private final long refreshDelay = 5 * 1000;
      protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //setContentView(R.layout.main);

            sendHttpRequestThread = new SendHttpRequestThread("","");
            sendHttpRequestThread.start();

        }

     class SendHttpRequestThread extends Thread {

            boolean sendHttpRequest;
            String userId;
            String pass;

            public SendHttpRequestThread(String str1, String str2) {
                this.userId = str1;
                this.pass = str2;
                sendHttpRequest = true;
            }

            public void stopSendingHttpRequest() {
                sendHttpRequest = false;
            }

            protected void onStop() {
                sendHttpRequestThread.stopSendingHttpRequest();
                super.stop();
            }

            @Override
            public void run() {
                while (sendHttpRequest) {
                    //Call U r function from here 

                    SystemClock.sleep(refreshDelay);
                }
            }
        }
于 2013-09-06T07:43:48.583 回答