开机启动服务,每 15 分钟工作一次

Starting service on boot to to do work every 15 minutes

所以,我通过互联网寻找解决方案,但没有找到任何结合我需要的东西。

我需要这个: 如果手机重新启动,我需要在启动时启动一项服务,每 15 分钟向我的服务器发送一次数据。我编写了可用于启动的代码,但不知道如何实现计时器。 我需要 2 个广播接收器和 2 个服务还是?

我的广播接收器:

public class BrReceiver extends BroadcastReceiver {

    final public static String ONE_TIME = "onetime";

    @Override
    public void onReceive(Context context, Intent intent) {
        if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {

            Intent serviceIntent = new Intent(context, Service.class);
            context.startService(serviceIntent);
        }

    }

}

和我的服务:

public class Service extends IntentService {

    private static final String TAG = "DownloadService";

    public Service() {
        super(Service.class.getName());
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        Log.d(TAG, "Service Started!");


    }


}

和我的 AndroidManifest:

<!-- Declaring broadcast receiver for BOOT_COMPLETED event. -->
        <receiver android:name=".services.BrReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            </intent-filter>
        </receiver>

          <service
            android:name=".services.Service"
            android:exported="false" />

这项每 15 分钟重复一次的服务不能从 activity 启动,而是在启动时启动。

定期使用警报管理器启动服务的最佳方法如下:

// 使用 AlarmManager 启动服务

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.SECOND, 10);
    Intent intent = new Intent(Main.this, Service_class.class);
    PendingIntent pintent = PendingIntent.getService(Main.this, 0, intent,
            0);
    AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
            36000 * 1000, pintent);

    // click listener for the button to start service
    Button btnStart = (Button) findViewById(R.id.button1);
    btnStart.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            startService(new Intent(getBaseContext(), Service_class.class));

        }
    });

    // click listener for the button to stop service
    Button btnStop = (Button) findViewById(R.id.button2);
    btnStop.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            stopService(new Intent(getBaseContext(), Service_class.class));
        }
    });
}

谢谢