2012-01-20 36 views
2

我有一个这样的服务:在Binder界面中返回服务实例是否安全?

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

在活动我收到粘结剂从而获得服务实例, 我可以访问它的所有方法之后。我想知道, 是否安全?或者我应该只通过Binder 界面与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