Android Service彻底解析,关于服务你所需知道的一切(上)

Service的基本用法


关于Service最基本的用法天然就是如何启动一个Service了,启动Service的方法和启动Activity很相似,都须要借助Intent来实现,下面咱们就经过一个具体的例子来看一下。python

新建一个Android项目,项目名就叫ServiceTest,这里我选择使用4.0的API。android

 

而后新建一个MyService继承自Service,并重写父类的onCreate()、onStartCommand()和onDestroy()方法,以下所示:面试

public class MyService extends Service { public static final String TAG = "MyService"; @Override public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate() executed"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "onStartCommand() executed"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy() executed"); } @Override public IBinder onBind(Intent intent) { return null; } }

 

能够看到,咱们只是在onCreate()、onStartCommand()和onDestroy()方法中分别打印了一句话,并无进行其它任何的操做。服务器

 

而后打开或新建activity_main.xml做为程序的主布局文件,代码以下所示:app

<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:id="@+id/start_service" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Start Service" />
 
    <Button android:id="@+id/stop_service" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Stop Service" />
 
</LinearLayout>

 

咱们在布局文件中加入了两个按钮,一个用于启动Service,一个用于中止Service。框架

 

而后打开或新建MainActivity做为程序的主Activity,在里面加入启动Service和中止Service的逻辑,代码以下所示:ide

public class MainActivity extends Activity implements OnClickListener { private Button startService; private Button stopService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startService = (Button) findViewById(R.id.start_service); stopService = (Button) findViewById(R.id.stop_service); startService.setOnClickListener(this); stopService.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.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; } } }

 

能够看到,在Start Service按钮的点击事件里,咱们构建出了一个Intent对象,并调用startService()方法来启动MyService。而后在Stop Serivce按钮的点击事件里,咱们一样构建出了一个Intent对象,并调用stopService()方法来中止MyService。代码的逻辑很是简单,相信不须要我再多作解释了吧。 布局

 

另外须要注意,项目中的每个Service都必须在AndroidManifest.xml中注册才行,因此还须要编辑AndroidManifest.xml文件,代码以下所示:学习

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.servicetest" android:versionCode="1" android:versionName="1.0" >
 
    <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="17" />
 
    <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > …… <service android:name="com.example.servicetest.MyService" >
        </service>
    </application>
 
</manifest>

 

这样的话,一个简单的带有Service功能的程序就写好了,如今咱们将程序运行起来,并点击一下Start Service按钮,能够看到LogCat的打印日志以下:测试

 

 

 

也就是说,当启动一个Service的时候,会调用该Service中的onCreate()和onStartCommand()方法。

 

那么若是我再点击一次Start Service按钮呢?这个时候的打印日志以下:

 

 

 

能够看到,此次只有onStartCommand()方法执行了,onCreate()方法并无执行,为何会这样呢?这是因为onCreate()方法只会在Service第一次被建立的时候调用,若是当前Service已经被建立过了,无论怎样调用startService()方法,onCreate()方法都不会再执行。所以你能够再多点击几回Start Service按钮试一次,每次都只会有onStartCommand()方法中的打印日志。

 

咱们还能够到手机的应用程序管理界面来检查一下MyService是否是正在运行,以下图所示:

 

 

 

恩,MyService确实是正在运行的,即便它的内部并无执行任何的逻辑。

 

回到ServiceTest程序,而后点击一下Stop Service按钮就能够将MyService中止掉了。

 

Service和Activity通讯


上面咱们学习了Service的基本用法,启动Service以后,就能够在onCreate()或onStartCommand()方法里去执行一些具体的逻辑了。不过这样的话Service和Activity的关系并不大,只是Activity通知了Service一下:“你能够启动了。”而后Service就去忙本身的事情了。那么有没有什么办法能让它们俩的关联更多一些呢?好比说在Activity中能够指定让Service去执行什么任务。固然能够,只须要让Activity和Service创建关联就行了。

 

观察MyService中的代码,你会发现一直有一个onBind()方法咱们都没有使用到,这个方法其实就是用于和Activity创建关联的,修改MyService中的代码,以下所示:

public class MyService extends Service { public static final String TAG = "MyService"; private MyBinder mBinder = new MyBinder(); @Override public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate() executed"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "onStartCommand() executed"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy() executed"); } @Override public IBinder onBind(Intent intent) { return mBinder; } class MyBinder extends Binder { public void startDownload() { Log.d("TAG", "startDownload() executed"); // 执行具体的下载任务
 } } }

 

这里咱们新增了一个MyBinder类继承自Binder类,而后在MyBinder中添加了一个startDownload()方法用于在后台执行下载任务,固然这里并非真正地去下载某个东西,只是作个测试,因此startDownload()方法只是打印了一行日志。

 

而后修改activity_main.xml中的代码,在布局文件中添加用于绑定Service和取消绑定Service的按钮:

<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:id="@+id/start_service" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Start Service" />
 
    <Button android:id="@+id/stop_service" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Stop Service" />
 
    <Button android:id="@+id/bind_service" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Bind Service" />
    
    <Button android:id="@+id/unbind_service" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Unbind Service"
        />
    
