インテント サービスを使用して定期的にサーバーにクエリを送信し、更新があるかどうかを確認しています。インテント サービスには、3 秒ごとにサーバーにクエリを実行するタイマー タスクがあります。これは、アプリケーションが閉じられると実行を開始します。
ユーザーが再びアプリケーションに戻ってきたら、サービスを停止したいと思います。
どうすればいいですか?timertask を実行しているインテント サービスを別のアクティビティから停止するにはどうすればよいですか?
それが私が使用しているものなので、Intent Serviceの提案をしてください。
2 に答える
1
たぶん、IntentService の代わりにサービスだけを使用する方が良いでしょう。
public class UpdateService extends Service {
public class LocalBinder extends Binder {
public void startUpdates() {
// start updateThread if it not started, or
// notify about resuming probes
}
public void stopUpdates() {
// make updateThread to wait, until startUpdates
// called again.
//
// REMEMBER this method can be called when startUpdates didnt called.
}
}
// For simplicity we will use local binder.
private final IBinder binder = new LocalBinder();
@Override
public IBinder onBind(Intent intent) {
return binder;
}
private Thread updateThread = new Thread() {
@Override
public void run() {
while (true) {
// Do updates. Sleep/awake managment.
}
}
};
}
( AUTO_CREATE_FLAGを使用して)サービスにバインドし、必要なときに更新を開始するだけです。アクティビティが表示されたら、サービスに再度バインドして、更新を停止します。
于 2012-03-31T07:49:37.490 に答える