Blog of CodeJELLOW’S ENGINEERING NOTES
← 返回文章

Android JetPack学习总结(二十一)

Android JetPack学习总结(二十一) Service(二) 前台服务ForeGround

Service(二) 前台服务ForeGround

在安卓9之后创建前台服务需要申请权限:

TEXT
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

创建前台服务的过程和之前创建后台服务的过程类似,只不过要在onCreate方法中加上一个方法:

TEXT
startForeground()

具体设置过程如下:

TEXT
Notification notification=new NotificationCompat        .Builder(MyService.this,"fdasf")        .setSmallIcon(R.drawable.ic_android_black_24dp)        .setContentTitle("this is a title")        .setContentText("this is a notification")        .build();startForeground(1,notification);

其中第一个参数是id(不能为0),第二个参数是一个通知.

在notification的设置中,Builder的第二个参数不能是一个任意的字符串,否则会爆出Bad notification for startForeground的错误,必须要创建一个真实的channelId:

TEXT
@Override
public void onCreate() {
    ...
    createNotificationChannel();
    Notification notification=new NotificationCompat
            .Builder(MyService.this,CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_android_black_24dp)
            .setContentTitle("this is a title")
            .setContentText("this is a notification")
            .build();
    startForeground(1,notification);
}

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "my notification channel";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

触摸通知以触发事件:

TEXT
PendingIntent pendingIntent=PendingIntent.getActivity(        MyService.this,        0,        new Intent(MyService.this,MainActivity.class),        0);Notification notification=new NotificationCompat        .Builder(MyService.this,CHANNEL_ID)        .setSmallIcon(R.drawable.ic_android_black_24dp)        .setContentTitle("this is a title")        .setContentText("this is a notification")        .setContentIntent(pendingIntent)        .build();startForeground(1,notification);

在manifest中设置以保证一个activity只会被创建一次:

TEXT
android:launchMode="singleInstance"
通过 RSS 订阅更新 →