Android基础Service高级用法

前台服务:

后台服务优先级比较低,可能会被回收。所以有前台服务,既显示在状态栏的服务。
只要修改Service的onCreate方法即可:

@Override
    public void onCreate() {
        super.onCreate();
        Intent notificationIntent=new Intent(this,MainActivity.class);
        PendingIntent pendingIntent= PendingIntent.getActivity(this,0,notificationIntent,0);
        Notification.Builder builder = new Notification.Builder(this);
        Notification notification=builder.setContentIntent(pendingIntent)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setWhen(System.currentTimeMillis()).setAutoCancel(false)
                .setContentTitle("statusContentTitle").setContentText("statusContentContext").build();
        startForeground(1,notification);
        Log.d("Service","onCreate Service");
    }

其实就是创建通知的形式,不过这里使用 startForeground(1,notification);来显示的。
测试:
这里写图片描述

使用IntentService

service里面可以开启子线程,并调用stopService停止服务。
但是这种方法如果忘记关闭线程会堵塞主线程。
使用IntentService就能解决问题:

IntentService是继承于Service并处理异步请求的一个类,在IntentService内有一个工作线程来处理耗时操作,启动IntentService的方式和启动传统Service一样,同时,当任务执行完后,IntentService会自动停止,而不需要我们去手动控制。另外,可以启动IntentService多次,而每一个耗时操作会以工作队列的方式在IntentService的onHandleIntent回调方法中执行,并且,每次只会执行一个工作线程,执行完第一个再执行第二个,以此类推。
而且,所有请求都在一个单线程中,不会阻塞应用程序的主线程(UI Thread),同一时间只处理一个请求。

也就是说,IntentService自己就是一个子线程,和主线程不在同一线程下运行。
使用方法,和Service雷同,只是继承IntentService。

发布了85 篇原创文章 · 获赞 40 · 访问量 24万+

猜你喜欢

转载自blog.csdn.net/lw_zhaoritian/article/details/52488835