4

私はアンドロイドの初心者です。バックグラウンドで 5 秒ごとに特定のコードが実行されるアプリを開発しています。これを実現するために、タイマー タスクを含むタイマー サービスを使用しています。しばらくは正常に動作しますが、無期限に私のサービスが実行されますが、タイマータスクはAndroidで自動的に停止します。これが私のコードです。助けてください。前もって感謝します。

    public void onStart(Intent intent, int startid) {
    //this is the code for my onStart in service class
    int delay = 1000; // delay for 1 sec.

    final int period = 5000; // repeat 5 sec.

    timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
                        executeCode();
    }, delay, period);

};
4

3 に答える 3

4

私の意見では、タイマータスクの代わりにバックグラウンドタスクの繰り返しをスケジュールするには、IntentServiceでAlarmManagerを使用する必要があります。タイマーは信頼性が低く、Androidフレームワーク内で常に正しく機能するとは限りません。また、電話がスリープ状態の場合、タイマーは実行されません。アラームで電話を起こして、AlarmManagerでコードを実行することができます。

見る:

https://developer.android.com/reference/android/app/AlarmManager.html

http://mobile.tutsplus.com/tutorials/android/android-fundamentals-scheduling-recurring-tasks/

http://android-er.blogspot.in/2010/10/simple-example-of-alarm-service-using.html

電話を再起動した場合は、アラームマネージャを再度トリガーする必要があります。これを行う方法の正確な手順については、このチュートリアルを参照してください。

http://www.androidenea.com/2009/09/starting-android-service-after-boot.html

于 2012-10-31T12:50:29.040 に答える
1

通常、TimerTask は、デバイスが長時間スリープ モードになると停止します。要件に合わせて AlarmManager クラスを使用してみてください。AlarmManager のバッテリー消費も少なくなります。

AlarmManagerの使用方法の例を次に示します。

于 2012-10-31T12:50:04.433 に答える
0

指定した時間の後に呼び出される組み込みメソッドを持つ CountDown Timer を使用すると、このタスクをより適切に達成できると思います

public class CountDownTest extends Activity {
TextView tv; //textview to display the countdown
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
this.setContentView(tv);
//5000 is the starting number (in milliseconds)
//1000 is the number to count down each time (in milliseconds)
MyCount counter = new MyCount(5000,1000);
counter.start();
}
//countdowntimer is an abstract class, so extend it and fill in methods
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
tv.setText(”done!”);
}
@Override
public void onTick(long millisUntilFinished) {
tv.setText(”Left: ” + millisUntilFinished/1000);
}
}

上記の例では、1000 ミリ秒ごとに呼び出されるOnTick
メソッドで任意の関数を実行できます。

詳細はこちら

于 2012-10-31T12:52:55.303 に答える