您的位置:首页 > 其它

service介绍之IntentService与Notification前台通知

2015-12-05 23:36 489 查看
service介绍之IntentService与Notification前台通知
  注明转载

  前面介绍了service的一般使用,在文章最后提到一般要在service里面启动线程去执行具体操作,这种情况下我们要调用stopService方法才能关闭Service,或者在线程中调用stopSelf()方法,但是程序员往往会忘了做这两件事情,从而导致service没有关闭或者主线程阻塞

android为我们提供了一个IntentService,来替我们默认创建一个子线程,同时在线程执行完毕以后,主动结束service

  注意IntentService是一个继承了Service的抽象类

 下面是一个简单的例子

import android.app.IntentService;
import android.content.Intent;

public class MyIntentService extends IntentService {

public MyIntentService(String name) {
super(name);
}

@Override
protected void onHandleIntent(Intent intent) {
/**
* 在这里具体操作,而不用担心线程阻塞的问题
* 因为已经android已经为之创建子线程了
*/

}

}
  创建好IntentService以后,我们就看startService()来正常启动这个服务了。

可以看出,具体的操作是在onHandleIntent方法里面,而在这个方法里面执行的操作,已经是在另外一个线程了,所以我们不必担心主线程阻塞的问题。另外由于IntentService继承自抽象类Service,并且实现了它的onBind()方法(返回null),所以我们可以不必实现onBind()方法,但是我们要实现onHandleIntent方法

  IntentService的使用很简单,接下来我们分析一下它的原理,看源码

@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 + "]");
thread.start();
//获取子线程的looper(每个线程都有一个looper)
mServiceLooper = thread.getLooper();
//将lopper设置给handler
mServiceHandler = new ServiceHandler(mServiceLooper);
}


  从上面代码可以看出,在IntentService创建的过程中,我们就已经开启了一个子线程,并且把这个子线程交给一个handler去处理

  在onstart()方法中,我们把启动service的intent信息交给handler处理

@Override
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}


接下来我们来看看这个handler内部类

private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}

@Override
public void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
}


  所以是这样的,handler的hanleMessage()方法里面调用了IntentService的onHandleIntent()方法,所以我们只要在这个方法里面写具体实现就相当于在子线程中写了!

  接下来我们再介绍一个service常见的使用,notification前台通知

直接看代码。

public class MyService extends Service {

/**
* 在服务创建是调用
*/
@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);
}
}


  所谓前台service,就是其是可视的,所以android系统不会将之回收,类似下图

  创建前台service的方法跟创建notification的方法类似,只是需要调用startForeground()方法来启动这个通知

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: