当我试图通过安卓应用程序中的通知打开它们时,设置不断崩溃



我正在尝试在我的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
    );

您使用Service创建Intent(假设名称为AlarmHandlerService.class(,然后使用它使用getActivity方法创建PendingIntent。应该是getService方法

顺便说一句。这被称为";通知蹦床";(点击通知后运行非UI Context(并且在最新(当前(Anroid 12上被禁止。关于的一些文章

最新更新