0

I have an Android app with 2 activities defined below. In the MainMenu.oncreate(), I have an AlarmManager kicked off to periodically query a server for data and update the text of a button in the PlayBack UI. Can I access the Playback object via a global reference or do I need to kick off the AlarmManager in the Playback.oncreate() instead so I can pass a reference to it? If so, should this be done with a BroadcastReceiver and Intent as I'm doing in the MainMenu shown below?

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

1 回答 1

1

我有一个 Android 应用程序,其中定义了以下 2 个活动。

您只有一项活动。

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

为什么?您是否打算在用户退出活动后继续这些警报?

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

两者都不。

使用AlarmManager意味着您希望即使在用户退出活动后也能继续进行定期工作。因此,很可能没有“播放对象”,因为用户可能不在您的活动中。如果活动仍然存在,您的服务可以发送自己的广播Intent以被拾取。此示例项目演示了为此使用有序广播,因此如果活动不存在,则改为引发 a。PlaybackNotification

另一方面,如果您不希望在用户退出活动时继续定期工作,则不要使用AlarmManager. postDelayed()在活动中使用,使用通过触发Runnable您的服务的startService(),然后通过 重新安排自身postDelayed()。在这种情况下,您可以考虑使用类似 aMessenger的方式让服务让活动知道正在发生的事情,如果活动仍然存在的话。此示例项目演示了Messenger以这种方式使用 a 。

于 2011-02-13T00:57:04.663 回答