0

以下に定義されている2つのアクティビティを持つAndroidアプリがあります。では、サーバーに定期的にデータを照会し、 UIのボタンのテキストを更新するためMainMenu.oncreate()AlarmManagerキックオフがあります。グローバル参照を介しPlayBackてオブジェクトにアクセスできますか、それとも参照を渡すことができるように、代わりにを開始する必要がありますか?もしそうなら、これは私が下に示されているようにとで行うべきですか?PlaybackAlarmManagerPlayback.oncreate()BroadcastReceiverIntentMainMenu

<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

以下に定義されている2つのアクティビティを持つAndroidアプリがあります。

アクティビティは1つだけです。

MainMenu.oncreate()で、AlarmManagerを起動して、サーバーにデータを定期的にクエリし、PlayBackUIのボタンのテキストを更新しています。

なんで?ユーザーがアクティビティを終了した後も、これらのアラームを継続する予定ですか?

グローバル参照を介してPlaybackオブジェクトにアクセスできますか、それとも参照を渡すことができるように、代わりにPlayback.oncreate()でAlarmManagerを開始する必要がありますか?

ない。

使用AlarmManagerとは、ユーザーがアクティビティを終了した後も定期的な作業を継続することを意味します。したがって、ユーザーがおそらくあなたのアクティビティに参加していないため、「再生オブジェクト」がない可能性が非常に高くなります。アクティビティがまだ行われている場合、サービスは独自のブロードキャストIntentを送信してピックアップすることができます。このサンプルプロジェクトは、このために順序付けられたブロードキャストを使用することを示しているため、アクティビティがない場合は、代わりにaが発生します。PlaybackNotification

一方、ユーザーがアクティビティから抜け出した場合に定期的な作業を続行したくない場合は、を使用しないでくださいAlarmManager。を介してサービスをトリガーし、を介して自身を再スケジュールするを使用postDelayed()して、アクティビティ内で使用します。この場合、アクティビティがまだ存在する場合は、サービスにアクティビティに何が起こっているかを知らせる方法として、のようなものを使用することを検討できます。このサンプルプロジェクトは、この方法でのの使用法を示しています。RunnablestartService()postDelayed()MessengerMessenger

于 2011-02-13T00:57:04.663 に答える