我正在尝试创建一个定期服务,我可以使用我的API服务器上的数据验证存储在移动设备上的某些值。如果用户的密码被更改或者用户被删除,API服务器应该发回响应,以便移动应用知道用户应该注销。请求/响应不是问题。只是定期获得服务的问题。
MyService.class:
public class MyService extends IntentService {
private static final String TAG = "MyService";
public MyService() {
super("MyService");
}
@Override
protected void onHandleIntent(Intent intent) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
try {
Thread.sleep(5000);
Log.d(TAG,"loop service");
} catch (InterruptedException e) {
// Restore interrupt status.
Thread.currentThread().interrupt();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}
}
在另一个随机类的onCreate里面:
Context mContext = getApplicationContext();
Intent i= new Intent(mContext, MyService.class);
i.putExtra("KEY1", "Value to be used by the service");
mContext.startService(i);
该服务确实启动(它显示了Log.d),如何从此处继续重启或在一定时间后启动它?
答案 0 :(得分:1)
首先要做的事情是:IntentService只是为了从主线程执行任务队列而设计的。因此,每次要检查更新时都必须创建一个新的:为此,请参阅Alarm Manager
但这不一定是最好的方法。您可以尝试使用push notifications方法,而不是轮询服务器以进行更改。