2012-02-04 105 views
0

我正在实施服务绑定到我的应用程序。但是,当我开始绑定到服务的活动时,应用程序关闭。伊夫针指出,由于getApplicationContext()...继承人我的代码和它被称为和使用... 所有帮助表示赞赏。 感谢getApplicationContext()...强制关闭?

private LocalService mBoundService; 
private boolean mIsBound; 


Context context = getApplicationContext(); 



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. 
    mBoundService = ((LocalService.LocalBinder)service).getService(); 

    // Tell the user about this for our demo. 
    Context context = getApplicationContext(); 
    Toast.makeText(context, "serviceconnected", 
      Toast.LENGTH_SHORT).show(); 
} 

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. 
    mBoundService = null; 
    Toast.makeText(context, "serviceDisconnected", 
      Toast.LENGTH_SHORT).show(); 
    } 
}; 

    void doBindService() { 
// Establish a connection with the service. We use an explicit 
// class name because we want a specific service implementation that 
// we know will be running in our own process (and thus won't be 
// supporting component replacement by other applications). 
bindService(new Intent(context, 
     LocalService.class), mConnection, Context.BIND_AUTO_CREATE); 
    mIsBound = true; 
} 

    void doUnbindService() { 
    if (mIsBound) { 
    // Detach our existing connection. 
    unbindService(mConnection); 
    mIsBound = false; 
} 
} 

    @Override 
    protected void onDestroy() { 
    super.onDestroy(); 
    doUnbindService(); 
} 
+0

提供一些日志,请.. – 2012-02-04 20:12:38

回答

1

为了与活动结合,而不是使用getApplicationContext()服务,你应该使用getBaseContext()this关键字

+0

嘿感谢我如何开始我的活动这项服务? – 2012-02-04 21:16:58

+0

如果你想开始你的服务,请在你的活动中调用'startService'方法。 http://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent) – waqaslam 2012-02-04 21:22:39

+0

boomy boom BOOM!使用doBindService();那么mBoundService.onStart(intent,0,0);谢谢 – 2012-02-05 00:56:56