我有一个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());
}
}
}