1 Service简介
服务(Service) 是Android中实现程序后台运行的解决方案,它非常适合去执行那些不需要 和用户交互而且还要求长期运行的任务。服务的运行不依赖于任何用户界面,即使程序被切换到 后台,或者用户打开了另外一个应用程序,服务仍然能够保持正常运行。
服务并不是运行在一个独立的进程当中的,而是依赖于创建服务时所在 的应用程序进程。当某个应用程序进程被杀掉时,所有依赖于该进程的服务也会停止运行。
服务并不会自动幵启线程,所有的代码都是 默认运行在主线程当中的。我们需要在服务的内部手动创建子线程,并在这里执行具 体的任务,否则就有可能出现主线程被阻塞住的情况。
2 Service的两种启动方式
1 使用Context 的startService(Intent)方法启动Service
- 步骤
- 定义一个类继承Service
- 在Manifest.xml文件中配置该Service
- 使用Context的startService(Intent)方法启动该Service
- 不再使用时,调用stopService(Intent)或者stopSelf()方法停止该服务
- 生命周期
onCreate()--->onStartCommand()(onStart()方法已过时)---> onDestory()
- 特点
- 如果服务已经开启,不会重复的执行onCreate(), 而是会调用onStartCommand()。服务停止的时候调用 onDestory()。服务只会被停止一次。
2. 一旦服务开启跟调用者(开启者)就没有任何关系了。开启者退出了,开启者挂了,服务还在后台长期的运行。开启者不能调用服务里面的方法。
- 代码示例
Actiivity 中代码
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startService = findViewById(R.id.start_service);
Button stopService = findViewById(R.id.stop_services);
startService.setOnClickListener(this);
stopService.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.start_service:
Intent startIntent=new Intent(this,MyService.class);
//开启服务
startService(startIntent);
break;
case R.id.stop_services:
Intent stopIntent=new Intent(this,MyService.class);
//结束服务
stopService(stopIntent);
break;
default:
break;
}
}
}
xml 中代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/start_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start Service"/>
<Button
android:layout_marginTop="10dp"
android:id="@+id/stop_service"
android:layout_width="match_parent"
android:layout_height="w