2012-02-04 3 views
0

Я внедряю привязку к сервису в своем приложении. Однако, когда я запускаю свою деятельность, которая связывается с сервисом, сила приложения закрывается. Ive pin указал, что из-за getApplicationContext() ... Heres мой код и где он вызывается и используется ... Вся помощь приветствуется. Благодаря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

Обеспечить некоторые журналы пожалуйста .. –

ответ

1

для того, чтобы связать службу с деятельностью, вместо того, чтобы использовать getApplicationContext(), вы должны использовать getBaseContext() или this ключевое слово

+0

эй спасибо как я запустить эту услугу в своей деятельности ? –

+0

, если вы хотите начать свою службу, вызовите метод 'startService' внутри вашей деятельности. http://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent) – waqaslam

+0

бумный бум BOOM! используется doBindService(); затем mBoundService.onStart (намерение, 0,0); благодаря –