我正在編寫我的第一個使用服務的應用程序,按照這裏的教程/指南http://www.vogella.com/articles/AndroidServices/article.html 我有我的服務工作,它描述了爲BOOT_COMPLETED製作一個廣播接收器,它工作並允許我每隔幾分鐘運行一次服務。開始服務計劃,無需重新啓動?
我的問題是,它不工作,直到用戶重新啓動他們的手機。該服務從活動開始,但似乎隨着活動而消失,除非設備已重新啓動。
有沒有什麼辦法可以在第一次運行時從活動中啓動調度程序而無需重新啓動?
我對調度代碼如下:
public class ScheduleReceiver extends BroadcastReceiver {
// Restart service every 30 seconds
private static final long REPEAT_TIME = 1000 * 60; // check every minute.
@Override
public void onReceive(Context context, Intent intent) {
Log.d("schedulereceiver", "starting schedule");
AlarmManager service = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, StartServiceReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
// Start 30 seconds after boot completed
cal.add(Calendar.SECOND, 30);
//
// Fetch every 30 seconds
// InexactRepeating allows Android to optimize the energy consumption
service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), REPEAT_TIME, pending);
// service.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
// REPEAT_TIME, pending);
}
}
我的清單文件看起來是這樣的:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".ProximityActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".ProximityService"
android:enabled="true"
android:icon="@drawable/ic_launcher"
android:label="@string/service_name" >
</service>
<receiver android:name="ScheduleReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver android:name="StartServiceReceiver" >
</receiver>
</application>
</manifest>
儘管如此多月後,我很欣賞答案。在那個階段,我仍然在學習很多東西,並沒有完全理解一些概念。你已經很好地解釋過了,謝謝!恐怕我無法回答你關於令人費解的「死於活動」的問題,因爲我不再使用該代碼。我正在搞一個沒有按照我想要的方式工作的想法(由於硬件限制),所以我放棄了它。 – hyarion