我是android開發的新手。我正在開發一個簡單的應用程序,其中包含1個活動,1個BroadcastReceiver和1個Notification服務。有些報警設置爲活動,我想在設備啓動/重新啓動時重新設置它們。無法在廣播接收器中獲取服務集中的意圖數據
這裏是MainActivity我的代碼:
//randomDates is an (Long) array of time in milliseconds
int len = randomDates.length;
AlarmManager[] alarmManager = new AlarmManager[len];
ArrayList<PendingIntent> intentArray = new ArrayList();
String type = "A";
Long t = new Date().getTime();
for (int i = 0; i < len; i++) {
if(t <= randomDates[i]) {
Intent myIntent = new Intent(MainActivity.this, Receiver.class);
if (i%2 == 1) {
type = "A";
} else {
type = "P";
}
myIntent.putExtra("type", type);
myIntent.putExtra("time", randomDates[i]);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, i, myIntent, PendingIntent.FLAG_ONE_SHOT);
alarmManager[i] = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager[i].set(AlarmManager.RTC, randomDates[i], pendingIntent);
intentArray.add(pendingIntent);
}
}
sharedPref = getSharedPreferences("MyCalApp",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("areAlarmsAlreadySet", false);
editor.putString("alarmDates",Arrays.toString(randomDates));
editor.commit();
報警將在活動設置。 Receiver在Manifest文件中註冊以接收事件。在接收器 的onReceive功能如下:
public void onReceive(Context context, Intent intent) {
if(intent.getAction() != null && intent.getAction().equalsIgnoreCase("android.intent.action.BOOT_COMPLETED")) {
Long[] randomDates1 = //get from shared Pref;
int len = randomDates1.length;
AlarmManager[] alarmManager = new AlarmManager[len];
ArrayList<PendingIntent> intentArray = new ArrayList();
String type = "A";
Long t = new Date().getTime();
for (int i = 0; i < len; i++) {
if (t <= randomDates1[i]) {
Intent myIntent = new Intent(context.getApplicationContext(), NotificationService.class);
if (i % 2 == 1) {
type = "A";
} else {
type = "P";
}
myIntent.putExtra("type", type);
myIntent.putExtra("time", randomDates1[i]);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, i, myIntent, PendingIntent.FLAG_ONE_SHOT);
alarmManager[i] = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
alarmManager[i].set(AlarmManager.RTC, randomDates1[i], pendingIntent);
intentArray.add(pendingIntent);
}
}
}
}
intent.setClass (context, NotificationService.class);
context.startService(intent);
}
而且在通知服務我取的意圖數據如下:
Bundle b = intent.getExtras();
String type = b.getString("type"); // This is line number 38.
Long time = intent.getLongExtra("time",1l);
我正確地收到所有通知從活動設置警報。但得到NullpointerException
Caused by: java.lang.NullPointerException at com.example.android.basicnotifications.NotificationService.onStart(NotificationService.java:38)
這是我從其中讀額外的意向。我在這裏錯過了什麼? 任何幫助表示讚賞。
P.S.清單文件中設置了所有必要的權限。
你需要顯示NotificationService.onStart()方法,特別是第38行:) – aelimill
@aelimill,編輯我的代碼。它顯示了第38行,我收到錯誤。 :) – meen