Spl*_*usa 5 notifications android download slowdown android-asynctask
我目前有一个asynctask
从服务器下载mp3.当用户开始下载时,会创建状态栏通知.这将实时显示下载进度.我唯一担心的是手机放慢了几乎.有没有办法延迟显示的进度或使我的代码更快的方法?谢谢.
代码如下:
public class DownloadFile extends AsyncTask<String, String, String> {
CharSequence contentText;
Context context;
CharSequence contentTitle;
PendingIntent contentIntent;
int HELLO_ID = 1;
long time;
int icon;
CharSequence tickerText;
File file;
public void downloadNotification() {
String ns = Context.NOTIFICATION_SERVICE;
notificationManager = (NotificationManager) getSystemService(ns);
icon = R.drawable.sdricontest;
//the text that appears first on the status bar
tickerText = "Downloading...";
time = System.currentTimeMillis();
notification = new Notification(icon, tickerText, time);
context = getApplicationContext();
//the bold font
contentTitle = "Your download is in progress";
//the text that needs to change
contentText = "0% complete";
Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
notificationIntent.setType("audio/*");
contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
notificationManager.notify(HELLO_ID, notification);
}
@Override
protected void onPreExecute() {
//execute the status bar notification
downloadNotification();
super.onPreExecute();
}
@Override
protected String doInBackground(String... url) {
int count;
try {
URL url2 = new URL(sdrUrl);
HttpURLConnection connection = (HttpURLConnection) url2.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
int lengthOfFile = connection.getContentLength();
//make the stop drop rave folder
File sdrFolder = new File(Environment.getExternalStorageDirectory() + "/StopDropRave");
boolean success = false;
if (!sdrFolder.exists()) {
success = sdrFolder.mkdir();
}
if (!success) {
String PATH = Environment.getExternalStorageDirectory()
+ "/StopDropRave/";
file = new File(PATH);
file.mkdirs();
} else {
String PATH = Environment.getExternalStorageDirectory()
+ "/StopDropRave/";
file = new File(PATH);
file.mkdirs();
}
String[] path = url2.getPath().split("/");
String mp3 = path[path.length - 1];
String mp31 = mp3.replace("%20", " ");
String sdrMp3 = mp31.replace("%28", "(");
String sdrMp31 = sdrMp3.replace("%29", ")");
String sdrMp32 = sdrMp31.replace("%27", "'");
File outputFile = new File(file, sdrMp32);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream input = connection.getInputStream();
byte[] data = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) (total * 100 / lengthOfFile));
fos.write(data, 0, count);
}
fos.close();
input.close();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
public void onProgressUpdate(String... progress) {
contentText = Integer.parseInt(progress[0]) + "% complete";
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
notificationManager.notify(HELLO_ID, notification);
super.onProgressUpdate(progress);
}
}
Run Code Online (Sandbox Code Playgroud)
我看到类似的结果,你需要不经常推送更新通知,我改变我的更新只更新几次每秒.(例如,在onProgressUpdate中跟踪您最后一次调用notify,并且只有在您超过前一次调用的100ms时,或者如果您处于最大值时才调用notify.
我曾经有过类似的问题,我使用CountDownTimer解决了。
与@superfell建议类似,您可以在下载文件时定期调用AsyncTask的进度更新。并且仅在特定间隔调用通知管理器。
在调用start()
CountDownTimer之后,它将onTick()
在每个固定的时间间隔后调用函数,并且将onFinish()
在定时器超时或显式调用时调用。cancel()
函数只会取消计时器,不会调用onFinish()
方法。
class DownloadMaterial extends AsyncTask<String, String, String> {
CountDownTimer cdt;
int id = i;
NotificationManager mNotifyManager;
NotificationCompat.Builder mBuilder;
@Override
protected void onPreExecute() {
/**
* Create custom Count Down Timer
*/
cdt = new CountDownTimer(100 * 60 * 1000, 500) {
public void onTick(long millisUntilFinished) {
mNotifyManager.notify(id, mBuilder.build());
}
public void onFinish() {
mNotifyManager.notify(id, mBuilder.build());
}
};
}
@Override
protected String doInBackground(String... strings) {
/**
* Start timer to update Notification
* Set Progress to 20 after connection
* Build Notification
* Increment Progress
* Download and Save file
*/
try {
mNotifyManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(context);
mBuilder.setContentTitle("Downloading File")
.setContentText(file_name)
.setProgress(0, 100, false)
.setOngoing(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(Notification.PRIORITY_LOW);
// Initialize Objects here
publishProgress("5");
mNotifyManager.notify(id, mBuilder.build());
cdt.start();
// Create connection here
publishProgress("20");
// Download file here
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) (20 + (total * 80 / fileLength)));
output.write(data, 0, count);
}
} catch (Exception e) {
return "Failed";
}
return "Success";
}
@Override
protected void onProgressUpdate(String... values) {
/**
* Update Download Progress
*/
mBuilder.setContentInfo(values[0] + "%")
.setProgress(100, Integer.parseInt(values[0]), false);
}
@Override
protected void onPostExecute(String s) {
String title;
if (s.equals("Success")) {
title = "Downloaded";
} else {
title = "Error Occurred";
}
mBuilder.setContentTitle(title)
.setContentInfo("")
.setOngoing(false)
.setProgress(0, 0, false);
cdt.onFinish();
cdt.cancel();
}
}
Run Code Online (Sandbox Code Playgroud)
最好先打电话onFinish()
然后再打电话cancel()
。
归档时间: |
|
查看次数: |
10993 次 |
最近记录: |