简体   繁体   中英

Using startForeground with android service

I have found this Question : How to use startForeground? in Stackoverflow and as it says in the command from the top answer the notification constructor and setLastEventInfo is deprecated. I know that's a duplicated post but the other post is 4 years old and has no answer in the commends so I thought i try do ask it again maybe someone can help me with this.

Code:

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);

You can use this method. Now with latest API versions you need to set channel for notifications.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM