2010-11-25 7 views
1

私はStartService()を使用してアプリケーションの最初のアクティビティのOnCreateで作成されたAndroidサービスを持っています。このサービスは、アプリケーションのライフサイクル全体、つまりアプリケーション内のすべてのアクティビティで実行する必要があります。しかし、ユーザーがホームキーまたは戻るボタンを押した後に、サービスはリソースを消費すべきではありません。すべてのアクティビティのonPause()メソッドでサービスを停止する以外の方法はありますか?ホームキーを押した後にAndroidサービスが実行される

+0

「リソースを消費すべきではない」とはどういう意味ですか?あなたは何を意味していますか? – xandy

+0

私はバックグラウンドで実行するサービスをしたくない – Ananth

答えて

1

アクティビティを拡張し、それをすべての通常のアクティビティに拡張する新しいクラスです。

私はあなたの目標を達成する他のよりエレガントな方法を知りません。

+0

ありがとうございました。私に良く見える – Ananth

2

StartServiceを使用する代わりに、onPauseのonResumeとunbindServiceでbindServiceを呼び出すことができます。開いているバインディングがない場合、サービスは停止します。

サービスにアクセスするにはServiceConnectionを作成する必要があります。例えば、ここでたMyService内にネストクラスです:

class MyService { 
    public static class MyServiceConnection implements ServiceConnection { 
     private MyService mMyService = null; 

     public MyService getMyService() { 
      return mMyService; 
     } 
     public void onServiceConnected(ComponentName className, IBinder binder) { 
      mMyService = ((MyServiceBinder)binder).getMyService(); 
     } 
     public void onServiceDisconnected(ComponentName className) { 
      mMyService = null; 
     } 
    } 

    // Helper class to bridge the Service and the ServiceConnection. 
    private class MyServiceBinder extends Binder { 
     MyService getMyService() { 
      return MyService.this; 
     } 
    } 

    @Override 
    public IBinder onBind(Intent intent) { 
     return new MyServiceBinder(); 
    } 

    @Override 
    public boolean onUnbind(Intent intent) { 
     return false; // do full binding to reconnect, not Rebind 
    } 

    // Normal MyService code goes here. 
} 

一つは介してサービスへのアクセスを得るために、このヘルパークラスを使用することができます:あなたはダレルはなく、Aにそのコードを置くことを示唆しているものを行うことができ

MyServiceConnection mMSC = new MyService.MyServiceConnection(); 

// Inside onResume: 
bindService(new Intent(this, MyService.class), mMSC, Context.BIND_AUTO_CREATE); 

// Inside onPause: 
unbindService(mMSC); 

// To get access to the service: 
MyService myService = mMSC.getMyService(); 
+0

あなたの応答のためにありがとう。このケースでも、私はすべてのアクティビティでOnPauseイベントを処理する必要があります – Ananth

関連する問題