1.启动Service的两种方式
1.1 startService及stopService
状态:
- onCreate
如果多次调用startService,并service已经处于运行的状态时,onCreate仅仅会被回调一次
- onStartCommand
如果多次调用startService,每次启动时onStartCommand均会被调用
- onBind:
Service中的onBind方法是抽象方法,所以Service类本身就是抽象类,也就是onBind方法是必须重写的,即使我们用不到。在通过startService使用Service时,我们在重写onBind方法时,只需要将其返回null即可
onBind方法主要是用于给bindService方法调用Service时才会使用到
- onDestory
通过startService方法启动的Service会无限期运行,只有当调用了Context的stopService或在Service内部调用stopSelf方法时,Service才会停止运行并销毁,在销毁的时候会执行Service回调函数
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Button startbutton;
private Button stopbutton;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startbutton = (Button)findViewById(R.id.startbutton);
stopbutton = (Button)findViewById(R.id.stopbutton)