使用服务管理android中的队列
我有一个具有“回收器”视图的活动,每个列表项都有一个下载按钮。内部按钮单击事件我管理呼叫下载服务。因此,当用户单击多个带有自定义通知更新的下载按钮时,我如何管理队列 我在谷歌上搜索并尝试了以下解决方案: 但是没有找到实现队列通知更新的正确方法 这是我的下载服务代码:使用服务管理android中的队列,android,queue,Android,Queue,我有一个具有“回收器”视图的活动,每个列表项都有一个下载按钮。内部按钮单击事件我管理呼叫下载服务。因此,当用户单击多个带有自定义通知更新的下载按钮时,我如何管理队列 我在谷歌上搜索并尝试了以下解决方案: 但是没有找到实现队列通知更新的正确方法 这是我的下载服务代码: public class DownloadApkService extends Service { private NotificationCompat.Builder notificationBuilder;
public class DownloadApkService extends Service {
private NotificationCompat.Builder notificationBuilder;
private NotificationManager notificationManager;
String downloadLocation;
String appId = null;
String appLink = null;
String appName = null;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("Queue", "queue");
appId = intent.getStringExtra(Constants.COM_APP_ID);
appLink = intent.getStringExtra(Constants.COM_APP_LINK);
appName = intent.getStringExtra(Constants.COM_APP_NAME);
Thread thread=new Thread(new MyThread(startId));
thread.start();
return START_STICKY;
}
final class MyThread implements Runnable {
int service_id;
MyThread(int service_id) {
this.service_id = service_id;
}
@Override
public void run() {
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationBuilder = new NotificationCompat.Builder(DownloadApkService.this)
.setSmallIcon(R.drawable.ic_list_app_icon)
.setContentTitle(appName).setProgress(0, 0, true)
.setContentText("Downloading APK")
.setOngoing(true)
.setAutoCancel(true);
notificationManager.notify(0, notificationBuilder.build());
downloadApk();
}
}
private void downloadApk() {
downloadLocation = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
String fileName = appName + ".apk";
downloadLocation += fileName;
File sourceFile = new File(downloadLocation);
if (sourceFile.exists()) {
sourceFile.delete();
}
Intent intentResponse = new Intent();
intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK);
intentResponse.putExtra(Constants.COM_APP_ID, appId);
intentResponse.putExtra(Constants.COM_APK_DOWNLOAD_PERCENTAGE, "0");
sendBroadcast(intentResponse);
new DownloadFileFromURL().execute(appLink);
}
public void installApk(Uri uri) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
install.setDataAndType(uri,
"application/vnd.android.package-archive");
DownloadApkService.this.startActivity(install);
}
/**
* Background Async Task to download file
*/
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Bar Dialog
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* Downloading file in background thread
*/
@Override
protected String doInBackground(String... f_url) {
int count;
try {
Log.e("ULR", f_url[0]);
URL url = new URL(f_url[0].trim());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = connection.getContentLength();
Log.e("Length", lenghtOfFile + "");
// download the file
InputStream input = connection.getInputStream();
downloadLocation = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
String fileName = appName + ".apk";
downloadLocation += fileName;
// Output stream
FileOutputStream output = new FileOutputStream(downloadLocation);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getStackTrace().toString());
}
return null;
}
/**
* Updating progress bar
*/
protected void onProgressUpdate(String... progress) {
// setting progress percentage
Intent intentResponse = new Intent();
intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK);
intentResponse.putExtra(Constants.COM_APP_ID, appId);
intentResponse.putExtra(Constants.COM_APK_DOWNLOAD_PERCENTAGE, progress[0]);
sendBroadcast(intentResponse);
}
/**
* After completing background task Dismiss the progress dialog
**/
@Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
notificationManager.cancel(0);
installApk(Uri.fromFile(new File(downloadLocation)));
}
}
}
公共类下载apkservice扩展服务{
私人通知建筑商通知建筑商;
私人通知经理通知经理;
字符串下载位置;
字符串appId=null;
字符串appLink=null;
字符串appName=null;
@可空
@凌驾
公共IBinder onBind(意向){
返回null;
}
@凌驾
public void onCreate(){
super.onCreate();
}
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId){
Log.e(“队列”、“队列”);
appId=intent.getStringExtra(Constants.COM\u APP\u ID);
appLink=intent.getStringExtra(Constants.COM\u APP\u链接);
appName=intent.getStringExtra(Constants.COM\u APP\u NAME);
线程线程=新线程(新的MyThread(startId));
thread.start();
返回开始时间;
}
最后一个类MyThread实现Runnable{
内部服务标识;
MyThread(内部服务\u id){
this.service\u id=service\u id;
}
@凌驾
公开募捐{
notificationManager=(notificationManager)getSystemService(Context.NOTIFICATION\u服务);
notificationBuilder=新建NotificationCompat.Builder(下载apkservice.this)
.setSmallIcon(R.drawable.ic_列表_应用_图标)
.setContentTitle(appName).setProgress(0,0,true)
.setContentText(“下载APK”)
.正在进行(正确)
.setAutoCancel(真);
notificationManager.notify(0,notificationBuilder.build());
下载apk();
}
}
私有void下载apk(){
downloadLocation=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_下载)+“/”;
字符串文件名=appName+“.apk”;
下载位置+=文件名;
文件源文件=新文件(下载位置);
if(sourceFile.exists()){
sourceFile.delete();
}
意向意向响应=新意向();
intentResponse.setAction(常数.ACTION\u下载\u APK);
intentResponse.putExtra(Constants.COM\u APP\u ID,appId);
intentResponse.putExtra(Constants.COM_APK_DOWNLOAD_PERCENTAGE,“0”);
发送广播(内部响应);
新建下载文件fromURL().execute(appLink);
}
公共void installApk(Uri){
安装意图=新意图(意图.动作\u视图);
安装.设置标志(意图.标志\活动\清除\顶部);
install.addFlags(Intent.FLAG\u ACTIVITY\u NEW\u TASK);
install.setDataAndType(uri,
“application/vnd.android.package归档文件”);
下载apkservice.this.startActivity(安装);
}
/**
*要下载文件的后台异步任务
*/
类DownloadFileFromURL扩展异步任务{
/**
*启动后台线程前显示进度条对话框
*/
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
}
/**
*在后台线程中下载文件
*/
@凌驾
受保护的字符串doInBackground(字符串…f_url){
整数计数;
试一试{
Log.e(“ULR”,f_url[0]);
URL=新URL(f_URL[0].trim());
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
connection.connect();
//这将非常有用,以便您可以显示一个典型的0-100%
//进度条
int lenghtOfFile=connection.getContentLength();
Log.e(“长度”,lenghtOfFile+”);
//下载该文件
InputStream输入=连接。getInputStream();
downloadLocation=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_下载)+“/”;
字符串文件名=appName+“.apk”;
下载位置+=文件名;
//输出流
FileOutputStream输出=新的FileOutputStream(下载位置);
字节数据[]=新字节[1024];
长总计=0;
而((计数=输入。读取(数据))!=-1){
总数+=计数;
//发布进度。。。。
//在此之后,将调用onProgressUpdate
出版进度(“+(int)((总计*100)/长度文档));
//将数据写入文件
输出.写入(数据,0,计数);
}
//冲洗输出
output.flush();
//合流
output.close();
input.close();
}捕获(例外e){
Log.e(“错误:”,e.getStackTrace().toString());
}
返回null;
}
/**
*更新进度条
*/
受保护的void onProgressUpdate(字符串…进度){
//设置进度百分比
意向意向响应=新意向();
intentResponse.setAction(常数.ACTION\u下载\u APK);
intentResponse.putExtra(Constants.COM\u APP\u ID,appId);
intentResponse.putExtra(Constants.COM_APK_DOWNLOAD_百分比,进度[0]);
发送广播(内部响应);
}
/**
*完成后台任务后,关闭“进度”对话框
**/
public class DownloadApkService extends Service {
private NotificationManager notificationManager = null;
String downloadLocation;
String appId = null;
String appLink = null;
String appName = null;
String isApkFromServer = null;
public boolean isDownloading = false;
public static Queue<QueueData> downloadQueue = new LinkedList<>();
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (isDownloading) {
QueueData queueData = new QueueData();
queueData.setAppId(intent.getStringExtra(Constants.COM_APP_ID));
queueData.setAppLink(intent.getStringExtra(Constants.COM_APP_LINK));
queueData.setIsApkFromServer(intent.getStringExtra(Constants.COM_APK_FROM_SERVER));
queueData.setAppName(intent.getStringExtra(Constants.COM_APP_NAME));
downloadQueue.add(queueData);
Intent intentQueueingApk = new Intent();
intentQueueingApk.setAction(Constants.ACTION_QUEUEING_APK);
sendBroadcast(intentQueueingApk);
return START_NOT_STICKY;
} else {
appId = intent.getStringExtra(Constants.COM_APP_ID);
appLink = intent.getStringExtra(Constants.COM_APP_LINK);
appName = intent.getStringExtra(Constants.COM_APP_NAME);
isApkFromServer = intent.getStringExtra(Constants.COM_APK_FROM_SERVER);
}
Thread thread = new Thread(new MyThread());
thread.start();
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
if (notificationManager != null) {
notificationManager.cancel(0);
}
}
class MyThread implements Runnable {
MyThread() {
}
@Override
public void run() {
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(DownloadApkService.this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(appName).setProgress(0, 0, true)
.setContentText(getResources().getText(R.string.downloading_notification))
.setOngoing(true)
.setAutoCancel(true);
notificationManager.notify(0, notificationBuilder.build());
new DownloadFileFromURL().execute(appLink);
}
}
public void installApk(Uri uri) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
install.setDataAndType(uri,
"application/vnd.android.package-archive");
DownloadApkService.this.startActivity(install);
}
/**
* Background Async Task to download file
*/
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Bar Dialog
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
isDownloading = true;
Intent intentResponse = new Intent();
intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK);
intentResponse.putExtra(Constants.COM_APP_ID, appId);
intentResponse.putExtra(Constants.COM_APK_DOWNLOAD_PERCENTAGE, "0");
sendBroadcast(intentResponse);
}
/**
* Downloading file in background thread
*/
@Override
protected String doInBackground(String... f_url) {
int count;
HttpURLConnection connection=null;
try {
String link=f_url[0].replace(" ","%20");
URL url = new URL(link);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Accept-Encoding", "identity");
int lenghtOfFile = connection.getContentLength();
connection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
// download the file
InputStream input = new BufferedInputStream(connection.getInputStream());
downloadLocation = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
String fileName = appName + ".apk";
downloadLocation += fileName;
File sourceFile = new File(downloadLocation);
if (sourceFile.exists()) {
sourceFile.delete();
}
// Output stream
FileOutputStream output = new FileOutputStream(downloadLocation);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
return "fail";
}finally {
if(connection != null)
connection.disconnect();
}
return "success";
}
/**
* Updating progress bar
*/
protected void onProgressUpdate(String... progress) {
// setting progress percentage
Intent intentResponse = new Intent();
intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK);
intentResponse.putExtra(Constants.COM_APP_ID, appId);
intentResponse.putExtra(Constants.COM_APK_DOWNLOAD_PERCENTAGE, progress[0]);
sendBroadcast(intentResponse);
Intent intentQueueingApk = new Intent();
intentQueueingApk.setAction(Constants.ACTION_QUEUEING_APK);
sendBroadcast(intentQueueingApk);
}
/**
* After completing background task Dismiss the progress dialog
**/
@Override
protected void onPostExecute(String file_url) {
notificationManager.cancel(0);
if (file_url.equals("success")) {
Intent intentResponse = new Intent();
intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK_COMPLETE);
intentResponse.putExtra(Constants.COM_APP_ID, appId);
sendBroadcast(intentResponse);
isDownloading = false;
if (isApkFromServer!=null && isApkFromServer.equals("0")) {
Intent intent = new Intent(DownloadApkService.this, UploadApkService.class);
intent.putExtra(Constants.COM_APP_ID, mAppDetails.getId());
intent.putExtra(Constants.COM_APK_FILE_PATH, downloadLocation);
startService(intent);
}
installApk(Uri.fromFile(new File(downloadLocation)));
} else if (file_url.equals("fail")) {
isDownloading = false;
Intent intentResponse = new Intent();
intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK_FAILED);
intentResponse.putExtra(Constants.COM_APP_ID, appId);
sendBroadcast(intentResponse);
}
if (/*isDownloading &&*/ !downloadQueue.isEmpty()) {
QueueData queueData = downloadQueue.poll();
appId = queueData.getAppId();
appLink = queueData.getAppLink();
appName = queueData.getAppName();
isApkFromServer = queueData.getIsApkFromServer();
Thread thread = new Thread(new MyThread());
thread.start();
}
}
}
@Override
public void onTaskRemoved(Intent rootIntent) {
if (notificationManager != null)
notificationManager.cancel(0);
}
}