【问题标题】:How can I access an Activity from another class globally in an Android app?如何在 Android 应用程序中全局访问另一个类的 Activity?
【发布时间】:2011-02-13 00:46:07
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

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

    您只有一项活动。

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

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

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

    都没有。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-04
      • 1970-01-01
      • 2011-10-29
      • 2013-03-15
      • 1970-01-01
      相关资源
      最近更新 更多