android-update前台服务文本

ar7v8xwq  于 2021-07-06  发布在  Java
关注(0)|答案(0)|浏览(341)

首先,我阅读了如何在android中更新前台服务的通知文本?给出了第二个答案(@luca manzo)。我知道一般的想法是使用notificationmanager.notify,而不是从头开始,但我不知道如何在我的代码中应用它,因为它与那个示例有点不同。
我已创建此服务:

public class servizioForeground extends Service {

@Override
public  int onStartCommand(Intent intent, int flags, int startId) {
    createNotificationChannel();

    Intent intent1 = new Intent(this,MainActivity.class);

    PendingIntent pendingIntent = PendingIntent.getActivity (this,0,intent1,0);

    Notification notification = new NotificationCompat.Builder(this, "ChannelID1").setContentTitle("Title").setContentText("Text").setSmallIcon(R.mipmap.ic_launcher).setContentIntent(pendingIntent).build();

    startForeground(1,notification);

    return START_STICKY;
}

private void createNotificationChannel() {

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel NotificationChannel = new NotificationChannel("ChannelID1", "foreground notification", NotificationManager.IMPORTANCE_DEFAULT);

        NotificationManager manager = getSystemService(NotificationManager.class);
        manager.createNotificationChannel(NotificationChannel);
    }
}

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

@Override
public void onDestroy() {
    stopForeground(true);
    stopSelf();
    super.onDestroy();
}

}
关于我的主要活动:

Intent intent = new Intent(this, servizioForeground.class);

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        startForegroundService(intent);
    }
    else {
        startService(intent);
    }

我尝试使用此代码执行此操作,但不确定是否正确:

NotificationChannel NotificationChannel = new NotificationChannel("ChannelID1", "foreground notification", NotificationManager.IMPORTANCE_DEFAULT);

                NotificationManager manager = getSystemService(context, NotificationManager.class);
                manager.createNotificationChannel(NotificationChannel);

                Intent intent1 = new Intent(context,MainActivity.class);

                PendingIntent pendingIntent = PendingIntent.getActivity (context,0,intent1,0);

                Notification notification = new NotificationCompat.Builder(context, "ChannelID1").setContentTitle("New name").setContentText("New text").setSmallIcon(R.mipmap.ic_launcher).setContentIntent(pendingIntent).build();

有人能给我一些提示吗?提前谢谢你的帮助

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题