一、服务是什么?
服务( Service )是Android中实现程序后台运行的解决方案,它非常适合去执行那些不需要和用户交互而且还要求长期运行的任务。
服务的运行不依赖于任何用户界面,即使程序被切换到后台,或者用户打开了另外一个应用程序,服务仍然能够保持正常运行。
不过需要注意的是,服务并不是运行在一个独立的进程当中的,而是依赖于创建服务时所在的应用程序进程。当某个应用程序进程被杀掉时,所有依赖于该进程的服务也会停止运行。
另外,也不要被服务的后台概念所迷惑,实际上服务并不会自动开启线程,所有的代码都是默认运行在主线程当中的。也就是说,我们需要在服务的内部手动创建子线程,并在这里执行具体的任务,否则就有可能出现主线程被阻塞住的情况。
二、定义一个服务
2.1、新建一个ServiceTest项目
2.2、建立一个MyService服务
右击com.example.servicetest→New→Service→Service, 会弹出如下窗口。
2.3、观察MyService代码
package com.example.servicetest;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class MyService extends Service {
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
可以看到,MyService 是继承自Service类的,说明这是一个服务。
有一个onBind()方法。这个方法是Service中唯一的一 个抽象方法 ,所以必须要在子类里实现。
既然是定义一个服务,自然应该在服务中去处理一些事情了,那处理事情的逻辑应该写在哪里呢?
这时就可以重写Service 中的另外一些方法了,如下所示:
package com.example.servicetest;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class MyService extends Service {
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
可以看到,这里重写了onCreate() 、onStartCommand( )和onDestroy()这3个方法,它们是每个服务中最常用到的3个方法了。
其中onCreate( )方法会在服务创建的时候调用,
onStartCommand()方法会在每次服务启动的时候调用,onDestroy() 方法会在服务销毁的时候调用。
通常情况下,如果我们希望服务一旦启动就立刻去执行某个动作,就可以将逻辑写在onStartCommand()方法里。
而当服务销毁时,我们又应该在onDestroy()方法中去回收那些不再使用的资源。
另外需要注意,每一个服务都需要在AndroidManifest.xml文件中进行注册才能生效。这是Android四大组件共有的特点。
不过,智能的Android Studio早已自动帮我们将这一步完成了 。
打开AndroidManifest.xml ,代码如下所示:
这样的话,就已经将一个服务完全定义好了。
三、启动和停止服务
定义好了服务之后,接下来就应该考虑如何去启动以及停止这个服务。
启动和停止的方法,主要是借助Intent来实现的。
首先修改activity_ main.xml 中的代码,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/start_service"
android:text="Start Service"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/stop_service"
android:text="Stop Service"/>
</LinearLayout>
这里我们在布局文件中加入了两个按钮,分别是用于启动服务和停止服务的。
然后修改MainActivity中的代码,如下所示:
package com.example.servicetest;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startService = (Button) findViewById(R.id.start_service);
Button stopService = (Button) findViewById(R.id.stop_service);
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_service:
Intent stopIntent = new Intent(this , MyService.class);
stopService(stopIntent);//停止服务
break;
default:
break;
}
}
}
可以看到,这里在onCreate()方法中分别获取到了StartService按钮和Stop Service按钮的实例,并给它们注册了点击事件。
然后在Start Service按钮的点击事件里,构建出了一个Intent对象,并调用startService()方法来启动MyService这个服务。
在Stop Serivce按钮的点击事件里,同样构建出了一个Intent对象,并调用stopService( )方法来停止MyService这个服务。
startService()和 stopService( )方法都是定义在Context 类中的,所以在活动里可以直接调用这两个方法。
注意,这里完全是由活动来决定服务何时停止的,如果没有点
击Stop Service 按钮,服务就会一直处于运行状态。
那服务有没有什么办法让自已停止下来呢?
只需要在MyService的任何一个位置调用stopSelf()方法 就能让这个服务停止下来了。
在MyService的几个方法中加入打印日志,证实服务已经成功启动或者停止,如下所示:
package com.example.servicetest;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
Log.d("MyService" , "onCreate executed");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MyService" , "onStartCommand executed");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.d("MyService" , "onDestroy executed");
super.onDestroy();
}
}
运行程序进行测试,点击Start Service按钮:
点击Stop Service按钮:
onCreate()方法和onStartCommand( )方法到底有什么区别?
因为刚刚点击Start Service按钮后两个方法都执行了。其实onCreate()方法是在服务第一次创建的时候调用的,而onStartCommand( )方法则在每次启动服务的时候都会调用,由于刚才我们是第一次点击Start Service按钮,服务此时还未创建过,所以两个方法都会执行,之后如果再连续多点击几次Start Service 按钮,就会发现只有onStartCommand()方法可以得到执行了。
四、活动和服务进行通信
虽然服务是在活动里启动的,但在启动了服务之后,活动与服务基本就没有什么关系了。
在活动里调用了startService()方法来启 动MyService 这个服务,然后MyService 的onCreate()和onStartCommand( )方法就会得到执行。之后服务会一直处于运行状态,但具体运行的是什么逻辑,活动就控制不了了。
这就类似于活动通知了服务一下:“你可以启动了!”然后服务就去忙自己的事情了,但活动并不知道服务到底去做了什么事情,以及完成得如何。
那么有没有什么办法能让活动和服务的关系更紧密一些呢?
例如在活动中指挥服务去干什么,服务就去干什么。当然可以,这就需要借助onBind()方法了。
比如说,目前我们希望在MyService里提供一个下载功能,然后在活动中可以决定何时开始下载,以及随时查看下载进度。实现这个功能的思路是创建一个专门的Binder对象来对下载功
能进行管理。
修改MyService中的代码,如下所示:
package com.example.servicetest;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
private DownloadBinder mBinder = new DownloadBinder();
class DownloadBinder extends Binder{
public void startDownload(){
Log.d("Myservice" , "startDownload executed");
}
public int getProgress(){
Log.d("MyService" , "getProgress executed");
return 0;
}
}
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onCreate() {
Log.d("MyService" , "onCreate executed");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MyService" , "onStartCommand executed");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.d("MyService" , "onDestroy executed");
super.onDestroy();
}
}
这里我们新建了一个DownloadBinder类,并让它继承自Binder,然后在它的内部提供了开始下载以及查看下载进度的方法。
当然这只是两个模拟方法,并没有实现真正的功能,我们在这两个方法中分别打印了一行日志。
接着,在MyService中创建了DownloadBinder的实例,然后在onBind()方法里返回了这个实例,这样MyService中的工作就全部完成了。
在布局文件里新增两个按钮,修改activity_ main.xml中的代码,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/start_service"
android:text="Start Service"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/stop_service"
android:text="Stop Service"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/bind_service"
android:text="Bind Service"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/unbind_service"
android:text="Unbind Service"/>
</LinearLayout>
这两个按钮分别是用于绑定服务和取消绑定服务的,然后通过
活动来去和服务绑定。
当一个活动和服务绑定了之后,就可以调用该服务里的Binder提供的方法了。
修改MainActivity中的代码,如下所示:
package com.example.servicetest;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private MyService.DownloadBinder downloadBinder;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
downloadBinder = (MyService.DownloadBinder)iBinder;
downloadBinder.startDownload();
downloadBinder.getProgress();
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startService = (Button) findViewById(R.id.start_service);
Button stopService = (Button) findViewById(R.id.stop_service);
startService.setOnClickListener(this);
stopService.setOnClickListener(this);
Button bindService = (Button) findViewById(R.id.bind_service);
Button unbindService = (Button) findViewById(R.id.unbind_service);
bindService.setOnClickListener(this);
unbindService.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_service:
Intent stopIntent = new Intent(this , MyService.class);
stopService(stopIntent);//停止服务
break;
case R.id.bind_service:
Intent bindIntent = new Intent(this , MyService.class);
bindService(bindIntent , connection , BIND_AUTO_CREATE);//绑定服务
break;
case R.id.unbind_service:
unbindService(connection);//解绑服务
break;
default:
break;
}
}
}
,这里我们首先创建了一个ServiceConnection 的匿名类,在里面重写了onServiceConnected( )方法和onServiceDisconnected()方法,这两个方法分别会在活动与
服务成功绑定以及解除绑定的时候调用。
在onServiceConnected()方法中,又通过向下转型得到了DownloadBinder的实例,有了这个实例,活动和服务之间的关系就变得非常紧密了。
现在可以在活动中根据具体的场景来调用DownloadBinder中的任何public()方法,即实现了指挥服务干什么服务就去干什么的功能。这里仍然只是做了个简单的测试,在onServiceConnected()方法中调用了DownloadBinder 的startDownload ()和getProgress()方法。
当然,现在活动和服务其实还没进行绑定,这个功能是在Bind Service按钮的点击事件里完成的。
可以看到,这里仍然是构建出了一个Intent对象,然后调用bindService()方法.将MainActivity和MyService进行绑定。
bindService()方法接收3个参数,第一个参数就是刚刚构建出的Intent对象,第二个参数是前面创建出的ServiceConnection的实例,第三个参数则是一个标志位,这里传人BIND_ AUTO_ CREATE 表示在活动和服务进行绑定后自动创建服务。
这会使得MyService中的onCreate ()方法得到执行,但onStartCommand( )方法不会执行。
然后如果我们想解除活动和服务之间的绑定,就调用一下unbindService()方法就可以了,这也是Unbind Service按钮的点击事件里实现的功能。
重新运行一下程序,点击Bind Service按钮,效果如下:
可以看到,首先是MyService 的onCreate()方法得到了执行,然后startDownload ( )和getProgress ()方法都得到了执行,说明确实已经在活动里成功调用了服务里提供的方法了。
另外需要注意,任何一个服务在整个应用程序范围内都是通用的,即MyService不仅可以和MainActivity绑定,还可以和任何一个其他的活动进行绑定,而且在绑定完成后它们都可以获取到相同的DownloadBinder实例。