2013-04-27 42 views
3

我想知道如果我可以做到這一點,我想實施一項服務,將在活動啓動時調用,並應定期運行,並且當我通過關閉或停止活動時在活動重新啓動之前應該停止服務並且警報管理員不應該調用服務。 我還想發送一些關於哪些服務可以運行的數據,並將結果返回給活動。 目前我做這樣的.....想要運行並停止服務與活動android

class MyService extends Service{ 

} 

class MyScheduler extends BroadCastReceiver{ 

//Here alarm manager and pending intent is initialized to repeat after regular intervals. 

} 

class MyActivity extends Activity{ 

onCreate(){ 

    //here i am binding the service 

} 

} 

MyBrodcastReceiver加入到清單

請大家幫忙,並建議該怎麼辦呢?

回答

9

啓動:

this.startService(new Intent(this, MyService.class)); 

用於回採:

this.stopService(new Intent(this, MyService.class)); 

具有間隔創建定期調用BrodcastReceiver類似於下面的示例服務:

在服務

// An alarm for rising in special times to fire the pendingIntentPositioning 
private AlarmManager alarmManagerPositioning; 
// A PendingIntent for calling a receiver in special times 
public PendingIntent pendingIntentPositioning; 

@Override 
     public void onCreate() { 
      super.onCreate(); 

      alarmManagerPositioning = (AlarmManager) getSystemService 
        (Context.ALARM_SERVICE); 

      Intent intentToFire = new Intent(
        ReceiverPositioningAlarm.ACTION_REFRESH_SCHEDULE_ALARM); 

      pendingIntentPositioning = PendingIntent.getBroadcast(
        this, 0, intentToFire, 0); 



     }; 


@Override 
    public void onStart(Intent intent, int startId) { 

      long interval = 10 * 60 * 1000; 
      int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP; 
      long timetoRefresh = SystemClock.elapsedRealtime(); 
      alarmManagerPositioning.setRepeating(alarmType, 
        timetoRefresh, interval, pendingIntentPositioning); 

    } 
+1

廣播接收機將如何接收意向數據? – 2013-04-27 07:21:19

+0

搜索有很多的例子在谷歌 – breceivemail 2013-04-27 07:27:06

+0

好吧,我會嘗試,然後標記您的答案:-) – 2013-04-27 07:28:32