首页 > 解决方案 > 启动应用程序时不运行计划通知

问题描述

所以我有一个BroadcastReceiver带有SwitchPreference设置页面的通知来打开和关闭它。问题是即使打开它也不会启动。

这里是SwitchPreference

public class SettingsFragment extends PreferenceFragment {

private StartAlarm startAlarm;

@TargetApi(Build.VERSION_CODES.M)
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    startAlarm = new StartAlarm(getContext());

    final SwitchPreference alarm7 = (SwitchPreference) findPreference(this.getResources()
            .getString(R.string.alarm7));

    final SwitchPreference alarm8 = (SwitchPreference) findPreference(this.getResources()
            .getString(R.string.alarm8));

    alarm7.setOnPreferenceChangeListener((preference, o) -> {
        if (alarm7.isChecked()) {
            alarm7.setChecked(false);
        } else {
            startAlarm.startAlarm7();
            alarm7.setChecked(true);
        }
        return false;
    });

    alarm8.setOnPreferenceChangeListener((preference, o) -> {
        if (alarm8.isChecked()) {
            alarm8.setChecked(false);
        } else {
            startAlarm.startAlarm8();
            alarm8.setChecked(true);
        }
        return false;
    });
}
}

和 startAlarm 方法

每天早上 7 点和 8 点触发警报

public class StartAlarm {
private Calendar c = Calendar.getInstance();
private Context context;

public StartAlarm(Context context) {
    this.context = context;
}

@SuppressLint("ShortAlarm")
public void startAlarm7() {
    Intent intent = new Intent(context, AlertReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);

     AlarmManager alarmManager = (AlarmManager) (context.getSystemService(ALARM_SERVICE));
    c.set(Calendar.HOUR_OF_DAY, 7);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);

    assert alarmManager != null;
    alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis() , pendingIntent);
}

@SuppressLint("ShortAlarm")
public void startAlarm8() {


    Intent release = new Intent(context, AlertReceiverRelease.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1, release, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) (context.getSystemService(ALARM_SERVICE));

    c.set(Calendar.HOUR_OF_DAY, 8);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);

    assert alarmManager != null;
    alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis() , pendingIntent);

}
}

首先BroadcastReceiver是预定的早上 7 点闹钟

public class AlertReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    NotificationHelper notificationHelper = new NotificationHelper(context);
    NotificationCompat.Builder nb = notificationHelper
            .getChannelNotification("Film Tv", "Hey, cek katalog movie kamu sekarang!");
    notificationHelper.getNotificationManager().notify(1, nb.build());
}

}

BroadcastReceiver早上 8 点警报的第二个

public class AlertReceiverRelease extends BroadcastReceiver {
public static final String API_KEY = "2e08750083b7e21e96e915011d3f8e2d";
private ArrayList<Notification> nb = new ArrayList<>();
private NotificationHelper notificationHelper;

@Override
public void onReceive(Context context, Intent intent) {
    notificationHelper = new NotificationHelper(context);
    loadData();
}

private void loadData() {
    ApiInterface apiInterface = ApiClient.getList().create(ApiInterface.class);

    Call<Response> responseCall = apiInterface.getLatestFilm(API_KEY);
    responseCall.enqueue(new Callback<Response>() {

        @Override
        public void onResponse(Call<Response> call, retrofit2.Response<Response> response) {

            assert response.body() != null;
            List<Response> responses = new ArrayList<>();
            responses.add(response.body());
            int id = 2;
            for (int i = 0; i < responses.size(); i++) {
                /* How much data is there */
                String title = responses.get(i).getTitle();
                String content = title + " has been released today!";
                nb.add(notificationHelper.getChannelNotification(title, content).build());
                notificationHelper.getNotificationManager().notify(++id, nb.get(i));
            }
        }

        @Override
        public void onFailure(Call<Response> call, Throwable t) {
            Log.d("TAG", t.toString());
        }
    });
}

}

我试图找出问题出在哪里。任何帮助,将不胜感激。谢谢!

编辑 :

还有更多代码可以扩展ContextWrapper

public class NotificationHelper extends ContextWrapper {

public static String CHANNEL_ID = "channel_01";
public static CharSequence CHANNEL_NAME = "dicoding channel";
private NotificationManager notificationManager;
NotificationChannel channel;

public NotificationHelper(Context base) {
    super(base);
    createChannels();
}

@TargetApi(Build.VERSION_CODES.O)
public void createChannels() {

    channel = new NotificationChannel(CHANNEL_ID,
            CHANNEL_NAME,
            NotificationManager.IMPORTANCE_HIGH);
    channel.enableVibration(true);
    channel.enableLights(true);
    channel.setLockscreenVisibility(MODE_PRIVATE);

    getNotificationManager().createNotificationChannel(channel);
}

public NotificationManager getNotificationManager() {

    if (notificationManager == null) {
        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }
    return notificationManager;
}

public NotificationCompat.Builder getChannelNotification(String title, String content) {
    Intent resultIntent = new Intent(this, BottomNavigation.class);
    PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 1, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    return new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
            .setContentTitle(title)
            .setContentText(content)
            .setSmallIcon(android.R.drawable.sym_def_app_icon)
            .setStyle(new NotificationCompat.BigTextStyle()
                    .bigText(content))
            .setAutoCancel(true)
            .setContentIntent(resultPendingIntent);
}

}

标签: androidandroid-notifications

解决方案


那是因为您的通知构建器应该设置更多字段:

NotificationManagerCompat.from(getApplicationContext()).notify(1, new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
                    .setSmallIcon(R.mipmap.ic_launcher_round)
                    .setStyle(new NotificationCompat.DecoratedCustomViewStyle())
                    .setContentTitle("Some title")
                    .setContentText("Some content text")
                    .setPriority(NotificationCompat.PRIORITY_HIGH).build());

推荐阅读