android中的start开启服务的作用
在学习服务之前,我们不得不先解释一下进程的概念,进程就是系统为该应用运行时开启了一个进程同时单独开启的一个线程来运行该应用,通常该线程被称为主线程,又叫UI线程。
进程:是具有一定独立功能的程序、它是系统进行资源分配和调度的一个独立单位,重点在系统调度和单独的单位,也就是说进程是可以独 立运行的一段程序。
android下四大组件都是运行在主线程中。
进程的优先级:
- Foreground progress:前台进程,优先级最高,就是正在与用户正在交互的进程。
- Visible progress:可视进程,一直影响用户看的见的进程,相当于activity执行了onPause()方法。
- Service progress:服务进程,通过startservice方法开启的服务
- background progress:后台进程,界面不可见,但是任然在运行的进程
- Empty progress:空进程,不会维持任何组件运行。
- 这五个进程中由于优先级的不同,空进程时最容易被销毁的,后台进程也比较容易销毁,所以这里需要服务进程,在后台运行的时候,不容易被销毁。
服务:
- 就是默默运行在后台的组件,可以理解为是没有前台的activity,适合用来运行不需要前台界面的代码
- 服务可以被手动关闭,不会重启,但是如果被自动关闭,内存充足就会重启
start方式开启服务的特点:
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
System.out.println("bind");
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("start");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
System.out.println("create");
super.onCreate();
}
@Override
public void onDestroy() {
System.out.println("destroy");
super.onDestroy();
}
}
startService启动服务的生命周期
onCreate-onStartCommand-onDestroy
重复的调用startService会导致onStartCommand被重复调用,startservice开启的服务,该服务所在的进程会变成服务进程,可在后台运行,服务与启动它的activity将不在有关系。
如何开启服务:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void start(View v){
//启动服务
Intent intent = new Intent(this, MyService.class);
startService(intent);
}
public void stop(View v){
//停止服务
Intent intent = new Intent(this, MyService.class);
stopService(intent);
}
}