android service bind与start,Android Start Service与Bind Service启动Service的异同,IntentService详解...

1.什么是Service

Service是Android四大组件之一,是系统服务。Service是运行在后台的服务,与Activity相比,Service不能与用户进行交互。Service和Activity一样有自己的生命周期,需要在AndroidManifest.xml中注册后才能使用。Service的生命周期与Activity有所不同,Service有两种启动方式即start Service和bind Service,用不同的方式启动Service,其生命周期有明显差异。

2.Service的生命周期

onCreate创建Service

onStartCommand执行服务内容

onBind绑定服务

onUnBind解绑服务

onDestroy销毁服务

由于Service是在主线程运行的所以在他的生命周期函数里不能执行耗时操作

29d622ef646e

service生命周期.png

3.Service startService和bindService两种启动方式的差异

1.startService单次启动服务的生命周期的执行顺序是onCreate-->onStartCommand-->onDestroy,多次启动服务的生命周期的执行顺序是onCreate-->onStartCommand--。。。-->onStartCommand-->onDestroy。需要注意的是多次启动只会多次执行onStartCommand函数,而不会多次创建服务执行onCreate函数。

startService启动的Service与启动它的组件没有绑定关系,所以即使启动它的组件销毁了,Service依然在后台运行,除非在外部执行stopService或者在内部调用stopSlef函数销毁Service。而且由于没有绑定关系,Service与组件的通讯也受到限制,组件无法获得Service执行完毕的返回结果。

startService启动服务很简单,只需要下面两行代码就能搞定

Intent mIntent = new Intent(this, StartService.class);// StartService是继承Service的类

startService(mIntent);

**需要注意的是由于android8.0(API26)对后台运行做了限制,因此

如果处于后台时您的应用需要创建一个前台 Service,请使用 startForegroundService()。

如果 Service 容易引起用户注意,请将其设置为前台 Service。 例如,播放音频的 Service 始终应为前台 Service。 使用 startForegroundService()。**

2.bindService启动服务的生命周期的执行顺序是onCreate-->onBind-->onUnBind-->onDestroy,与startService相比多次执行bindService启动Service并不会多次执行onBind函数。

bindService启动的Service相对来说要复杂一些。Service里需要一个Binder内部类与绑定的组件通信,在onBind函数里return这个Binder实例。bindService启动Service的时候还需要有一个ServiceConnection内部类监听绑定状态。ServiceConnection类里有两个函数,当绑定时调用onServiceConnected,解绑时调用onServiceDisconnected,其中onServiceConnected接收一个IBinder类型的参数,这个参数实际上就是Service里的Binder实例,通过这个参数就能获得Service实例。

下面是BindService的代码

package com.text.demo.com.text.service;

import android.app.Service;

import android.content.Intent;

import android.os.Binder;

import android.os.IBinder;

import android.util.Log;

public class BindService extends Service {

private final static String TAG ="zxqBindService";

public BindService(){

}

// BindService中的Binder内部类

public class MyBinder extends Binder{

// 获取BindService实例

public BindService getService() {

return BindService.this;

}

}

private MyBinder binder = new MyBinder();

@Override

public void onCreate() {

super.onCreate();

Log.i(TAG,"onCreate");

}

@Override

public boolean onUnbind(Intent intent) {

Log.i(TAG,"onUnbind");

return false;

}

@Override

public IBinder onBind(Intent intent) {

Log.i(TAG,"onBind");

// 返回binder实例

return binder;

}

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

Log.i(TAG,"onStartCommand");

return START_NOT_STICKY;

}

@Override

public void onDestroy() {

super.onDestroy();

Log.i(TAG,"onDestroy");

}

}

下面是执行bindService的代码

package com.text.demo;

import android.content.ComponentName;

import android.content.Intent;

import android.content.ServiceConnection;

import android.os.Bundle;

import android.os.IBinder;

import android.support.v7.app.AppCompatActivity;

import android.util.Log;

import android.view.View;

import android.widget.Toast;

import com.text.demo.com.text.service.BindService;

import com.text.demo.com.text.service.StartService;

