[英]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.