今天给大家分享下Android 四大组件的服务,服务就是在后台为我们执行耗时操作的,在服务中又分为二中方式的服务,一种是启动,一种是绑定,在官方的介绍中都有就不详说了。
今天为大家介绍服务中的启动:
布局就一个Button就是启动服务,
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="开启服务"
android:onClick="star"/>
在Activity中写一个star的方法去开启服务:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = new Intent(this,MyServices.class);
}
public void star(View view){
startService(intent);
}
因为startServices()要一个Intent的参数然后服务也是一个类所以我们直接放到Intent中但是在清单文件要配置一下:
<service android:name=".MyServices"
android:exported="true"
></service>
这里的MyServices是我写的一个服务:public class MyServices extends Service {
//绑定服务
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
//创建服务
@Override
public void onCreate() {
Log.i("test","onCreate");
super.onCreate();
}
//开始服务
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("test","onStartCommand");
new MyThree(startId).start();
return super.onStartCommand(intent, flags, startId);
}
//销毁服务
@Override
public void onDestroy() {
super.onDestroy();
Log.i("test","onDestroy");
}
//线程
class MyThree extends Thread{
private int startId;
//从外面拿到startId
public MyThree(int startId){
this.startId=startId;
}
@Override
public void run() {
super.run();
for (int i = 0; i <10 ; i++) {
Log.i("test",i+"");
}
//在线程结束时销毁服务
stopSelf();
//在所有的线程结束时才会销毁服务
stopSelf(startId);
}
}
}
在点击开启服务的时候会先调用onCreate()然后在调用onStartCommand()在线程结束的时候会调用stopSelf方法在调用onDestroy()。
在这里解释一下服务中为什么要放线程,不是服务就是为我们执行耗时操作的吗?
就比如一场战争,服务就如一个将军,线程就如一个士兵,开启服务其实就是要线程帮我们做事然后服务去指挥线程,一个线程结束了但是服务并不会被干掉并且被干掉的线程并不会被重新唤起,但是如果服务被干掉了还是有可能被唤起重新打开的。