【问题标题】:android service with asynctask not stopping completely带有异步任务的android服务没有完全停止
【发布时间】:2013-07-31 19:11:12
【问题描述】:

我有一个下载服务来使用 asynctask 下载文件。有一个按钮用于暂停和恢复。当我点击暂停时,它应该会破坏服务以取消当前任务。我试图通过使用来实现它

Intent download=new Intent(Download.this, DownloadService.class); getApplicationContext().stopService(download);

还有放

stopself();

onDestroy(){} 函数内。我的问题是 DownloadService 被销毁时,DownloadTask 没有被取消。请帮助找到问题的根源。谢谢。

【问题讨论】:

  • 如何下载文件?使用 http 请求或 DownloadManager?
  • http 请求,因此我正在使用服务。

标签: android service android-asynctask


【解决方案1】:

您必须在停止服务之前取消 AsyncTask。因为 AsyncTask 会一直工作到 App 进程关闭。

因此,您必须关闭 HttpRequest 才能中断 AsyncTask 中的阻塞调用。将 HttpClient 的实例作为 AsyncTask 中的属性。在你的服务中定义一个中断函数,看起来像这样。

public void stopTaskAndService(){
    yourAsyncTask.yourHttpClient.getConnectionManager().shutdown();
    yourAsyncTask.cancel(true) // prevent the onPostExecute() call
    stopself();
}

【讨论】:

  • 感谢您的回复,我正在查看。
  • 我无法输入 yourAsyncTask.yourHttpClient.getConnectionManager().shutdown(); 我刚刚关闭了连接以使其正常工作。
【解决方案2】:

我必须查看更多代码才能确定发生了什么。

我想知道使用 IntentService 代替 Service 是否会更好地为您服务。你考虑过这个吗?

【讨论】:

  • 我的 onStartCommand() code=intent.getIntExtra("code", 0);链接=intent.getStringExtra("nLink");文件名=intent.getStringExtra("ntitle");行=intent.getLongExtra("行", 0); if(code==1){ percent=intent.getStringExtra("perce"); total=intent.getStringExtra("total");下载=intent.getStringExtra("下载"); } System.out.println(row); Toast.makeText(this, "MyService Started", Toast.LENGTH_LONG).show(); getfile.execute(new String[] {link,fileName});返回服务。START_NOT_STICKY;
  • 我将在 mainactivity 中停止此服务,因为 Intent download=new Intent(Download.this, DownloadService.class); getApplicationContext().stopService(下载);休息;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-20
  • 2016-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-07
相关资源
最近更新 更多