onHandleIntent 在设备关闭时的行为是什么?
我知道在 IntentService 上,只要 onHandleIntent 没有完成它的工作,服务就会一直运行。
所以考虑一下它是关于设备关闭时服务行为的一般问题,一旦我们再次启动设备,它们会“唤醒”吗?
如果没有,有办法吗?无论发生什么,我都希望我的意图服务继续运行直到 onHandleIntent 完成。
编辑:我将添加我的代码以便更好地理解。我正在尝试在 SQLite 上保存请求并继续运行,直到该表为空,然后服务将关闭。所以在设备关闭的情况下,我仍然会从关闭前的同一个地方继续。PS - 我尝试使用 executor 以获得更好的性能(它是一个测试,尚未得到证实),如果有人得到更好的建议,我很乐意听到他们,因为我是这个主题的新手
onHandleIntent
@Override
protected void onHandleIntent(Intent intent) {
helper = new DBHelper(getApplicationContext());
executor = Executors.newFixedThreadPool(5);
File file;
Log.e("requestsExists",helper.requestsExists()+"");
while (helper.requestsExists()) {
ArrayList<String> requestArr = helper.getRequestsToExcute(5);
//checks if the DB requests exists
if (!requestArr.isEmpty()) {
//execute them and delete the DB entry
for(int i = 0; i < requestArr.size(); i++) {
file = new File(requestArr.get(i));
Log.e("file",file.toString());
Future<String> future = executor.submit(new MyThread(file,getApplicationContext()));
Log.e("future object", future.toString());
try {
long idToDelete = Long.parseLong(future.get());
Log.e("THREAD ANSWER", future.get() + "");
helper.deleteRequest(idToDelete);
} catch (InterruptedException e) {
Log.e("future try", "");
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
}
executor.shutdown();
}
我的线程
public class MyThread implements Callable {
private File _file;
private Context context;
private DBHelper helper;
public MyThread(File file, Context context) {
this._file = file;
this.context = context;
}
@Override
public String call() throws Exception {
HttpClient client = Utility.getNewHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost post = new HttpPost("http://192.168.9.62/mobile_api/timeline/moment/upload");
try {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fileBody = new FileBody(_file);
builder.addPart("content", fileBody);
builder.addPart("type", new StringBody("file", ContentType.TEXT_PLAIN));
builder.addPart("title", new StringBody("service test", ContentType.TEXT_PLAIN));
builder.addPart("userType", new StringBody("user", ContentType.TEXT_PLAIN));
builder.addPart("uid", new StringBody(MyInfiActivity.friends_uid, ContentType.TEXT_PLAIN));
builder.addPart("momentId", new StringBody("1", ContentType.TEXT_PLAIN));
builder.addPart("storyId", new StringBody("8", ContentType.TEXT_PLAIN));
Utility.addCookiesToPost(post);
post.setEntity(builder.build());
client.execute(post, localContext);
} catch (IOException e) {
Log.e("Callable try", post.toString());
}
return "1";
}
}