在关闭应用程序时,我试图通过异步任务向我的数据库发送一些信息,该任务调用了一个更新服务器的帖子。我的问题是,当应用程序被销毁并调用异步任务时,代码会在服务中运行,但是一旦完成对异步任务的调用,它就不会真正进入任务,它只是完成应用程序并取消异步。是否有不同/更好的方法来解决这个问题?谢谢! 干杯 〜洛基
服务代码:
public class DeleteGroup extends Service {
String username;
SendGCM sendGCM;
@Override
public void onCreate() {
super.onCreate();
Log.d("Log:", "Started");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent,int flags, int startId) {
Bundle bundle = intent.getExtras();
if(bundle != null && intent.getAction() != null)
{
this.username = bundle.getString("username");
}
Log.d("User", username);
return Service.START_STICKY;
}
@Override
public void onDestroy()
{
super.onDestroy();
sendGCM = new SendGCM();
sendGCM.execute("DeleteGroup", "", "", username, "", "");
}
@Override
public void onTaskRemoved(Intent rootIntent)
{
Log.d("Log:", "Task Removed");
}
//class that sends a gcm asynch to the server
class SendGCM extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
HttpResponse response;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
response = httpClient.execute(httpPost);
return EntityUtils.toString(response.getEntity());
// writing response to log
} catch (IOException e) {
e.printStackTrace();
}
stopSelf();
Log.d("Done", "Done");
return null;
}
}//end SendGCM asynchronus task
}
答案 0 :(得分:0)
尝试将您的服务更改为IntentService。服务在主线程上运行,并在应用程序关闭后立即停止。 IntentService有自己的工作线程。 来自开发人员指南:
警告:服务在其托管进程的主线程中运行 - 该服务不会创建自己的线程,也不会在单独的进程中运行(除非您另行指定)。
从Android开发者指南中提取的IntentService示例:
var response =
"[{ \"trace\":{ \"details\":{ \"date\":\"[28-02-2016 11:04:26.856573]\",\"type\":\"[info]\",\"message\":\"[system done.]\"},\"context\":{ \"context\":[[{\"ID\":\"john dillinger\"}]]}}},{\"trace\":{\"details\":{\"date\":\"[28-02-2016 11:04:26.856728]\",\"type\":\"[info]\",\"message\":\"[trace done.]\"},\"context\":{\"context\":[[{\"ID\":\"john dillinger\"}]]}}}]";
var obj = JsonConvert.DeserializeObject<List<Trace>>(response);