使用服务管理android中的队列

时间:2017-02-02 09:52:42

标签: android queue

我有一个带有recycleler-view的活动,每个列表项都有一个下载按钮。内部按钮点击事件我管理下载调用服务。当用户点击多个下载按钮时,如何管理队列通知更新。

我用Google搜索并尝试了一些解决方案:

1.How to Manage Queue of Runnable Tasks in Android

2.how to handle a queue in android?? java

3.Best way to update Activity from a Queue

但找不到使用通知更新实现队列的正确方法。

这是我的DownloadService代码:

New elements is added: 
(
10,
11
)

任何帮助都会得到满足......

1 个答案:

答案 0 :(得分:1)

最后得到了我自己的问题的答案。 我使用java.util包中的Queue类来管理它。 我使用的代码如下:

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);
    }
}

我希望这会对某人有所帮助。