在Android服务中使用startForeground

时间:2018-07-11 06:14:47

标签: java android

我在Stackoverflow中发现了这个问题:How to use startForeground?,正如它在顶部回答命令中所说的那样,通知构造函数和setLastEventInfo已被弃用。我知道那是重复的帖子,但另一篇帖子已经有4年历史了,在表彰中没有答案,所以我想我想再问一次,也许有人可以帮我解决这个问题。

代码:

Notification note = new Notification(R.drawable.ic_launcher,
        "Foreground Service notification?", System.currentTimeMillis());
Intent i = new Intent(this, CurrentActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
        | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
Date dateService=new Date(System.currentTimeMillis());
String dateString=dateService.toString().split(" ")[1]+" "+dateService.toString().split(" ")[2]+" "+dateService.toString().split(" ")[3];
note.setLatestEventInfo(this, "Foreground service",
        "Now foreground service running: "+dateString, pi);
note.flags |= Notification.FLAG_AUTO_CANCEL;

startForeground(2337, note);

1 个答案:

答案 0 :(得分:2)

您可以使用此方法。现在,使用最新的API版本,您需要设置通知渠道。

private static final String NOTIFICATION_CHANNEL_ID ="notification_channel_id";
private static final String NOTIFICATION_Service_CHANNEL_ID = "service_channel";
.....
private void startInForeground() {
    int icon = R.mipmap.icon;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
        icon = R.mipmap.icon_transparent;
    }

    Intent notificationIntent = new Intent(this, CurrentActivity.class);
    PendingIntent pendingIntent=PendingIntent.getActivity(this,0,notificationIntent,0);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
        .setSmallIcon(icon)
        .setContentIntent(pendingIntent)
        .setContentTitle("Service")
        .setContentText("Running...");
    Notification notification=builder.build();
    if(Build.VERSION.SDK_INT>=26) {
        NotificationChannel channel = new NotificationChannel(NOTIFICATION_Service_CHANNEL_ID, "Sync Service", NotificationManager.IMPORTANCE_HIGH);
        channel.setDescription("Service Name");
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(channel);

        notification = new Notification.Builder(this,NOTIFICATION_Service_CHANNEL_ID)
            .setContentTitle("Service")
            .setContentText("Running...")
            .setSmallIcon(icon)
            .setContentIntent(pendingIntent)
            .build();
    }
    startForeground(121, notification);
}