2015年3月31日 星期二

[Android] About Service - how to establish?

In general, we use Activity to construct our program, including the interaction with user and what need to do.
So...why do we need what called Service?

Image that you may need to play music in background or communicate through TCP/UDP and so on.
Of course, you can new a thread to run these jobs in background.
But, what if we want these functions to be available even we have closed our activity?
In this case, you will need the Service mechanism.

First, we need to create service class:
public class myService  extends Service {
 private ServiceThread mServiceThread; 
 @Override
 public IBinder onBind(Intent intent) {
  // TODO Auto-generated method stub
  return null;
 }
 
 @Override
 public void onCreate() {
 // TODO Auto-generated method stub
 super.onCreate();
 }
  
 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
  mServiceThread = new ServiceThread();
  mServiceThread.start();
     return  START_STICKY ; 
 }     
  

 @Override
 public void onDestroy() {
  Log.d(TAG,"onDestroy()");
  if (mServiceThread != null)
   mServiceThread.interrupt();
 }
  
 private class ServiceThread extends Thread {
  @Override
  public void run() {
   super.run();
   //your action here
  }
 } 
}
We new  ServiceThread() here because we need our service to run some jobs repeatedly.
If you only want to do some simple actions and just need to do them once, you can add the related codes in onStartCommand() directly.

After that, we need to register our service in AndroidManifest.xml.
<service android:name="myPackageName.myService"> </service >
We have established our Service now.

How to call it?
Assume that you have on button in the activity, and we want to start the service when we press it.
public void onClick(View v) {
Intent i = new Intent(this, myService.class);  
startService(i);
}
On the other hand, if we want to stop the Service?
public void onClick(View v) {
Intent i = new Intent(this, myService.class);  
stopService(i);
}

To check if we have established our service or not, we can open the RUNNING list in Settings/Apps.
There should have the name of our service.

沒有留言:

張貼留言