/* Service communication */ void doBindService() { startService(new Intent(this.getApplicationContext(), MyService.class)); bindService( new Intent(this.getApplicationContext(), MyService.class), mConnection, Context.BIND_AUTO_CREATE); mIsBound = true; Logs.d(this, "Service binding."); }
@Override protected void onDestroy() { super.onDestroy(); try { doUnbindService(); } catch (Throwable t) { Logs.d(this, "Failed to unbind from the service"); } }
@Override protected void onPause() { Logs.d(this, "onPause"); if (mService != null && mService.getBinder() != null) { // unbindService(myConnection); doUnbindService(); } super.onPause(); }
public void onServiceConnected(ComponentName className, IBinder service) { mService = new Messenger(service); Logs.d(this, "Service attached."); try { Message msg = Message.obtain(null, MyService.MSG_REGISTER_CLIENT); msg.replyTo = mMessenger; mService.send(msg); } catch (RemoteException e) { // In this case the service has crashed before we could even do anything with it } }
void doUnbindService() { if (mIsBound) { // If we have received the service, and hence registered with it, then now is the time to // unregister. if (mService != null) { try { Message msg = Message.obtain(null, MyService.MSG_UNREGISTER_CLIENT); msg.replyTo = mMessenger; mService.send(msg); } catch (RemoteException e) { // There is nothing special we need to do if the service has crashed. } } // Detach our existing connection. unbindService(mConnection); mIsBound = false; Logs.d(this, "Unbinding."); } }
@Override protected void onResume() { AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); Intent i = new Intent(this.getApplicationContext(), MyService.class); PendingIntent pi = PendingIntent.getService(this, 0, i, 0); am.cancel(pi); double minutes = 1; // by my own convention, minutes <= 0 means notifications are disabled if (minutes > 0) { am.setInexactRepeating( AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime() + (long) minutes * 60 * 1000, (long) minutes * 60 * 1000, pi); } Logs.d(this, "onResume"); if (mService == null || mService.getBinder() == null) { doBindService(); } super.onResume(); }
public void onServiceDisconnected(ComponentName className) { // This is called when the connection with the service has been unexpectedly disconnected // - process crashed. mService = null; Logs.d(this, "Service disconnected."); }