2012-01-20 6 views
2

私はそのようなサービスがあります。私は、バインダーは、それによってサービスのインスタンスを取得受け取り、その後、私はそのすべてのメソッドへのアクセスを持って活動にバインダーインターフェイスでサービスのインスタンスを返すのは安全ですか?

public MyService extends Service { 

    // ... 

    IBinder binder = new MyBinder(); 

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

    public class MyBinder extends Binder { 

     public MyService getService() { 
      return MyService.this; 
     } 
    } 

    // ... 
} 

を。私は知りたい、それをするのは安全ですか?または、私はBinderインターフェイスを介してのみサービスと対話する必要がありますか?ありがとうございました!

答えて

2

アクティビティでは、私はバインダーを受け取り、サービスインスタンスを取得し、 の後に、すべてのメソッドにアクセスできます。私は知りたい、 のようにそれは安全ですか?または私はバインダー インターフェイスを介してのみサービスと対話する必要がありますか?

バインダーは返されるもので、あなたが知っているServiceクラスにキャストするだけです。あなたがそれをやっているやり方は、バインダーだけを使用しているのです...

そして、あなたがやったやり方は、それがどのように行われたかです。 http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/LocalService.htmlサービスクラスのメソッドを呼び出す他の方法はかなりハッキリです(前に試してみました)。

例:

private ServiceConnection mConnection = new ServiceConnection() { 
     public void onServiceConnected(ComponentName className, IBinder service) { 
      // This is called when the connection with the service has been 
      // established, giving us the service object we can use to 
      // interact with the service. Because we have bound to a explicit 
      // service that we know is running in our own process, we can 
      // cast its IBinder to a concrete class and directly access it. 
      myService = ((MyService.LocalBinder)service).getService(); 



     } 

     public void onServiceDisconnected(ComponentName className) { 
      // This is called when the connection with the service has been 
      // unexpectedly disconnected -- that is, its process crashed. 
      // Because it is running in our same process, we should never 
      // see this happen. 

     } 
    }; 
+0

はどうもありがとうございました!今分かります。 – Anton

関連する問題