startService的生命周期实践:
public class MyService extends Service { @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); Log.i("msg","onCreate"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i("msg","onStartCommand"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { Log.i("msg","onDestroy"); super.onDestroy(); } }
现在有两个activity,MainActivity、UselessActivity,MainActivity有个按钮启动UselessActivity,UselessActivity启动MyServier
1.MainActivity启动UselessActivity后,UselessActivity启动MyService
Log.i=msg: onCreate msg: onStartCommand
①如果UselessActivity中不调用stopService(Intent):
按返回到MainActivity,并不会打出Log.i=msg: onDestroy. ★服务不会随着启动它的Activity一起销毁。★
再按返回退出程序,再打开程序,启动service,打出Log.i=onStartCommand.而没有打出msg: onCreate,说明service还在 ★服务不会随着启动它的程序退出被销毁。★
再按返回退出程序,并在手机的程序列表里把程序给删除掉,再打开程序,启动service,打出Log.i=onStartCommand.而没有打出msg: onCreate,说明service还在 ★服务不会因为启动它的程序被销毁而销毁。★
②如果在UselessActivity中的onDestroy调用stopService(Intent):
UselessActivity:
@Override protected void onDestroy() { super.onDestroy(); stopService(intent); }
按返回到MainActivity,打出Log.i=msg: onDestroy. ★需要调用stopService(Intent),service才会被销毁。★
bindService的生命周期实践:(慢慢补充)
时间: 2024-10-14 22:38:09