Add these methods to your work:
private MyService myServiceBinder; public ServiceConnection myConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder binder) { myServiceBinder = ((MyService.MyBinder) binder).getService(); Log.d("ServiceConnection","connected"); showServiceData(); } public void onServiceDisconnected(ComponentName className) { Log.d("ServiceConnection","disconnected"); myService = null; } }; public Handler myHandler = new Handler() { public void handleMessage(Message message) { Bundle data = message.getData(); } }; public void doBindService() { Intent intent = null; intent = new Intent(this, BTService.class);
And you can bind to the service using ovverriding onResume () and onPause () in your Activity class.
@Override protected void onResume() { Log.d("activity", "onResume"); if (myService == null) { doBindService(); } super.onResume(); } @Override protected void onPause() {
Note that when binding to a service in the service class, only the onCreate() method is onCreate() . In your Service class, you need to define the myBinder method:
private final IBinder mBinder = new MyBinder(); private Messenger outMessenger; @Override public IBinder onBind(Intent arg0) { Bundle extras = arg0.getExtras(); Log.d("service","onBind"); // Get messager from the Activity if (extras != null) { Log.d("service","onBind with extra"); outMessenger = (Messenger) extras.get("MESSENGER"); } return mBinder; } public class MyBinder extends Binder { MyService getService() { return MyService.this; } }
After you have defined these methods, you can use the methods of your service in your activity:
private void showServiceData() { myServiceBinder.myMethod(); }
and finally, you can start your service when some kind of event happens, for example _BOOT_COMPLETED _
public class MyReciever extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals("android.intent.action.BOOT_COMPLETED")) { Intent service = new Intent(context, myService.class); context.startService(service); } } }
note that when the onCreate() and onStartCommand() services are started, it is called in the service class and you can stop your service when another event occurs using stopService (); note that your event listener must be registered in your Android manifest file:
<receiver android:name="MyReciever" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver>