码迷,mamicode.com
首页 > 移动开发 > 详细

android 原生的DownloadManager

时间:2014-10-27 16:59:08      阅读:443      评论:0      收藏:0      [点我收藏+]

标签:des   android   style   blog   http   io   color   os   ar   

代码:

 

public class MainActivity extends Activity {
    private DownloadManager downloadManager;
    public static final String DOWNLOAD_FOLDER_NAME = "Trinea";
    public static final String DOWNLOAD_FILE_NAME = "MeiLiShuo.apk";
    public static final String APK_URL = "http://img.meilishuo.net/css/images/AndroidShare/Meilishuo_3.6.1_10006.apk";
    public static final String KEY_NAME_DOWNLOAD_ID = "downloadId";
    private long downloadId = 0;
    private CompleteReceiver completeReceiver;

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        findViewById(R.id.button1).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                File folder = Environment
                        .getExternalStoragePublicDirectory(DOWNLOAD_FOLDER_NAME);
                if (!folder.exists() || !folder.isDirectory()) {
                    folder.mkdirs();
                }

                DownloadManager.Request request = new DownloadManager.Request(
                        Uri.parse(APK_URL));
                request.setDestinationInExternalPublicDir(DOWNLOAD_FOLDER_NAME,
                        DOWNLOAD_FILE_NAME);
                request.setTitle("美丽传说");
                request.setDescription("meilishuo desc");
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setVisibleInDownloadsUi(false);
                // request.allowScanningByMediaScanner();
                // request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
                // request.setShowRunningNotification(false);
                // request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
                //application/cn.trinea.download.file
                request.setMimeType("application/vnd.android.package-archive");
                downloadId = downloadManager.enqueue(request);
                /** save download id to preferences **/
            }
        });
    }

    private void init() {
        // TODO Auto-generated method stub
        completeReceiver = new CompleteReceiver();
        /** register download success broadcast **/
        registerReceiver(completeReceiver, new IntentFilter(
                DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    }

    private int getInt(long downloadId, String columnName) {
        DownloadManager.Query query = new DownloadManager.Query()
                .setFilterById(downloadId);
        int result = -1;
        Cursor c = null;
        try {
            c = downloadManager.query(query);
            if (c != null && c.moveToFirst()) {
                result = c.getInt(c.getColumnIndex(columnName));
            }
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return result;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(completeReceiver);
    }

    class CompleteReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            /**
             * get the id of download which have download success, if the id is
             * my id and it‘s status is successful, then install it
             **/
            long completeDownloadId = intent.getLongExtra(
                    DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (completeDownloadId == downloadId) {

                // if download successful, install apk
                // if (downloadManagerPro.getStatusById(downloadId) ==
                // DownloadManager.STATUS_SUCCESSFUL) {
                if (getInt(downloadId, DownloadManager.COLUMN_STATUS) == DownloadManager.STATUS_SUCCESSFUL) {
                    String apkFilePath = new StringBuilder(Environment
                            .getExternalStorageDirectory().getAbsolutePath())
                            .append(File.separator)
                            .append(DOWNLOAD_FOLDER_NAME)
                            .append(File.separator).append(DOWNLOAD_FILE_NAME)
                            .toString();
                    install(context, apkFilePath);
                }
            }
        }
    };

    /**
     * install app
     * 
     * @param context
     * @param filePath
     * @return whether apk exist
     */
    public static boolean install(Context context, String filePath) {
        Intent i = new Intent(Intent.ACTION_VIEW);
        File file = new File(filePath);
        if (file != null && file.length() > 0 && file.exists() && file.isFile()) {
            i.setDataAndType(Uri.parse("file://" + filePath),
                    "application/vnd.android.package-archive");
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);
            return true;
        }
        return false;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

清单文件里的权限:

 <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.BROADCAST_STICKY" />
    <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />

 

android 原生的DownloadManager

标签:des   android   style   blog   http   io   color   os   ar   

原文地址:http://www.cnblogs.com/yujian-bcq/p/4054375.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!