[英]How can I access a method from an activity and use it into another activity in Android?
[英]How can I access an Activity from another class globally in an Android app?
我有一個Android應用,下面定義了2個活動。 在MainMenu.oncreate()
,我啟動了AlarmManager
,以定期查詢服務器的數據並更新PlayBack
UI中按鈕的文本。 我可以通過全局引用訪問Playback
對象,還是需要在Playback.oncreate()
啟動AlarmManager
,以便可以將引用傳遞給它? 如果是這樣,是否應該像在下面顯示的MainMenu
中那樣使用BroadcastReceiver
和Intent
來完成?
<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());
}
}
}
我有一個Android應用,下面定義了2個活動。
您只有一項活動。
在MainMenu.oncreate()中,我啟動了AlarmManager,以定期向服務器查詢數據並更新“播放UI”中按鈕的文本。
為什么? 您是否打算在用戶退出活動后仍繼續發出這些警報?
我可以通過全局引用訪問Playback對象,還是需要在Playback.oncreate()中啟動AlarmManager,以便可以將引用傳遞給它?
都不行
使用AlarmManager
意味着即使用戶退出活動后,您也希望繼續進行定期工作。 因此,很可能沒有“播放對象”,因為用戶可能不在您的活動中。 如果“ Playback
活動仍在進行中,則您的服務可以發送自己的廣播Intent
以進行接收。 此示例項目演示了為此使用有序廣播的方法,因此,如果活動不在附近,則會發出Notification
。
另一方面,如果您不想在用戶退出活動后繼續進行定期工作,則不要使用AlarmManager
。 在活動中使用postDelayed()
,使用Runnable
通過startService()
觸發您的服務,然后通過postDelayed()
重新安排自身的postDelayed()
。 在這種情況下,如果活動仍在進行中,您可以考慮使用Messenger
類的方法讓服務讓活動知道發生了什么。 此示例項目演示了以這種方式使用Messenger
的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.