service字面上是服务的意思,但在android中我理解的它是“后台”服务。他与acivity一样有生命周期,但是它却不能与人之间进行界面的交互。servic常见的会有四个API:startService,stopService,bindService(绑定),unbindService
如何启动service?
1.首先新建一个类继承Service,在AndroidManifest.xml要声明:
<service android:name="com.example.androidservice.Myservice"></service>
2.在layout布局中拖入四个button,然后再mainactivity中给这四个按钮设置监听器:
findViewById(R.id.st).setOnClickListener(this); findViewById(R.id.sp).setOnClickListener(this); findViewById(R.id.bd).setOnClickListener(this); findViewById(R.id.unbd).setOnClickListener(this);}
3.捕获到this的异常,实现onclick函数,设置监听器:
不同的按钮对应不同的四个service的API
public void onClick(View v) {
switch (v.getId()){
case R.id.st:startService(intent);break;
case R.id.sp:stopService(intent); break;
case R.id.bd:
bindService(intent, this,Context.BIND_AUTO_CREATE);
break;
case R.id.unbd:unbindService(this);break;}
4:监听器的参数intent:
private Intent intent;
intent=new Intent(MainActivity.this,Myservice.class)
5:在模拟器中运行,观察结果。注意在“设置”,“app”中才能看到service是否运行: