今天抽点时间来讲Services服务,什么事服务呢,大家应该联想到生活中很多的服务,对的,我们这个服务简单来说和生活中的服务也一样的,Services是一个可以在后台执行长时间运行操作而不是提供用户的应用界面,服务仍将在后台继续运行,服务基本上分为两种方式,1,启动。2,绑定。今天我们就来讲讲启动,接下来执行下面的操作
首先配服务
<service android:name=".MyServices2"
android:exported="true"
>
</service>
要通过Activity来启动服务
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = new Intent(this,MyServices2.class);
}
public void start(View view){
intent.putExtra("data","下载的路径");
startService(intent);
}
public void stop(View view){
stopService(intent);
}
Services有四大生命周期还有启动的一些操作
public IBinder onBind(Intent intent) {
Log.i("test", "onBind");
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.i("test", "onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String data=intent.getStringExtra("data");
Log.i("test", "onStartCommand"+data);
//ANR:application not responsing应用程序未响应
new MyThread(startId).start();
return super.onStartCommand(intent, flags, startId);
}
class MyThread extends Thread {
private int startId;
public MyThread(int startId) {
this.startId = startId;
}
@Override
public void run() {
super.run();
for (int i = 0; i < 10; i++) {
Log.i("test", "i=" + i);
SystemClock.sleep(1000);
}
//停止服务
// stopSelf();//当第一个线程执行完毕,则会停止服务
//所有的线程都执行完毕,才停止服务
stopSelf(startId);
}
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i("test", "onDestroy");
}
服务停止有两种方式
startId:代表启动服务的次数,由系统生成。
stopSelf(int startId):
在其参数startId跟最后启动该service时生成的ID相等时才会执行停止服务。
stopSelf():直接停止服务。
使用场景:
如果同时有多个服务启动请求发送到onStartCommand(),不应该在处理完一个请求后调用stopSelf();因为在调用此函数销毁service之前,可能service又接收到新的启动请求,如果此时service被销毁,新的请求将得不到处理。此情况应该调用stopSelf(int startId)。请参见:IntentService
`
stopService
stopSelf
stopSelf()
stopSelf(id)
Services也有两种的继承方式然后他们最大的区别就是在这里面可以直接写耗时操作,还有一个区别就是onHandleIntent是有顺序的,onStartCommand是无序的
`