【发布时间】:2017-11-30 02:17:59
【问题描述】:
我使用意图服务创建了下载任务。它显示带有百分比进度条的通知。我正在使用本地广播管理器在下载时传递数据。我还在通知中添加了一个按钮来取消下载,但问题是当我单击取消时下载它不会停止 Intent 服务。我怎样才能停止意图服务。在这里,我将我的 Intent 服务代码和广播接收器放入关闭服务。
public class DownloadService extends IntentService {
public DownloadService() {
super(DownloadService.class.getName());
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
InputStream input;
OutputStream output;
HttpURLConnection connection;
Intent intent1 = new Intent();
intent1.setAction("com.demo.downloading");
try {
URL url = new URL(urlToDownload);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return;
}
final int fileLength = connection.getContentLength();
input = connection.getInputStream();
output = new FileOutputStream(file);
byte data[] = new byte[8192];
long total = 0;
int count, latestPercentDone;
int percentDone = -1;
while ((count = input.read(data)) != -1) {
total += count;
latestPercentDone = (int) (total * 100 / fileLength);
if (percentDone != latestPercentDone) {
percentDone = latestPercentDone;
if (percentDone < 100) {
if (percentDone != 0) {
intent1.putExtra("progress", "" + percentDone);
intent1.putExtra("IsCancel", false);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent1);
}
}
if (percentDone == 100) {
intent1.putExtra("progress", "" + 0);
intent1.putExtra("IsCancel", false);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent1);
}
}
output.write(data, 0, count);
if (StaticFields.cancelDownload) {
Log.d(TAG, "onHandleIntent: Download Cancel");
this.stopSelf();
}
}
output.close();
} catch (IOException e) {
intent1.putExtra("progress", "" + (-1));
intent1.putExtra("IsCancel", true);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent1);
e.printStackTrace();
is_all_download = false;
}
}
}
我的广播接收器类 OnReceive方法()
if (intent.getAction() != null) {
if (action.equals("notification_cancelled")) {
Global.cancelDownload = true;
Intent intent1 = new Intent();
intent1.setAction("com.demo.downloading");
intent1.putExtra("IsCancel", true);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent1);
}
}
}
LocalBroadcast 管理器接收方法
boolean isCancel = intent.getBooleanExtra("IsCancel", false);
if (isCancel) {
Global.cancelDownload = true;
mContext.stopService(serviceIntent);
}
【问题讨论】:
-
其实我对下载管理器一无所知,而且我想用取消下载按钮在通知中显示进度,所以......
标签: android android-service android-notifications android-intentservice