</LinearLayout>

 

接下来再修改MainActivity中的代码,让MainActivity和MyService之间创建关联,代码以下所示:

public class MainActivity extends Activity implements OnClickListener { private Button startService; private Button stopService; private Button bindService; private Button unbindService; private MyService.MyBinder myBinder; private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { } @Override public void onServiceConnected(ComponentName name, IBinder service) { myBinder = (MyService.MyBinder) service; myBinder.startDownload(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startService = (Button) findViewById(R.id.start_service); stopService = (Button) findViewById(R.id.stop_service); bindService = (Button) findViewById(R.id.bind_service); unbindService = (Button) findViewById(R.id.unbind_service); startService.setOnClickListener(this); stopService.setOnClickListener(this); bindService.setOnClickListener(this); unbindService.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.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()方法,这两个方法分别会在Activity与Service创建关联和解除关联的时候调用。在onServiceConnected()方法中,咱们又经过向下转型获得了MyBinder的实例,有了这个实例,Activity和Service之间的关系就变得很是紧密了。如今咱们能够在Activity中根据具体的场景来调用MyBinder中的任何public方法,即实现了Activity指挥Service干什么Service就去干什么的功能。

 

固然,如今Activity和Service其实还没关联起来了呢,这个功能是在Bind Service按钮的点击事件里完成的。能够看到,这里咱们仍然是构建出了一个Intent对象,而后调用bindService()方法将Activity和Service进行绑定。bindService()方法接收三个参数,第一个参数就是刚刚构建出的Intent对象,第二个参数是前面建立出的ServiceConnection的实例,第三个参数是一个标志位,这里传入BIND_AUTO_CREATE表示在Activity和Service创建关联后自动建立Service,这会使得MyService中的onCreate()方法获得执行,但onStartCommand()方法不会执行。

 

而后如何咱们想解除Activity和Service之间的关联怎么办呢?调用一下unbindService()方法就能够了,这也是Unbind Service按钮的点击事件里实现的逻辑。

如今让咱们从新运行一下程序吧,在MainActivity中点击一下Bind Service按钮,LogCat里的打印日志以下图所示:

 

 

 

另外须要注意,任何一个Service在整个应用程序范围内都是通用的,即MyService不只能够和MainActivity创建关联,还能够和任何一个Activity创建关联,并且在创建关联时它们均可以获取到相同的MyBinder实例。

 

如何销毁Service


在Service的基本用法这一部分,咱们介绍了销毁Service最简单的一种状况,点击Start Service按钮启动Service,再点击Stop Service按钮中止Service,这样MyService就被销毁了,能够看到打印日志以下所示:

 

 

 

那么若是咱们是点击的Bind Service按钮呢?因为在绑定Service的时候指定的标志位是BIND_AUTO_CREATE,说明点击Bind Service按钮的时候Service也会被建立,这时应该怎么销毁Service呢?其实也很简单,点击一下Unbind Service按钮,将Activity和Service的关联解除就能够了。

 

先点击一下Bind Service按钮,再点击一下Unbind Service按钮,打印日志以下所示:

 

 

 

以上这两种销毁的方式都很好理解。那么若是咱们既点击了Start Service按钮,又点击了Bind Service按钮会怎么样呢?这个时候你会发现,无论你是单独点击Stop Service按钮仍是Unbind Service按钮,Service都不会被销毁,必要将两个按钮都点击一下,Service才会被销毁。也就是说,点击Stop Service按钮只会让Service中止,点击Unbind Service按钮只会让Service和Activity解除关联,一个Service必需要在既没有和任何Activity关联又处理中止状态的时候才会被销毁。

 

为了证明一下,咱们在Stop Service和Unbind Service按钮的点击事件里面加入一行打印日志:

public void onClick(View v) { switch (v.getId()) { case R.id.start_service: Intent startIntent = new Intent(this, MyService.class); startService(startIntent); break; case R.id.stop_service: Log.d("MyService", "click Stop Service button"); 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: Log.d("MyService", "click Unbind Service button"); unbindService(connection); break; default: break; } }

 

而后从新运行程序,先点击一下Start Service按钮,再点击一下Bind Service按钮,这样就将Service启动起来,并和Activity创建了关联。而后点击Stop Service按钮后Service并不会销毁,再点击一下Unbind Service按钮,Service就会销毁了,打印日志以下所示:

 

 

 

咱们应该始终记得在Service的onDestroy()方法里去清理掉那些再也不使用的资源,防止在Service被销毁后还会有一些再也不使用的对象仍占用着内存。

 

Service和Thread的关系


很多Android初学者均可能会有这样的疑惑,Service和Thread到底有什么关系呢?何时应该用Service,何时又应该用Thread?答案可能会有点让你吃惊,由于Service和Thread之间没有任何关系!

 

之因此有很多人会把它们联系起来,主要就是由于Service的后台概念。Thread咱们你们都知道,是用于开启一个子线程,在这里去执行一些耗时操做就不会阻塞主线程的运行。而Service咱们最初理解的时候,总会以为它是用来处理一些后台任务的,一些比较耗时的操做也能够放在这里运行,这就会让人产生混淆了。可是,若是我告诉你Service实际上是运行在主线程里的,你还会以为它和Thread有什么关系吗?让咱们看一下这个残酷的事实吧。

 

 

在MainActivity的onCreate()方法里加入一行打印当前线程id的语句:

Log.d("MyService", "MainActivity thread id is " + Thread.currentThread().getId());

 

而后在MyService的onCreate()方法里也加入一行打印当前线程id的语句:

Log.d("MyService", "MyService thread id is " + Thread.currentThread().getId());

 

如今从新运行一下程序,并点击Start Service按钮,会看到以下打印日志:

 

 

能够看到,它们的线程id彻底是同样的,由此证明了Service确实是运行在主线程里的,也就是说若是你在Service里编写了很是耗时的代码,程序一定会出现ANR的。

 

你可能会惊呼,这不是坑爹么!?那我要Service又有何用呢?其实你们不要把后台和子线程联系在一块儿就好了,这是两个彻底不一样的概念。Android的后台就是指,它的运行是彻底不依赖UI的。即便Activity被销毁,或者程序被关闭,只要进程还在,Service就能够继续运行。好比说一些应用程序,始终须要与服务器之间始终保持着心跳链接,就可使用Service来实现。你可能又会问,前面不是刚刚验证过Service是运行在主线程里的么?在这里一直执行着心跳链接,难道就不会阻塞主线程的运行吗?固然会,可是咱们能够在Service中再建立一个子线程,而后在这里去处理耗时逻辑就没问题了。

 

额,既然在Service里也要建立一个子线程,那为何不直接在Activity里建立呢?这是由于Activity很难对Thread进行控制,当Activity被销毁以后,就没有任何其它的办法能够再从新获取到以前建立的子线程的实例。并且在一个Activity中建立的子线程,另外一个Activity没法对其进行操做。可是Service就不一样了,全部的Activity均可以与Service进行关联,而后能够很方便地操做其中的方法,即便Activity被销毁了,以后只要从新与Service创建关联,就又可以获取到原有的Service中Binder的实例。所以,使用Service来处理后台任务,Activity就能够放心地finish,彻底不须要担忧没法对后台任务进行控制的状况。

 

一个比较标准的Service就能够写成:

 

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
	new Thread(new Runnable() {
		@Override
		public void run() {
			// 开始执行后台任务
		}
	}).start();
	return super.onStartCommand(intent, flags, startId);
}
 
class MyBinder extends Binder {
 
