apk更新、下载、安装(三)---DownloadManager ui方式【有卡顿bug】

来源:互联网 发布:女生围巾品牌 知乎 编辑:程序博客网 时间:2024/06/18 10:15

文件下载 点击打开链接下载。。。。。

这个demo有个bug 1、下载时候通知栏很卡 2、如果下载时,没有下载完毕,清掉通知栏,下载在启动报错

由于对这个系统下载类不熟悉,大神看到后,有解决方案的话,留言,多谢了

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".MainActivity" >    <Button        android:id="@+id/button1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_marginTop="10dp"        android:text="@string/download1" />    <ProgressBar        android:id="@+id/progress1"        style="@android:style/Widget.ProgressBar.Horizontal"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginTop="5dip" /></LinearLayout>

EpaApplication

package com.example.indownloaddemo;import android.app.Application;public class EpaApplication extends Application {    static EpaApplication epp;    @Override    public void onCreate() {        super.onCreate();        epp = this;    }    public static EpaApplication getEpaApplication() {        return epp;    }}

MainActivity

package com.example.indownloaddemo;import java.io.File;import android.app.Activity;import android.app.Notification;import android.app.NotificationManager;import android.content.Context;import android.content.Intent;import android.net.Uri;import android.os.Bundle;import android.os.Environment;import android.os.Handler;import android.os.Message;import android.support.v4.app.NotificationCompat;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ProgressBar;import android.widget.TextView;import com.thin.downloadmanager.DownloadManager;import com.thin.downloadmanager.DownloadRequest;import com.thin.downloadmanager.DownloadRequest.Priority;import com.thin.downloadmanager.DownloadStatusListener;import com.thin.downloadmanager.ThinDownloadManager;public class MainActivity extends Activity implements OnClickListener {    private DownloadManager downloadManager;    //下载的线程数    private static final int DOWNLOAD_THREAD_POOL_SIZE = 4;    Button mDownload1;    ProgressBar mProgress1;    Context context;    /**     * 服务端apk路径       */    private static final String FILE1 = "http://img.meilishuo.net/css/images/AndroidShare/Meilishuo_3.6.1_10006.apk";    MyDownloadListner myDownloadStatusListener = new MyDownloadListner();    int downloadId1 = 0;    private DownloadRequest request1;    EppNotificationControl notificationControl;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        context = this;        createSDCardDir("epp.apk");        initView();        initDownload();        notificationControl = new EppNotificationControl(this.urlPath);    }    private void initView() {        mDownload1 = (Button) findViewById(R.id.button1);        mProgress1 = (ProgressBar) findViewById(R.id.progress1);        mProgress1.setMax(100);        mProgress1.setProgress(0);        downloadManager = new ThinDownloadManager(DOWNLOAD_THREAD_POOL_SIZE);        mDownload1.setOnClickListener(this);    }    private void initDownload() {        Uri downloadUri = Uri.parse(FILE1);        Uri destinationUri = Uri.parse(urlPath);        Log.e("TAG", urlPath);        request1 = new DownloadRequest(downloadUri)                .setDestinationURI(destinationUri).setPriority(Priority.HIGH)                .setDownloadListener(myDownloadStatusListener);    }    @Override    public void onClick(View v) {        switch (v.getId()) {            case R.id.button1:                if (downloadManager.query(downloadId1) == DownloadManager.STATUS_NOT_FOUND) {                    downloadId1 = downloadManager.add(request1);                }                notificationControl.showProgressNotify();                break;        }    }    @Override    protected void onDestroy() {        super.onDestroy();        downloadManager.release();    }    class MyDownloadListner implements DownloadStatusListener {        @Override        public void onDownloadComplete(int id) {            Log.e("TAG", "download completed");            if (id == downloadId1) {            }        }        @Override        public void onDownloadFailed(int id, int errorCode, String errorMessage) {            Log.e("TAG", "DownloadFailed");            if (id == downloadId1) {                mProgress1.setProgress(0);            }        }        @Override        public void onProgress(int id, long totalBytes, long downloadedBytes,                int progress) {            Log.e("TAG", progress + "");            if (id == downloadId1) {                mProgress1.setProgress(progress);                notificationControl.updateNotification(progress);            }        }    }    String urlPath;    public String createSDCardDir(String name) {        if (Environment.MEDIA_MOUNTED.equals(Environment                .getExternalStorageState())) {            File sdcardDir = Environment.getExternalStorageDirectory();            String path = sdcardDir.getPath() + "/MUDOWN";            File dir = new File(path);            if (!dir.exists()) {                dir.mkdirs();            }            File file = new File(dir + File.separator + name);            if (!file.exists()) {                try {                    file.createNewFile();                } catch (Exception e) {                }                urlPath = file.getPath();            }        }        return urlPath;    }}

EppNotificationControl

package com.example.indownloaddemo;import java.io.File;import android.app.Notification;import android.app.NotificationManager;import android.content.Intent;import android.net.Uri;import android.os.Environment;import android.os.Handler;import android.os.Message;import android.support.v4.app.NotificationCompat;public class EppNotificationControl {    NotificationManager mNotificationManager;    NotificationCompat.Builder mBuilder;    String urlPath;    int progress;    final int NOTIFYCATIONID = 1001;    public EppNotificationControl(String urlPath) {        initNotifycation();        this.urlPath = urlPath;    }    private void initNotifycation() {        mNotificationManager = (NotificationManager) EpaApplication                .getEpaApplication()                .getSystemService(                        EpaApplication.getEpaApplication().NOTIFICATION_SERVICE);        mBuilder = new NotificationCompat.Builder(                EpaApplication.getEpaApplication());        mBuilder.setWhen(System.currentTimeMillis()).setSmallIcon(                R.drawable.ic_launcher);    }    public void showProgressNotify() {        mBuilder.setContentTitle("等待下载").setContentText("进度:")                .setTicker("开始下载");// 通知首次出现在通知栏,带上升动画效果的        Notification mNotification = mBuilder.build();        mNotification.flags = Notification.FLAG_ONGOING_EVENT;//        // 确定进度的        mBuilder.setProgress(100, progress, false); // 这个方法是显示进度条 设置为true就是不确定的那种进度条效果        mNotificationManager.notify(NOTIFYCATIONID, mNotification);    }    /** 设置下载进度 */    public void updateNotification(int progress) {        Notification mNotification = mBuilder.build();        mNotification.flags = Notification.FLAG_ONGOING_EVENT;//        mBuilder.setProgress(100, progress, false); // 这个方法是显示进度条        mBuilder.setContentText("下载中...").setContentTitle("");        if (progress >= 100) {            mBuilder.setContentText("").setContentTitle("完成");            new Thread(new Runnable() {                public void run() {                    Message msg = handler.obtainMessage();                    msg.sendToTarget();                }            }).start();        }        mNotificationManager.notify(NOTIFYCATIONID, mNotification);    }    /**     * 异步安装apk     */    Handler handler = new Handler() {        public void handleMessage(android.os.Message msg) {            Intent apkIntent = new Intent();            apkIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);            apkIntent.setAction(android.content.Intent.ACTION_VIEW);            File apkFile = new File(urlPath);            Uri uri = Uri.fromFile(apkFile);            apkIntent.setDataAndType(uri,                    "application/vnd.android.package-archive");            EpaApplication.getEpaApplication().startActivity(apkIntent);            mNotificationManager.cancel(NOTIFYCATIONID);// 删除一个特定的通知ID对应的通知        };    };}


0 0