public class SecondActivity extends AppCompatActivity implements View.OnClickListener{

public SecondActivity(){

}

private boolean isBind = false;

private MyButton bindBtn;

private MyButton startBtn;

private BindService mBindService;

private BindService.MyBinder binder;

private static final String TAG = "zxq-SecondActivity";

private ServiceConnection cnn = new ServiceConnection(){

@Override

public void onServiceConnected(ComponentName name, IBinder service) {

isBind = true;

binder = (BindService.MyBinder)service;// 链接成功后获取到service里的binder实例

mBindService = binder.getService();// 通过binder获取service实例

Log.i(TAG,"onServiceConnected");

}

// 断开链接的时候调用

@Override

public void onServiceDisconnected(ComponentName name) {

isBind = false;

Log.i(TAG,"onServiceDisconnected");

}

};

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

Log.i(TAG,"onCreate");

setContentView(R.layout.activity_second);

bindBtn = findViewById(R.id.button1);

startBtn = findViewById(R.id.button2);

bindBtn.setOnClickListener(this);

startBtn.setOnClickListener(this);

}

@Override

public void onClick(View v) {

if(v.getId() == bindBtn.getId()){

// bindService的启动方式

Intent bindIntent = new Intent(this, BindService.class);

bindService(bindIntent,cnn,BIND_AUTO_CREATE);

Toast.makeText(SecondActivity.this,"bind Service",Toast.LENGTH_LONG).show();

}else if(v.getId() == startBtn.getId()){

// startService的启动方式

Intent mIntent = new Intent(this, StartService.class);

startService(mIntent);

Toast.makeText(SecondActivity.this,"start Service",Toast.LENGTH_LONG).show();

}

}

}

4.IntentService如何使用

上文提到Service是运行的主线程的,不能进行耗时操作,否则会出现ANR(Application not response)。当然我们也可以在Service中使用子线程去做耗时任务,但又有一个问题,如果有多个耗时任务,就需要启动多个子线程,那么多个子线程的执行顺序是怎样的,此时又需要一个线程队列管理这些子线程,这样虽然能满足需求,但实现起来太复杂了。为此Android提供了IntentService。

1.IntentService继承Service是一个抽象类,需要一个子类继承它并重写抽象函数onHandleIntent,在onHandle中可以处理多个耗时任务。

2.IntentService中有工作队列和工作线程,工作队列负责管理工作线程,当工作队列中所有的任务都执行完毕,IntentService会调用stopService自我销毁。

下面是IntentService的源码

public abstract class IntentService extends Service {

private volatile Looper mServiceLooper;

private volatile ServiceHandler mServiceHandler;

private String mName;

private boolean mRedelivery;

private final class ServiceHandler extends Handler {// 这是内部消息队列

public ServiceHandler(Looper looper) {

super(looper);

}

@Override

public void handleMessage(Message msg) {

onHandleIntent((Intent)msg.obj);// 在消息队列中执行onHandleIntent函数

stopSelf(msg.arg1);// 所有任务执行完毕后销毁Service

}

}

...

@Override

public void onCreate() {

// TODO: It would be nice to have an option to hold a partial wakelock

// during processing, and to have a static startService(Context, Intent)

// method that would launch the service & hand off a wakelock.

super.onCreate();

HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");// 创建IntentService的时候就创建一个工作子线程

thread.start();

mServiceLooper = thread.getLooper();// 获取线程的循环器

mServiceHandler = new ServiceHandler(mServiceLooper);// 创建消息队列

}

在IntentService中不需要重写onStartCommand,因为在IntentService源码用onStartCommand调用onStart函数发送消息。

@Override

public void onStart(@Nullable Intent intent, int startId) {

Message msg = mServiceHandler.obtainMessage();

msg.arg1 = startId;

msg.obj = intent;

mServiceHandler.sendMessage(msg);

}

/**

* You should not override this method for your IntentService. Instead,

* override {@link #onHandleIntent}, which the system calls when the IntentService

* receives a start request.

* @see android.app.Service#onStartCommand

*/

@Override

public int onStartCommand(@Nullable Intent intent, int flags, int startId) {

onStart(intent, startId);

return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;

}

5.Service如何保活

Service保活,即,让Service一直在后台运行。那么什么情况下Service会被系统干掉呢?

1.当APP退出时,Service会被系统干掉。

2.当内存不足,系统会将优先级较低的Service干掉,释放资源。

3.当用户手动清理内存时,Service可能会被干掉。

解决方案:

1.提高Service的优先级,Service优先级最高的是前台服务,可以在创建Service的时候调用startForeground函数提高优先级。

2.Android7.0版本以前,是可以通过双进程守护进行Service保活的,7.0及以后的版本,则很难保活了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值