【发布时间】:2016-06-02 21:24:29
【问题描述】:
我正在开发一款应用,可将您的本地日期与云端同步。所以我需要每 10 分钟自动检查一次我的本地数据,以便将新的相机文件上传到云端。
所以我使用了仅在应用程序在前台运行时才有效的 IntentService。如果我关闭它,我的服务不会上传任何内容。我希望我的 INTENTSERVICE 在后台与 AlarmManager 一起工作。
我的 IntentService 在 Manifest.xml 中声明:
<!-- Uploader and Deleter Files Service -->
<service android:name=".receiver.UploadDeleteService" android:exported="false" />
<receiver
android:name=".receiver.AlarmReceiver"
android:process=":remote" >
</receiver>
我的警报接收器:
public class AlarmReceiver extends BroadcastReceiver {
public static final int REQUEST_CODE = 12345;
public static final String ACTION = "com.codepath.example.servicesdemo.alarm";
// Triggered by the Alarm periodically (starts the service to run task)
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, UploadDeleteService.class);
context.startService(i);
}
}
我的 ServiceInteractor,我在 AlarmManager 中实例化了我的 AlarmReceiver:
public class ServiceInteractorImpl implements ServiceInteractor {
private Context context;
public ServiceInteractorImpl(Context context){
this.context = context;
}
@Override
public void launchService() {
// Construct an intent that will execute the AlarmReceiver
Intent intent = new Intent(context, AlarmReceiver.class);
// Create a PendingIntent to be triggered when the alarm goes off
final PendingIntent pIntent = PendingIntent.getBroadcast(context, AlarmReceiver.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Setup periodic alarm every 5 seconds
long firstMillis = System.currentTimeMillis(); // alarm is set right away
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP
// Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, 10);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
cal.getTimeInMillis(), pIntent);
}
}
我的 UploadDeleteService 调用改造实现模块:
public class UploadDeleteService extends IntentService implements ApiConnector.GetObjectListener {
private RemoteInteractor remoteInteractor;
public UploadDeleteService(String name) {
super(name);
}
public UploadDeleteService() {
super("UpdateDeleteService");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.i("SERVICE", "Service running");
remoteInteractor = new RemoteInteractorImpl(getApplicationContext());
remoteInteractor.checkNews(this);
}
@Override
public void onImageUploaded(String type, JSONObject response) {
Log.d("SERVICE", " onImageUploaded ");
//REST OF THE STUFF....
}
}
请帮助我解决这个问题。尽管应用程序已关闭,但我需要它每 10 分钟运行一次。谢谢!
【问题讨论】:
-
你确定服务在前台重复吗?
-
cal.add(Calendar.MINUTE, 10); //这将使当前时间增加 10 分钟尝试将“cal.getTimeInMillis()”更改为“10*60*1000”
-
这是错误,谢谢。但是有人知道如何避免我的服务在警报管理器控制时打开应用程序吗?
标签: android service upload alarmmanager intentservice