0

我正在尝试在我的 android 应用程序中创建一个服务。该服务进一步启动前台服务。我试图确保当我单击此前台服务的此通知时,我被带到此通知的频道设置(用户可以轻松地禁用此频道的通知)。但这没有发生。相反,当我单击设置时会崩溃。我哪里错了?这是我使用的代码:

public class AlarmHandlerService extends Service {

        public NotificationCompat.Builder createNotification(String title, String content, String channel_id, int priority) {

    NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), channel_id)
            .setSmallIcon(R.drawable.notification_icon)
            .setContentTitle(title)
            .setContentText(content)
            .setPriority(priority);
    return builder;
}

    @Override
    public void onCreate() {
        super.onCreate();
        Intent i = new Intent(Settings
                .ACTION_CHANNEL_NOTIFICATION_SETTINGS)
                .putExtra(Settings.EXTRA_APP_PACKAGE, AlarmHandlerService.class)
                .putExtra(Settings.EXTRA_CHANNEL_ID, "foreground_services")
                .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                this,
                1,
                i,
                PendingIntent.FLAG_UPDATE_CURRENT
        );

        startForeground(1, createNotification("Foreground Service", "Click here to disable this foreground service", "foreground_services", NotificationCompat.PRIORITY_DEFAULT).setContentIntent(pendingIntent).build());

    }

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

}

编辑:找出解决方案......正如@snachmsm 正确指出的那样,我以错误的方式设置了我的意图......这应该是意图的正确代码......

  Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
    intent.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
    intent.putExtra(Settings.EXTRA_CHANNEL_ID, "foreground_services");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(
            this,
            1,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT
    );
4

1 回答 1

0

您正在Intent使用Service(假设名称为AlarmHandlerService.class)创建,然后您正在使用它来创建PendingIntentwithgetActivity方法。应该是getService方法

顺便提一句。这被称为“通知蹦床”(在单击通知后运行非 UI Context)并且在最新(当前)Anroid 12 上被禁止。一些关于

于 2022-01-02T18:03:25.823 回答