startService开启服务
startService(Intent) 通过这种方式开启的服务执行的生命周期方法:
第一次调用startService的时候
onCreate()->onStartCommand
再次调用startService
startService->onStartCommand
.
想停止用startService开启的服务 stropService(intent);
stopService执行之后Service会走onDestroy()方法,执行后Service销毁。
再次调用stopService没有反应。
.
如果在activity中通过startService方法开启一个服务,当activity退出的时候Service不会销毁,依然在后台运行,只有手动调用stopService或者应用管理器中关闭Service服务才会销毁。
startService开启服务示例
1.创建JAVA类 并继承Service服务
// 创建JAVA类 并继承Service服务
public class MyService extends Service{
@Override
public IBinder onBind(Intent arg0) {
System.out.println("onBind!!!");
return null;
}
@Override
public void onCreate() {
super.onCreate();
System.out.println("onCreate!!!");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("onStartCommand!!!");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
System.out.println("onDestroy!!!");
super.onDestroy();
}
2.在程序清单中注册服务
<service android:name="com.example.service.MyService"></service>
3.处理事件 开启服务或停止服务
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//开启服务
public void start(View view) {
Intent intent = new Intent(getApplicationContext(),MyService.class);
startService(intent);
}
//停止服务
public void stop(View view) {
Intent intent = new Intent(getApplicationContext(),MyService.class);
stopService(intent);
}
}