0

アプリには、アプリが実行されている時間を検出する必要があるサービスがあり、それに基づいて、サービスはその他のアクションを開始します。

これを実装する適切な方法は何ですか?

アプリがユーザーの前で実行されている場合にのみ、サービスが実行されていることを確認するにはどうすればよいですか?

サービスの開始は簡単に思えます。スプラッシュ ロードで開始するだけです。しかし、難しいのはそれを終わらせることです。ユーザーが最後の画面で [戻る] ボタンを押したときに終了できません。ユーザーがホーム画面を押したり、他のアプリ (電話、バイバー ポップアップなど) を押したりした場合の状況を処理するにはどうすればよいですか?

私は他のテーマからの提案を試みました ( How to start a android service from one activity and stop service in another activity? )、これはホームボタンまたは画面を引き継ぐ他のアプリの状況を処理しません。

アプリには合計で約 10 のアクティビティがあります。このサービスを 10 個のアクティビティすべてにバインドし、すべてがオフになるとサービスがオフになるのは適切な方法ですか?

4

2 に答える 2

2

すべてのアクティビティに対して BaseActivity を作成します。BaseActivity で、次の操作を行います。

public class MyActivity extends Activity implements ServiceConnection {

    //you may add @override, it's optional
    protected void onStart() {
        super.onStart();
        Intent intent = new Intent(this, MyService.class);
        bindService(intent, this, 0);
    }

    //you may add @override, it's optional
    protected void onStop() {
        super.onStop();
        unbindService(this);
    }

    public void onServiceConnected(ComponentName name, IBinder binder) {};
    public void onServiceDisconnected(ComponentName name) {};

    /* lots of other stuff ... */
}

BaseActivity は ServiceConnection インターフェイスを実装する必要があります (または、匿名の内部クラスを使用できます) が、これらのメソッドを空のままにしておくことができます。

onBind(Intent)Service クラスでは、メソッドを実装して IBinder を返す必要があります。これを行う最も簡単な方法は次のとおりです。

public class MyService extends Service {
    private final IBinder localBinder = new LocalBinder();

    public void onCreate() {
        super.onCreate();
        // first time the service is bound, it will be created
        // you can start up your timed-operations here
    }

    public IBinder onBind(Intent intent) {
        return localBinder;
    }

    public void onUnbind(Intent intent) {
        // called when the last Activity is unbound from this service
        // stop your timed operations here
    }

    public class LocalBinder extends Binder {

        MyService getService() {
            return MyService.this;
        }
    }
}
于 2013-08-09T16:15:07.093 に答える
1

バインドされたサービスは、この目的のために特別に定義されています。アクティビティをそれにバインドできます。すべてのアクティビティがなくなると、サービスも停止されます。リンクには、実装するのに十分な詳細が含まれている必要があります。

于 2013-08-09T16:14:51.480 に答える