Я пытаюсь запустить этот код в моем мобильном приложении, но он не работает и также не выдает ошибку.Я попытался также распечатать журнал, но он ничего не показывает в logcat.Эта проблема возникает только в Oreo и хорошо работает во всех других версиях Android, также хорошо работает, когда приложение находится в фоновом режиме.
public class MainActivity extends AppCompatActivity {
AlarmManager am;
TimeAlarm timeAlarm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
setOneTimeAlarm();
}
public void setOneTimeAlarm() {
Intent intent = new Intent(this, TimeAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), pendingIntent);
}
public void setRepeatingAlarm() {
Intent intent = new Intent(this, TimeAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), (5 * 1000), pendingIntent);
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("ondestroy","ondestroy");
}
@Override
protected void onStart() {
super.onStart();
Log.d("onstart","onstart");
IntentFilter intentFilter=new IntentFilter("my.custom.action.tag.fordemo");
intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(timeAlarm,intentFilter);
}
}
Код широковещательного приемника, когда я удалил приложение из фона, оно перестало работать.
public class TimeAlarm extends BroadcastReceiver {
NotificationManager nm;
String channelId = "channel-01";
String channelName = "Channel Name";
int importance = NotificationManager.IMPORTANCE_HIGH;
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onReceive(Context context, Intent intent) {
nm = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
channelId, channelName, importance);
nm.createNotificationChannel(mChannel);
} else {
}
CharSequence from = "Nithin";
CharSequence message = "Crazy About Android...";
PendingIntent contentIntent =
PendingIntent.getActivity(context, 0, new Intent(), 0);
//Notification notif = new Notification(R.drawable.logo,
"Crazy About Android...", System.currentTimeMillis());
NotificationCompat.Builder notification = new
NotificationCompat.Builder(context.getApplicationContext());
// notification.setContentIntent(pintent);
notification.setTicker(from).setSubText(from).setSmallIcon(R.drawable.logo);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notification.setChannelId(channelId);
}
Notification notification1 = notification.build();
notif.setLatestEventInfo(context, from, message,contentIntent);
nm.notify(1, notification1);
}
}