在开机启动的服务做的工作,每15分钟 [英] Starting service on boot to to do work every 15 minutes
问题描述
所以,我通过互联网去寻找解决方案,但没有发现任何东西,结合我所需要的。
So, i have gone through internet looking for solution, but didnt find anything that combines what I need.
我需要这样的:
如果手机被重新启动,我需要在开机即会每隔15分钟将数据发送到我的服务器启动服务。我做了code,它正在为开机,但不知道如何实现计时器。
我需要2广播接收器和2个服务或?
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?
我的广播接收器:
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:
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" />
这是怎么回事每15分钟重复该服务不能从活动开始,但在开机。
This service that is going to be repeated every 15 minutes must not start from the activity, but on boot.
推荐答案
在如下定期间隔使用警报管理启动服务的最佳方式:
Best way to start service on a regular interval use alarm manager as below:
//使用AlarmManager启动服务
// 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));
}
});
}
感谢
这篇关于在开机启动的服务做的工作,每15分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!