我正在编写我的第一个使用服务的应用程序,遵循这里的教程/指南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>