2011-02-13 86 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的使用。

相关问题