服務是在後臺運行,負責更新內容提供器、發出意圖、觸發通知,它們是執行持續或定時處理的方式。多線程
多線程通常捆綁服務執行任務,由於在activity中開闢多線程執行任務的話,子線程的生命週期得不到保障,可能在應用進入後臺時(進入後臺後子線程仍會繼續執行),activity被釋放時同時被釋放,而service在進入後臺後仍有優先級存在,因此讓子線程捆綁它執行,來保障子線程能執行徹底。而在servcie的onStartCommand中,不會將一個在主線程運行且消耗長時間的任務放在onStartCommand(雖然進入後臺後onStartCommand中的主線程代碼仍會繼續執行),而子線程的開闢通常就放到onStartCommand。這樣onStartCommand就能夠快速完成,並返回一個重啓行爲標識:ide
建立服務this
public class MyService extends Service { private final IBinder binder = new MyBinder(); public class MyBinder extends Binder { MyService getService() { return MyService.this; } } @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) { //啓動一個後臺線程來進行處理 if ((flags & START_FLAG_RETRY) == 0) { } else { } // return super.onStartCommand(intent, flags, startId); return Service.START_STICKY; } }
綁定服務spa
public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startService(new Intent(this, MyService.class)); //綁定服務,這樣就能夠獲取服務對象,從而可使用服務對象的全部公有方法和屬性(應用外的交互能夠經過廣播意圖,或意圖中啓動服務調度extras Bundle,而AIDL是另外一種更緊密的鏈接方式) Intent bindIntent = new Intent(MainActivity.this, MyService.class); bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE); } private MyService serviceBinder; private ServiceConnection mConnection = new ServiceConnection() { //處理服務和活動之間的連接 @Override public void onServiceDisconnected(ComponentName name) { //當服務之外對開時調用 serviceBinder = null; } @Override public void onServiceConnected(ComponentName name, IBinder service) { //當創建鏈接時調用 serviceBinder = ((MyService.MyBinder)service).getService(); } }; }
服務移到前臺線程
public class MyService extends Service { public void moveServiceToForeground() { int NOTIFICATION_ID = 1; Intent intent = new Intent(this, MainActivity.class); PendingIntent pi = PendingIntent.getActivity(this, 1, intent, 0); Notification notification = new Notification(R.drawable.ic_launcher, "Running in the Foreground", System.currentTimeMillis()); notification.setLatestEventInfo(this, "title", "Text", pi); notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT; startForeground(NOTIFICATION_ID, notification); } }