我有一個Android應用程序,下面定義了2個活動。在MainMenu.oncreate()
中,我有一個AlarmManager
開始定期查詢服務器的數據並更新PlayBack
用戶界面中按鈕的文本。我可以通過全球參考訪問Playback
對象,還是需要啓動Playback.oncreate()
中的AlarmManager
,才能將參考傳遞給它?如果是這樣,這是否應該用BroadcastReceiver
和Intent
來完成,就像我在下面顯示的MainMenu
中做的那樣?如何在Android應用程序中全局訪問其他課程的活動?
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".MainMenu"
android:label="@string/app_name">
</activity>
<activity android:name=".Playing" android:label="@string/playing_title">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".NotificationUpdateReceiver" android:process=":remote" />
<service android:name="org.chirpradio.mobile.PlaybackService"
public class MainMenu extends Activity implements OnClickListener {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
View playingButton = findViewById(R.id.playing_button);
playingButton.setOnClickListener(this);
try {
Long firstTime = SystemClock.elapsedRealtime();
// create an intent that will call NotificationUpdateReceiver
Intent intent = new Intent(this, NotificationUpdateReceiver.class);
// create the event if it does not exist
PendingIntent sender = PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// call the receiver every 10 seconds
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, firstTime, 10000, sender);
} catch (Exception e) {
Log.e("MainMenu", e.toString());
}
}
}