Starting service on boot to to do work every 15 mi

2019-06-12 22:37发布

问题:

So, i have gone through internet looking for solution, but didnt find anything that combines what I need.

I need this: if mobile gets restarted, I need to start a service on boot that will every 15 minutes send data to my server. I made code that is working for boot, but don't know how to implement timer. Do I need 2 broadcast receivers and 2 services or?

My broadcast receiver:

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);
        }

    }

}

and my Service:

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!");


    }


}

and my 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" />

This service that is going to be repeated every 15 minutes must not start from the activity, but on boot.

回答1:

Best way to start service on a regular interval use alarm manager as below:

// Start service using 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));
        }
    });
}

Thanks