Android 多个下载的多个通知
在stackoverflow中,我实现了多次下载。但我面临以下问题: ==>当下载多个文件时,文件的进度是混合的,即如果第一个文件下载1.15mb/5mb,第二个文件下载5mb/10mb,则第一个文件的通知交替显示“下载1.15/5mb”和“下载5/10mb”。其他文件也是如此。所以我的问题是如何根据文件本身的大小显示正确的进度 下载完成后,文件名也会混合,即在两次下载的通知中都会显示“filedownload:1st.pdf” 这是我的DownloadService.class:Android 多个下载的多个通知,android,Android,在stackoverflow中,我实现了多次下载。但我面临以下问题: ==>当下载多个文件时,文件的进度是混合的,即如果第一个文件下载1.15mb/5mb,第二个文件下载5mb/10mb,则第一个文件的通知交替显示“下载1.15/5mb”和“下载5/10mb”。其他文件也是如此。所以我的问题是如何根据文件本身的大小显示正确的进度 下载完成后,文件名也会混合,即在两次下载的通知中都会显示“filedownload:1st.pdf” 这是我的DownloadService.class: public
public class DownloadService extends Service {
final static String TAG = DownloadService.class.getSimpleName();
String downloadUrl, saveName;
int id;
public DownloadService() {
super();
}
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
private NotificationCompat.Builder notificationBuilder;
private NotificationManager notificationManager;
private float totalFileSize;
public static boolean isDownloading = false;
@Override
public void onCreate() {
super.onCreate();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
downloadUrl = intent.getStringExtra("downloadurl");
saveName = intent.getStringExtra("savename");
id = intent.getIntExtra("id", 0);
HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
return START_STICKY;
}
private void isDownloading(boolean b, int id) {
this.id = id;
isDownloading = b;
}
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
Log.d(TAG, "onHandleIntent: ");
//SHOW NOTIFICATION IN WHILE RUNNING BACKGROUND SERVICES
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.logout)
.setContentTitle("Dishanirdesh-Plus")
.setContentText("Downloading: " + saveName)
.setOngoing(true)
.setAutoCancel(true);
notificationManager.notify(id, notificationBuilder.build());
initDownload(downloadUrl, id);
}
}
private void initDownload(String downloadUrl, int id) {
Log.d(TAG, "initDownload: ");
SetupRetrofit setupRetrofit = new SetupRetrofit();
Retrofit retrofit = setupRetrofit.getRetrofit();
DownloadApiInterface retrofitInterface = retrofit.create(DownloadApiInterface.class);
Call<ResponseBody> request = retrofitInterface.downloadFile(downloadUrl);
try {
downloadFile(request.execute().body(), id);
isDownloading(true, id);
} catch (IOException e) {
e.printStackTrace();
isDownloading(false, id);
notificationManager.cancel(id);
Toast.makeText(getApplicationContext(),LinkConfig.BOOK_ERROR_MSG, Toast.LENGTH_SHORT).show();
}
}
private void downloadFile(ResponseBody body, int id) throws IOException {
Log.d(TAG, "downloadFile: ");
int count;
byte data[] = new byte[1024 * 4];
long fileSize = body.contentLength();
InputStream bis = new BufferedInputStream(body.byteStream(), 1024 * 8);
String bookPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
LinkConfig.DISHANIRDESH_PLUS_FOLDER_NAME + "/" + LinkConfig.BOOK_SUB_FOLDER_NAME + "/" + saveName;
File outputFile = new File(bookPath);
OutputStream output = new FileOutputStream(outputFile);
long total = 0;
long startTime = System.currentTimeMillis();
int timeCount = 1;
while ((count = bis.read(data)) != -1) {
total += count;
//Converting byte to mega-byte
totalFileSize = (float) (fileSize / (Math.pow(1024, 2)));//shows in MB
double current = (total / (Math.pow(1024, 2)));
int progress = (int) ((total * 100) / fileSize);
long currentTime = System.currentTimeMillis() - startTime;
Download download = new Download();
download.setTotalFileSize(totalFileSize);
Log.d(TAG, "downloadFile: totalFileSize: " + totalFileSize);
if (currentTime > 10 * timeCount) {
download.setCurrentFileSize((float) current);
download.setProgress(progress);
sendNotification(download, id);
timeCount++;
}
output.write(data, 0, count);
}
output.flush();
output.close();
bis.close();
Encryption encryption = new Encryption();
Log.d(TAG, "downloadFile: encryption");
try {
try {
encryption.encrypt(bookPath);
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
onDownloadComplete(id);
}
private void sendNotification(Download download, int id) {
Log.d(TAG, "sendNotification: ");
//Send to EbookDetailActivity
sendIntent(download, id);
//Send to Notification Bar
notificationBuilder.setProgress(100, download.getProgress(), false);
notificationBuilder.setContentText("Downloading file " +new DecimalFormat("##.##").format(download.getCurrentFileSize()) +"/" +new DecimalFormat("##.##").format(totalFileSize)+"MB");
notificationManager.notify(id, notificationBuilder.build());
}
private void sendIntent(Download download, int id) {
Log.d(TAG, "sendIntent: ");
Intent intent = new Intent(EbookDetailActivity.MESSAGE_PROGRESS);
intent.putExtra("download", download);
intent.putExtra("id", id);
LocalBroadcastManager.getInstance(DownloadService.this).sendBroadcast(intent);
}
private void onDownloadComplete(int id) {
Log.d(TAG, "onDownloadComplete: ");
isDownloading(false, id);
try {
Download download = new Download();
download.setProgress(100);
sendIntent(download, id);
notificationManager.cancel(id);
notificationBuilder.setProgress(0, 0, false);
notificationBuilder .setContentText("Tap to Open");
notificationManager.notify(id, notificationBuilder.build());
Intent intent = new Intent(this, EbookDetailActivity.class);
intent.putExtra("savename", saveName);
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder
.setAutoCancel(true)
.setContentIntent(pIntent)
.setContentTitle("File Downloaded: " + saveName);
notificationManager.notify(id, notificationBuilder.build());
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onTaskRemoved(Intent rootIntent) {
notificationManager.cancel(id);
}
公共类下载服务扩展服务{
最终静态字符串标记=DownloadService.class.getSimpleName();
字符串下载URL,保存名称;
int-id;
公共下载服务(){
超级();
}
专用活套;
私有服务处理程序mServiceHandler;
私人通知建筑商通知建筑商;
私人通知经理通知经理;
私有浮动文件大小;
公共静态布尔值isDownloading=false;
@凌驾
public void onCreate(){
super.onCreate();
}
@可空
@凌驾
公共IBinder onBind(意向){
返回null;
}
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId){
downloadUrl=intent.getStringExtra(“downloadUrl”);
saveName=intent.getStringExtra(“saveName”);
id=intent.getIntExtra(“id”,0);
HandlerThread线程=新的HandlerThread(“ServiceStartArguments”,Process.thread\u PRIORITY\u BACKGROUND);
thread.start();
mServiceLooper=thread.getLooper();
MSServiceHandler=新的ServiceHandler(MSServiceLooper);
Message msg=mServiceHandler.obtainMessage();
msg.arg1=startId;
mServiceHandler.sendMessage(msg);
返回开始时间;
}
私有void isDownloading(布尔b,int-id){
this.id=id;
isDownloading=b;
}
私有最终类ServiceHandler扩展处理程序{
公共服务处理程序(活套-活套){
超级(活套);
}
@凌驾
公共无效handleMessage(消息消息消息){
Log.d(标签“onHandleIntent:”);
//运行后台服务时在中显示通知
notificationManager=(notificationManager)getSystemService(Context.NOTIFICATION\u服务);
notificationBuilder=新建NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(右可绘制。注销)
.setContentTitle(“Dishanirdesh Plus”)
.setContentText(“下载:“+saveName”)
.正在进行(正确)
.setAutoCancel(真);
notificationManager.notify(id,notificationBuilder.build());
初始化下载(下载URL,id);
}
}
私有void initDownload(字符串下载URL,int-id){
Log.d(标签“initDownload:”);
SETUPREFORMAT SETUPREFORMAT=新SETUPREFORMAT();
改装改装=setupRefundation.getRefundation();
DownloadApiInterface-RefundationInterface=Refundation.create(DownloadApiInterface.class);
Call request=interface.downloadFile(downloadUrl);
试一试{
下载文件(request.execute().body(),id);
isDownloading(true,id);
}捕获(IOE异常){
e、 printStackTrace();
isDownloading(false,id);
通知管理器。取消(id);
Toast.makeText(getApplicationContext(),LinkConfig.BOOK\u ERROR\u MSG,Toast.LENGTH\u SHORT).show();
}
}
私有void下载文件(ResponseBody body,int-id)引发IOException{
Log.d(标记“downloadFile:”);
整数计数;
字节数据[]=新字节[1024*4];
long fileSize=body.contentLength();
InputStream bis=新的BufferedInputStream(body.ByTestStream(),1024*8);
字符串bookPath=Environment.getExternalStorageDirectory().getAbsolutePath()+“/”+
LinkConfig.DISHANIRDESH\u PLUS\u FOLDER\u NAME+“/”+LinkConfig.BOOK\u SUB\u FOLDER\u NAME+“/”+saveName;
文件输出文件=新文件(bookPath);
OutputStream output=新文件OutputStream(outputFile);
长总计=0;
long startTime=System.currentTimeMillis();
int timeCount=1;
而((计数=二读(数据))!=-1){
总数+=计数;
//将字节转换为兆字节
totalFileSize=(float)(fileSize/(Math.pow(1024,2));//以MB为单位显示
双电流=(总/(数学功率(1024,2));
int进度=(int)((总计*100)/文件大小);
长currentTime=System.currentTimeMillis()-startTime;
下载=新下载();
下载.setTotalFileSize(totalFileSize);
Log.d(标记“downloadFile:totalFileSize:+totalFileSize”);
如果(当前时间>10*时间计数){
下载.setCurrentFileSize((float)current);
下载.setProgress(progress);
发送通知(下载,id);
timeCount++;
}
输出.写入(数据,0,计数);
}
output.flush();
output.close();
二、关闭();
加密=新加密();
Log.d(标记“downloadFile:encryption”);
试一试{
试一试{
加密。加密(bookPath);
}捕获(无此填充例外){
e、 printStackTrace();
}捕获(InvalidKeyException e){
e、 printStackTrace();
}
}捕获(无算法异常){
e、 printStackTrace();
}
onDownloadComplete(id);
}
私有void发送通知(下载,int-id){
Log.d(标记“sendNotification:”);
//发送到电子书详细信息活动
sendIntent(下载,id);
//发送到通知栏
notificationBuilder.setProgress(100,download.getProgress(),false);
notificationBuilder.setContentText(“下载文件”+新的十进制格式(“###.#####”).format(下载.getCurrentFileSize())+“/”+新的十进制格式(“##.##”).format(总文件大小)+“MB”);
notificationManager.notify(id,notificationBuilder.build());
}
私有void sendIntent(下载downl