	public void startDownload() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				// 执行具体的下载任务
			}
		}).start();
	}
 
}

 

建立前台Service


Service几乎都是在后台运行的,一直以来它都是默默地作着辛苦的工做。可是Service的系统优先级仍是比较低的,当系统出现内存不足状况时,就有可能会回收掉正在后台运行的Service。若是你但愿Service能够一直保持运行状态,而不会因为系统内存不足的缘由致使被回收,就能够考虑使用前台Service。前台Service和普通Service最大的区别就在于,它会一直有一个正在运行的图标在系统的状态栏显示,下拉状态栏后能够看到更加详细的信息,很是相似于通知的效果。固然有时候你也可能不只仅是为了防止Service被回收才使用前台Service,有些项目因为特殊的需求会要求必须使用前台Service,好比说墨迹天气,它的Service在后台更新天气数据的同时,还会在系统状态栏一直显示当前天气的信息,以下图所示:

 

 

那么咱们就来看一下如何才能建立一个前台Service吧,其实并不复杂,修改MyService中的代码,以下所示:

public class MyService extends Service {
 
	public static final String TAG = "MyService";
 
	private MyBinder mBinder = new MyBinder();
 
	@Override
	public void onCreate() {
		super.onCreate();
		Notification notification = new Notification(R.drawable.ic_launcher,
				"有通知到来", System.currentTimeMillis());
		Intent notificationIntent = new Intent(this, MainActivity.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
				notificationIntent, 0);
		notification.setLatestEventInfo(this, "这是通知的标题", "这是通知的内容",
				pendingIntent);
		startForeground(1, notification);
		Log.d(TAG, "onCreate() executed");
	}
 
	.........
 
}

 

这里只是修改了MyService中onCreate()方法的代码。能够看到,咱们首先建立了一个Notification对象,而后调用了它的setLatestEventInfo()方法来为通知初始化布局和数据,并在这里设置了点击通知后就打开MainActivity。而后调用startForeground()方法就可让MyService变成一个前台Service,并会将通知的图片显示出来。

 

如今从新运行一下程序,并点击Start Service或Bind Service按钮,MyService就会之前台Service的模式启动了,而且在系统状态栏会弹出一个通栏图标,下拉状态栏后能够看到通知的详细内容,以下图所示。

 

 

但愿本文对你有所帮助~~若是对软件测试、接口测试、自动化测试、面试经验交流感兴趣能够加入咱们。642830685,免费领取最新软件测试大厂面试资料和Python自动化、接口、框架搭建学习资料!技术大牛解惑答疑,同行一块儿交流。

相关文章
相关标签/搜索