好吧,我有一個名爲'Main.java'的主要活動。這個主要活動啓動一個AlarmManager,它觸發一個導致'AlarmReceiver.java'的意圖。 這個'AlarmReceiver.java'然後創建一個通知,其上有兩個按鈕。其中一個按鈕是刪除按鈕,所以當用戶點擊該按鈕時,會觸發另一個意圖,將其導向「DelPair.java」。Android - 從活動外部調用功能(通過AlarmManager和通知)
在DelPair.java中,我修改了數據庫中的表格,但是後來我需要Main.java的UI來反映這種更改。我已經創造了Main.java兩個函數updateArrayFromDB()和updateUIFromArray()爲我做到這一點:
- updateArrayFromDB()將在Main.java創建一個ArrayList同步到一個數據庫中的 某個表。
- updateUIFromArray()將更改 Main.java的UI以表示剛剛更改的ArrayList。
問題是我無法從DelPair.java調用這兩個函數(它們不存在於該空間中)。我遇到了Serializables試圖找到一個答案,但我不知道它們是否適用於此處,或者確切地說,如何通過AlarmManager 和 NotificationManager實現它們。
如何從DelPair.java訪問這些方法?
在Main.java:
public void updateArrayFromDB(){
//... The code for this is long and irrelevant
}
public void updateUIFromArray(){
//... The code for this is long and irrelevant
}
private void SendNotification() {
Intent intent = new Intent(this, AlarmReceiver.class);
//...
PendingIntent sender = PendingIntent.getBroadcast(this, 2 , intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, 5000, notif_freq, sender);
}
在AlarmReceiver.java:
Intent delPairI = new Intent(context, DelPair.class);
PendingIntent delPairPI = PendingIntent.getService(context, 0, delPairI, PendingIntent.FLAG_UPDATE_CURRENT);
Notification noti;
noti = new Notification.Builder(context)
//...
.addAction(R.drawable.ic_delete_icon, "Delete the thing", delPairPI)
.build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, noti);
,然後在DelPair.java:
public class DelPair extends IntentService {
//...
@Override
protected void onHandleIntent(final Intent intent) {
//...
Intent it = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
getApplicationContext().sendBroadcast(it);
handler.post(new Runnable() {
@Override
public void run() {
//... here is where I update the database, which works perfectly
//now need to update the UI and array in Main.java
updateArrayFromDB(); //these lines
updateUIFromArray(); //obviously don't work
}
});
}
}
您可以嘗試在'onResume()'中放置'updateArrayFromDB()'和'updateUIFromArray()'的代碼,這樣每次用戶輸入活動時都會調用它。 – Shaishav
這可能只是工作。讓我稍微回到你身邊。你可以把它作爲答案嗎? – Beyarkay