Android Foreground Service

为了防止后台服务被系统干掉,我们需要将服务提升为前台服务。

示例代码:

需要在AndroidManifest 添加 前台服务的权限 :
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

FOREGROUND_SERVICE
Added in API level 28 Android 9.0
public static final String FOREGROUND_SERVICE
Allows a regular application to use Service.startForeground.
Protection level: normal
Constant Value: android.permission.FOREGROUND_SERVICE
public class SampleService extends Service {

    public static final String CHANNEL_ID = "com.github.103style.SampleService";
    public static final String CHANNEL_NAME = "com.github.103style";

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        registerNotificationChannel();
        int notifyId = (int) System.currentTimeMillis();
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID);
        mBuilder
                //必须要有
                .setSmallIcon(R.mipmap.ic_launcher)
                //可选
                //.setSound(null)
                //.setVibrate(null)
                //...
        ;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            mBuilder.setContentTitle(getResources().getString(R.string.app_name));
        }
        startForeground(notifyId, mBuilder.build());
    }

    /**
     * 注册通知通道
     */
    private void registerNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationChannel notificationChannel = mNotificationManager.getNotificationChannel(CHANNEL_ID);
            if (notificationChannel == null) {
                NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                        CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
                //是否在桌面icon右上角展示小红点
                channel.enableLights(true);
                //小红点颜色
                channel.setLightColor(Color.RED);
                //通知显示
                channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
                //是否在久按桌面图标时显示此渠道的通知
                //channel.setShowBadge(true);
                mNotificationManager.createNotificationChannel(channel);
            }
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、如何保活后台服务 在Android Services (后台服务) 里面,我们了解了Android四大组件之一...
    罐头过期阅读 5,633评论 0 1
  • 转载注明出处:http://www.jianshu.com/p/a1d3d9693e91 1. 简介 与前一篇An...
    王三的猫阿德阅读 1,979评论 1 9
  • 为了面试,为了高工资,废话不多说,不定期更新。 1. Activity正常和异常情况下的生命周期分析。 Activ...
    24K男阅读 853评论 0 0
  • 2018.3.23 哈尔滨363期 努力一组 【日精进打卡第136天】 【知-学习】 日常背诵《六项精进》、《大学...
    jszhufeng阅读 89评论 0 0
  • 多图预警,建议在Wifi下打开,土豪随意~ 对于全图型PPT,常常需要在图上搭配一定的说明文字 如果图片本来就有大...
    好PPT阅读 1,219评论 4 49