【发布时间】:2015-05-27 08:07:42
【问题描述】:
onHandleIntent 在设备关闭时的行为是什么?
我知道在 IntentService 上,只要 onHandleIntent 没有完成它的工作,服务就会一直运行。
所以考虑一下,这是一个关于设备关闭时服务行为的一般性问题,一旦我们再次启动设备,它们会“唤醒”吗?
如果没有,有办法吗?无论发生什么,我都希望我的 intentservice 继续运行直到 onHandleIntent 完成。
编辑: 我将添加我的代码以便更好地理解。 我正在尝试在 SQLite 上保存请求并继续运行,直到该表为空,然后该服务将关闭。 所以在设备关闭的情况下,我仍然会从关闭前的同一个地方继续。 P.S - 我尝试使用 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";
}
}
【问题讨论】:
-
你为什么用IntentService,为什么不用普通Service?
-
hmmn,抱歉,如果您在工作线程中提交作业,我不知道您为什么需要后台线程
-
我后来添加了工作线程来尝试提高性能。我认为它也可以通过服务来完成
标签: android device shutdown android-intentservice application-shutdown