0
我正在使用鬧鐘管理器定期向服務器請求數據。我想在通知中顯示回覆。但是,每當我嘗試顯示通知時,應用程序都會崩潰。這是我寫的代碼:使用AlarmManager運行通知
主要活動
public class MainActivity extends AppCompatActivity {
private WebView mWebview;
private Alarm alarm;
private PendingIntent pendingIntent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent alarmIntent = new Intent(MainActivity.this, Alarm.class);
alarmIntent.putExtra(Alarm.NOTIFICATION_ID, 1);
alarmIntent.putExtra(Alarm.NOTIFICATION, getNotification("HELLO"));
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent, 0);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 10000, pendingIntent);
Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
}
private Notification getNotification(String content) {
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle("Scheduled Notification");
builder.setContentText(content);
return builder.build();
}
}
,報警類
public class Alarm extends BroadcastReceiver
public static String NOTIFICATION_ID = "notification-id";
public static String NOTIFICATION = "notification";
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(NOTIFICATION);
int id = intent.getIntExtra(NOTIFICATION_ID, 0);
notificationManager.notify(id, notification); // !!!!! CRASHES HERE
}
我是一個完整的Android新手,所以任何幫助,將不勝感激。
你能分享崩潰日誌? – jomartigcal
嗨,感謝您的回覆。它突然開始工作......所以崩潰日誌被刪除了。但是,它仍然不顯示任何內容:/ – Tim