Service的开启和停止以及生命周期
1、清单文件
<service android:name=".TestService"></service>
2、开启Service
Intent intent = new Intent(this, TestService.class); startService(intent);
3、停止服务
Intent intent = new Intent(this, TestService.class); stopService(intent);
4、Service的开启和停止所显示的生命周期
1 package com.example.testservice; 2 3 import android.app.Service; 4 import android.content.Intent; 5 import android.os.IBinder; 6 7 public class TestService extends Service { 8 9 @Override 10 public IBinder onBind(Intent intent) { 11 // TODO Auto-generated method stub 12 return null; 13 } 14 15 @Override 16 public void onCreate() { 17 // TODO Auto-generated method stub--1 18 System.out.println("onCreate"); 19 super.onCreate(); 20 21 } 22 23 @Override 24 @Deprecated 25 public void onStart(Intent intent, int startId) { 26 // TODO Auto-generated method stub--3 27 System.out.println("onStart"); 28 super.onStart(intent, startId); 29 30 } 31 32 @Override 33 public int onStartCommand(Intent intent, int flags, int startId) { 34 // TODO Auto-generated method stub--2 35 System.out.println("onStartCommand"); 36 return super.onStartCommand(intent, flags, startId); 37 38 } 39 40 @Override 41 public void onDestroy() { 42 // TODO Auto-generated method stub--4 43 System.out.println("onDestroy"); 44 super.onDestroy(); 45 } 46 47 }
注意:--n显示是它们的执行顺序