2012-02-04 127 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