如何从Android应用程序中全局访问另一个类的活动?

时间:2011-02-13 00:46:07

标签: java android android-manifest android-intent android-ui

我有一个Android应用,下面定义了2个活动。在MainMenu.oncreate()中,我启动AlarmManager以定期向服务器查询数据并更新PlayBack UI中的按钮文本。我可以通过全局参考访问Playback对象,还是需要启动AlarmManager中的Playback.oncreate(),以便我可以传递对它的引用?如果是这样,我应该使用BroadcastReceiverIntent完成这项操作,就像我在下面显示的MainMenu中所做的一样吗?

<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());
       }      
    }
}

1 个答案:

答案 0 :(得分:1)

  

我有一个Android应用,下面定义了2个活动。

您只有一项活动。

  

在MainMenu.oncreate()中,我启动了一个AlarmManager,定期向服务器查询数据并更新PlayBack UI中按钮的文本。

为什么呢?即使用户退出活动,您是否打算继续这些警报?

  

我可以通过全局引用访问Playback对象,还是需要在Playback.oncreate()中启动AlarmManager,以便我可以传递对它的引用?

都不是。

使用AlarmManager表示您希望即使在用户退出活动后也能继续定期工作。因此,很可能没有“播放对象”,因为用户可能不在您的活动中。如果Intent活动仍然存在,您的服务可以发送自己的广播PlaybackThis sample project演示了为此使用有序广播,因此如果活动不在,则会引发Notification

如果另一方面,如果用户退出活动,您不希望继续定期工作,则不要使用AlarmManager。在活动中使用postDelayed(),使用通过Runnable触发服务的startService(),然后通过postDelayed()重新安排自己。在这种情况下,您可以考虑使用类似Messenger之类的方式让服务让活动知道发生了什么,如果活动仍然存在。 This sample project演示了以这种方式使用Messenger