2011年3月8日 星期二

[Android] Android Service

什麼是Android Service
  • A service can run in the background to perform work even while the user is in a different application.
  • A service can allow other components to bind to it, in order to interact with it and perform interprocess communication.
  • A service runs in the main thread of the application that hosts it, by default.

來個例子

在AndroidManifest.xml中增加一個Service,其中ExampleService為你Service class的名稱
<manifest ... >
  ...  
  <application ... >      
  <service android:name=".ExampleService" />
  ...  
 </application>
</manifest>

建立myService.java,參考自Android學習筆記 - 背景執行服務(Service)
package com.cyberlink.dtcpip; 
import android.app.Service; 
import android.content.Intent; 
import android.os.Handler; 
import android.os.IBinder; 
import android.util.Log; 
import java.util.Date; 

//繼承android.app.Service 
public class myService extends Service { 
    private Handler handler = new Handler(); 
  
    @Override
    public IBinder onBind(Intent intent) { 
        return null; 
    } 
  
    @Override
    // The old onStart method that will be called on the pre-2.0
    // platform. On 2.0 or later we override onStartCommand().
    public int onStartCommand(Intent intent, int flags, int startId) { 
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
        handler.postDelayed(showTime, 1000); 
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    } 
  
    @Override
    public void onDestroy() { 
        handler.removeCallbacks(showTime); 
        super.onDestroy(); 
    } 
      
    private Runnable showTime = new Runnable() { 
        public void run() { 
            //log目前時間 
            Log.i("[MyService]", "Time = " + new Date().toString()); 
            handler.postDelayed(this, 1000); 
        } 
    }; 
}

By returning the START_STICKY constant when your Service is started, you tell Android that if it has to kill the Service to free up valuable resources, then you’d like it to restart the Service when resource become available again.

啟動Service
Intent intent = new Intent(this, myService.class); 
startService(intent); 

關閉Service
Intent intent = new Intent(this, myService.class); 
stopService(intent); 

相關連結

沒有留言:

張貼留言