2011-02-13 63 views
0

我有一個Android應用程序,下面定義了2個活動。在MainMenu.oncreate()中,我有一個AlarmManager開始定期查詢服務器的數據並更新PlayBack用戶界面中按鈕的文本。我可以通過全球參考訪問Playback對象,還是需要啓動Playback.oncreate()中的AlarmManager,才能將參考傳遞給它?如果是這樣,這是否應該用BroadcastReceiverIntent來完成,就像我在下面顯示的MainMenu中做的那樣?如何在Android應用程序中全局訪問其他課程的活動?

<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

我有如下定義的2個活動Android應用。

您只有一項活動。

在MainMenu.oncreate()中,我有一個AlarmManager啓動以定期查詢服務器的數據並更新PlayBack UI中按鈕的文本。

爲什麼?即使在用戶退出該活動之後,您是否打算繼續使用這些警報?

我可以通過全局引用訪問回放對象還是需要揭開序幕在Playback.oncreate(在AlarmManager)代替我可以傳遞給它的參考?

都沒有。

使用AlarmManager意味着即使在用戶退出活動之後仍希望定期工作繼續。因此,很可能沒有「播放對象」,因爲用戶可能不在您的活動中。如果Playback活動還在,您的服務可以發送自己的廣播IntentThis sample project演示使用一個有序的廣播爲此,所以如果該活動不在周圍,則會提出Notification

另一方面,如果您不希望在用戶離開活動時繼續週期性工作,請不要使用AlarmManager。在活動中使用postDelayed(),使用Runnable通過startService()觸發您的服務,然後通過postDelayed()重新安排自己。在這種情況下,您可以考慮使用類似Messenger這樣的方式,讓活動知道發生了什麼,如果活動還在。 This sample project以這種方式演示了Messenger的使用。

相關問題