本文内容

  • 环境
  • 项目结构
  • 演示下载
  • 参考资料

本文是 github 上 Trinea-Android-commonTrinea-Android-Demo 项目的一部分,将下载部分分离出来,看看如何实现。(不知道此人学了多久,Android 水平不低~ 貌似年龄跟我差不多~

假设,现在有个下载 apk 包的需求,你大概能想到什么?

  • 下载本身;
  • 下载进度;
  • 期间还能取消;
  • 由于网络不好或中断,下载失败,还要能重试;
  • 因为下载的是 apk,下载完还要能提示安装更好,而且,很多手机管理 app,还能静默安装;
  • 还能在手机通知栏看到下载提示;
  • 这些就涉及到 android.app.DownloadManagerandroid.content.BroadcastReceiverandroid.os.Handler

自己下载 Demo 调试一下~

下载 Demo

更多 Demo

环境


  • Windows 2008 R2 64 位
  • Eclipse ADT V22.6.2,Android 4.4.2(API 19)
  • SAMSUNG GT-8618,Android OS 4.1.2

项目结构


图 1 项目结构

图 2 主程序

图 3 下载

(注意:顶部通知栏,是有下载图标的~)

package com.example.download.ui;

 

import java.io.File;

import java.text.DecimalFormat;

import com.example.download.R;

import com.example.download.utils.DownloadManagerPro;

import com.example.download.utils.PreferencesUtils;

import android.annotation.SuppressLint;

import android.app.Activity;

import android.app.DownloadManager;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.content.IntentFilter;

import android.database.ContentObserver;

import android.net.Uri;

import android.os.Bundle;

import android.os.Environment;

import android.os.Handler;

import android.os.Message;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.ProgressBar;

import android.widget.TextView;

import android.widget.Toast;

 

/**

 * DownloadManagerDemo

 * 

 */

public class DownloadManagerDemo extends Activity {

 

    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 Button downloadButton;

    private ProgressBar downloadProgress;

    private TextView downloadTip;

    private TextView downloadSize;

    private TextView downloadPrecent;

    private Button downloadCancel;

 

    private DownloadManager downloadManager;

    private DownloadManagerPro downloadManagerPro;

    private long downloadId = 0;

 

    private MyHandler handler;

 

    private DownloadChangeObserver downloadObserver;

    private CompleteReceiver completeReceiver;

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        

        setContentView(R.layout.download_manager_demo);

        

        handler = new MyHandler();

        downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

        downloadManagerPro = new DownloadManagerPro(downloadManager);

 

        // see android mainfest.xml, 

        // accept minetype of cn.trinea.download.file

        Intent intent = getIntent();

        if (intent != null) {

            /**

             * below android 4.2, intent.getDataString() is

             * file:///storage/sdcard1/Trinea/MeLiShuo.apk<br/>

             * equal or above 4.2 intent.getDataString() is

             * content://media/external/file/29669

             */

            Uri data = intent.getData();

            if (data != null) {

                Toast.makeText(getApplicationContext(), data.toString(), Toast.LENGTH_LONG)

                        .show();

            }

        }

 

        initView();

        initData();

 

        downloadObserver = new DownloadChangeObserver();

        completeReceiver = new CompleteReceiver();

        /** register download success broadcast **/

        registerReceiver(completeReceiver, new IntentFilter(

                DownloadManager.ACTION_DOWNLOAD_COMPLETE));

    }

 

    @Override

    protected void onResume() {

        super.onResume();

        /** observer download change **/

        getContentResolver().registerContentObserver(

                DownloadManagerPro.CONTENT_URI, true, downloadObserver);

        updateView();

    }

 

    @Override

    protected void onPause() {

        super.onPause();

        getContentResolver().unregisterContentObserver(downloadObserver);

    }

 

    @Override

    protected void onDestroy() {

        super.onDestroy();

        unregisterReceiver(completeReceiver);

    }

 

    private void initView() {

        downloadButton = (Button) findViewById(R.id.download_button);

        downloadCancel = (Button) findViewById(R.id.download_cancel);

        downloadProgress = (ProgressBar) findViewById(R.id.download_progress);

        downloadTip = (TextView) findViewById(R.id.download_tip);

        downloadTip

                .setText(getString(R.string.tip_download_file)

                        + Environment

                                .getExternalStoragePublicDirectory(DOWNLOAD_FOLDER_NAME));

        downloadSize = (TextView) findViewById(R.id.download_size);

        downloadPrecent = (TextView) findViewById(R.id.download_precent);

    }

 

    private void initData() {

        /**

         * get download id from preferences.<br/>

         * if download id bigger than 0, means it has been downloaded, then

         * query status and show right text;

         */

        downloadId = PreferencesUtils.getLong(getApplicationContext(), KEY_NAME_DOWNLOAD_ID);

        updateView();

        downloadButton.setOnClickListener(new OnClickListener() {

 

            @Override

            public void onClick(View v) {

                File folder = new File(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(getString(R.string.download_notification_title));

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

                request.setMimeType("application/cn.trinea.download.file");

                

                downloadId = downloadManager.enqueue(request);

                /** save download id to preferences **/

                PreferencesUtils.putLong(getApplicationContext(), KEY_NAME_DOWNLOAD_ID,

                        downloadId);

                updateView();

            }

        });

        downloadCancel.setOnClickListener(new OnClickListener() {

 

            @Override

            public void onClick(View v) {

                downloadManager.remove(downloadId);

                updateView();

            }

        });

    }

 

    /**

     * 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;

    }

 

    class DownloadChangeObserver extends ContentObserver {

 

        public DownloadChangeObserver() {

            super(handler);

        }

 

        @Override

        public void onChange(boolean selfChange) {

            updateView();

        }

 

    }

 

    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) {

                initData();

                updateView();

                // if download successful, install apk

                if (downloadManagerPro.getStatusById(downloadId) == 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);

                }

            }

        }

    };

 

    public void updateView() {

        int[] bytesAndStatus = downloadManagerPro.getBytesAndStatus(downloadId);

        handler.sendMessage(handler.obtainMessage(0, bytesAndStatus[0],

                bytesAndStatus[1], bytesAndStatus[2]));

    }

 

    @SuppressLint("HandlerLeak")

    private class MyHandler extends Handler {

 

        @Override

        public void handleMessage(Message msg) {

            super.handleMessage(msg);

 

            switch (msg.what) {

            case 0:

                int status = (Integer) msg.obj;

                if (isDownloading(status)) {

                    downloadProgress.setVisibility(View.VISIBLE);

                    downloadProgress.setMax(0);

                    downloadProgress.setProgress(0);

                    downloadButton.setVisibility(View.GONE);

                    downloadSize.setVisibility(View.VISIBLE);

                    downloadPrecent.setVisibility(View.VISIBLE);

                    downloadCancel.setVisibility(View.VISIBLE);

 

                    if (msg.arg2 < 0) {

                        downloadProgress.setIndeterminate(true);

                        downloadPrecent.setText("0%");

                        downloadSize.setText("0M/0M");

                    } else {

                        downloadProgress.setIndeterminate(false);

                        downloadProgress.setMax(msg.arg2);

                        downloadProgress.setProgress(msg.arg1);

                        downloadPrecent.setText(getNotiPercent(msg.arg1,

                                msg.arg2));

                        downloadSize.setText(getAppSize(msg.arg1) + "/"

                                + getAppSize(msg.arg2));

                    }

                } else {

                    downloadProgress.setVisibility(View.GONE);

                    downloadProgress.setMax(0);

                    downloadProgress.setProgress(0);

                    downloadButton.setVisibility(View.VISIBLE);

                    downloadSize.setVisibility(View.GONE);

                    downloadPrecent.setVisibility(View.GONE);

                    downloadCancel.setVisibility(View.GONE);

 

                    if (status == DownloadManager.STATUS_FAILED) {

                        downloadButton

                                .setText(getString(R.string.app_status_download_fail));

                    } else if (status == DownloadManager.STATUS_SUCCESSFUL) {

                        downloadButton

                                .setText(getString(R.string.app_status_downloaded));

                    } else {

                        downloadButton

                                .setText(getString(R.string.app_status_download));

                    }

                }

                break;

            }

        }

    }

 

    static final DecimalFormat DOUBLE_DECIMAL_FORMAT = new DecimalFormat("0.##");

 

    public static final int MB_2_BYTE = 1024 * 1024;

    public static final int KB_2_BYTE = 1024;

 

    /**

     * @param size

     * @return

     */

    public static CharSequence getAppSize(long size) {

        if (size <= 0) {

            return "0M";

        }

 

        if (size >= MB_2_BYTE) {

            return new StringBuilder(16).append(

                    DOUBLE_DECIMAL_FORMAT.format((double) size / MB_2_BYTE))

                    .append("M");

        } else if (size >= KB_2_BYTE) {

            return new StringBuilder(16).append(

                    DOUBLE_DECIMAL_FORMAT.format((double) size / KB_2_BYTE))

                    .append("K");

        } else {

            return size + "B";

        }

    }

 

    public static String getNotiPercent(long progress, long max) {

        int rate = 0;

        if (progress <= 0 || max <= 0) {

            rate = 0;

        } else if (progress > max) {

            rate = 100;

        } else {

            rate = (int) ((double) progress / max * 100);

        }

        return new StringBuilder(16).append(rate).append("%").toString();

    }

 

    public static boolean isDownloading(int downloadManagerStatus) {

        return downloadManagerStatus == DownloadManager.STATUS_RUNNING

                || downloadManagerStatus == DownloadManager.STATUS_PAUSED

                || downloadManagerStatus == DownloadManager.STATUS_PENDING;

    }

}

以及自定义的 DownloadManagerPro 和 PreferencesUtils 类,代码如下所示:

package com.example.download.utils;

 

import java.lang.reflect.Method;

 

import android.app.DownloadManager;

import android.app.DownloadManager.Request;

import android.database.Cursor;

import android.net.Uri;

import android.os.Build;

 

/**

 * DownloadManagerPro

 */

public class DownloadManagerPro {

 

    public static final Uri CONTENT_URI = Uri

            .parse("content://downloads/my_downloads");

    /** represents downloaded file above api 11 **/

    public static final String COLUMN_LOCAL_FILENAME = "local_filename";

    /** represents downloaded file below api 11 **/

    public static final String COLUMN_LOCAL_URI = "local_uri";

 

    public static final String METHOD_NAME_PAUSE_DOWNLOAD = "pauseDownload";

    public static final String METHOD_NAME_RESUME_DOWNLOAD = "resumeDownload";

 

    private static boolean isInitPauseDownload = false;

    private static boolean isInitResumeDownload = false;

 

    private static Method pauseDownload = null;

    private static Method resumeDownload = null;

 

    private DownloadManager downloadManager;

 

    public DownloadManagerPro(DownloadManager downloadManager) {

        this.downloadManager = downloadManager;

    }

 

    /**

     * get download status

     * 

     * @param downloadId

     * @return

     */

    public int getStatusById(long downloadId) {

        return getInt(downloadId, DownloadManager.COLUMN_STATUS);

    }

 

    /**

     * get downloaded byte, total byte

     * 

     * @param downloadId

     * @return a int array with two elements

     *         <ul>

     *         <li>result[0] represents downloaded bytes, This will initially be

     *         -1.</li>

     *         <li>result[1] represents total bytes, This will initially be -1.</li>

     *         </ul>

     */

    public int[] getDownloadBytes(long downloadId) {

        int[] bytesAndStatus = getBytesAndStatus(downloadId);

        return new int[] { bytesAndStatus[0], bytesAndStatus[1] };

    }

 

    /**

     * get downloaded byte, total byte and download status

     * 

     * @param downloadId

     * @return a int array with three elements

     *         <ul>

     *         <li>result[0] represents downloaded bytes, This will initially be

     *         -1.</li>

     *         <li>result[1] represents total bytes, This will initially be -1.</li>

     *         <li>result[2] represents download status, This will initially be

     *         0.</li>

     *         </ul>

     */

    public int[] getBytesAndStatus(long downloadId) {

        int[] bytesAndStatus = new int[] { -1, -1, 0 };

        DownloadManager.Query query = new DownloadManager.Query()

                .setFilterById(downloadId);

        Cursor c = null;

        try {

            c = downloadManager.query(query);

            if (c != null && c.moveToFirst()) {

                bytesAndStatus[0] = c

                        .getInt(c

                                .getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));

                bytesAndStatus[1] = c

                        .getInt(c

                                .getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));

                bytesAndStatus[2] = c.getInt(c

                        .getColumnIndex(DownloadManager.COLUMN_STATUS));

            }

        } finally {

            if (c != null) {

                c.close();

            }

        }

        return bytesAndStatus;

    }

 

    /**

     * pause download

     * 

     * @param ids

     *            the IDs of the downloads to be paused

     * @return the number of downloads actually paused, -1 if exception or

     *         method not exist

     */

    public int pauseDownload(long... ids) {

        initPauseMethod();

        if (pauseDownload == null) {

            return -1;

        }

 

        try {

            return ((Integer) pauseDownload.invoke(downloadManager, ids))

                    .intValue();

        } catch (Exception e) {

            /**

             * accept all exception, include ClassNotFoundException,

             * NoSuchMethodException, InvocationTargetException,

             * NullPointException

             */

            e.printStackTrace();

        }

        return -1;

    }

 

    /**

     * resume download

     * 

     * @param ids

     *            the IDs of the downloads to be resumed

     * @return the number of downloads actually resumed, -1 if exception or

     *         method not exist

     */

    public int resumeDownload(long... ids) {

        initResumeMethod();

        if (resumeDownload == null) {

            return -1;

        }

 

        try {

            return ((Integer) resumeDownload.invoke(downloadManager, ids))

                    .intValue();

        } catch (Exception e) {

            /**

             * accept all exception, include ClassNotFoundException,

             * NoSuchMethodException, InvocationTargetException,

             * NullPointException

             */

            e.printStackTrace();

        }

        return -1;

    }

 

    /**

     * whether exist pauseDownload and resumeDownload method in

     * {@link DownloadManager}

     * 

     * @return

     */

    public static boolean isExistPauseAndResumeMethod() {

        initPauseMethod();

        initResumeMethod();

        return pauseDownload != null && resumeDownload != null;

    }

 

    private static void initPauseMethod() {

        if (isInitPauseDownload) {

            return;

        }

 

        isInitPauseDownload = true;

        try {

            pauseDownload = DownloadManager.class.getMethod(

                    METHOD_NAME_PAUSE_DOWNLOAD, long[].class);

        } catch (Exception e) {

            // accept all exception

            e.printStackTrace();

        }

    }

 

    private static void initResumeMethod() {

        if (isInitResumeDownload) {

            return;

        }

 

        isInitResumeDownload = true;

        try {

            resumeDownload = DownloadManager.class.getMethod(

                    METHOD_NAME_RESUME_DOWNLOAD, long[].class);

        } catch (Exception e) {

            // accept all exception

            e.printStackTrace();

        }

    }

 

    /**

     * get download file name

     * 

     * @param downloadId

     * @return

     */

    public String getFileName(long downloadId) {

        return getString(

                downloadId,

                (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB ? COLUMN_LOCAL_URI

                        : COLUMN_LOCAL_FILENAME));

    }

 

    /**

     * get download uri

     * 

     * @param downloadId

     * @return

     */

    public String getUri(long downloadId) {

        return getString(downloadId, DownloadManager.COLUMN_URI);

    }

 

    /**

     * get failed code or paused reason

     * 

     * @param downloadId

     * @return <ul>

     *         <li>if status of downloadId is

     *         {@link DownloadManager#STATUS_PAUSED}, return

     *         {@link #getPausedReason(long)}</li>

     *         <li>if status of downloadId is

     *         {@link DownloadManager#STATUS_FAILED}, return

     *         {@link #getErrorCode(long)}</li>

     *         <li>if status of downloadId is neither

     *         {@link DownloadManager#STATUS_PAUSED} nor

     *         {@link DownloadManager#STATUS_FAILED}, return 0</li>

     *         </ul>

     */

    public int getReason(long downloadId) {

        return getInt(downloadId, DownloadManager.COLUMN_REASON);

    }

 

    /**

     * get paused reason

     * 

     * @param downloadId

     * @return <ul>

     *         <li>if status of downloadId is

     *         {@link DownloadManager#STATUS_PAUSED}, return one of

     *         {@link DownloadManager#PAUSED_WAITING_TO_RETRY}<br/>

     *         {@link DownloadManager#PAUSED_WAITING_FOR_NETWORK}<br/>

     *         {@link DownloadManager#PAUSED_QUEUED_FOR_WIFI}<br/>

     *         {@link DownloadManager#PAUSED_UNKNOWN}</li>

     *         <li>else return {@link DownloadManager#PAUSED_UNKNOWN}</li>

     *         </ul>

     */

    public int getPausedReason(long downloadId) {

        return getInt(downloadId, DownloadManager.COLUMN_REASON);

    }

 

    /**

     * get failed error code

     * 

     * @param downloadId

     * @return one of {@link DownloadManager#ERROR_*}

     */

    public int getErrorCode(long downloadId) {

        return getInt(downloadId, DownloadManager.COLUMN_REASON);

    }

 

    public static class RequestPro extends DownloadManager.Request {

 

        public static final String METHOD_NAME_SET_NOTI_CLASS = "setNotiClass";

        public static final String METHOD_NAME_SET_NOTI_EXTRAS = "setNotiExtras";

 

        private static boolean isInitNotiClass = false;

        private static boolean isInitNotiExtras = false;

 

        private static Method setNotiClass = null;

        private static Method setNotiExtras = null;

 

        /**

         * @param uri

         *            the HTTP URI to download.

         */

        public RequestPro(Uri uri) {

            super(uri);

        }

 

        /**

         * set noti class, only init once

         * 

         * @param className

         *            full class name

         */

        public void setNotiClass(String className) {

            synchronized (this) {

 

                if (!isInitNotiClass) {

                    isInitNotiClass = true;

                    try {

                        setNotiClass = Request.class.getMethod(

                                METHOD_NAME_SET_NOTI_CLASS, CharSequence.class);

                    } catch (Exception e) {

                        // accept all exception

                        e.printStackTrace();

                    }

                }

            }

 

            if (setNotiClass != null) {

                try {

                    setNotiClass.invoke(this, className);

                } catch (Exception e) {

                    /**

                     * accept all exception, include ClassNotFoundException,

                     * NoSuchMethodException, InvocationTargetException,

                     * NullPointException

                     */

                    e.printStackTrace();

                }

            }

        }

 

        /**

         * set noti extras, only init once

         * 

         * @param extras

         */

        public void setNotiExtras(String extras) {

            synchronized (this) {

 

                if (!isInitNotiExtras) {

                    isInitNotiExtras = true;

                    try {

                        setNotiExtras = Request.class

                                .getMethod(METHOD_NAME_SET_NOTI_EXTRAS,

                                        CharSequence.class);

                    } catch (Exception e) {

                        // accept all exception

                        e.printStackTrace();

                    }

                }

            }

 

            if (setNotiExtras != null) {

                try {

                    setNotiExtras.invoke(this, extras);

                } catch (Exception e) {

                    /**

                     * accept all exception, include ClassNotFoundException,

                     * NoSuchMethodException, InvocationTargetException,

                     * NullPointException

                     */

                    e.printStackTrace();

                }

            }

        }

    }

 

    /**

     * get string column

     * 

     * @param downloadId

     * @param columnName

     * @return

     */

    private String getString(long downloadId, String columnName) {

        DownloadManager.Query query = new DownloadManager.Query()

                .setFilterById(downloadId);

        String result = null;

        Cursor c = null;

        try {

            c = downloadManager.query(query);

            if (c != null && c.moveToFirst()) {

                result = c.getString(c.getColumnIndex(columnName));

            }

        } finally {

            if (c != null) {

                c.close();

            }

        }

        return result;

    }

 

    /**

     * get int column

     * 

     * @param downloadId

     * @param columnName

     * @return

     */

    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;

    }

}

package com.example.download.utils;

 

import android.content.Context;

import android.content.SharedPreferences;

 

/**

 * PreferencesUtils, easy to get or put data

 */

public class PreferencesUtils {

 

    public static String PREFERENCE_NAME = "TrineaAndroidCommon";

 

    /**

     * put string preferences

     * 

     * @param context

     * @param key

     *            The name of the preference to modify

     * @param value

     *            The new value for the preference

     * @return True if the new values were successfully written to persistent

     *         storage.

     */

    public static boolean putString(Context context, String key, String value) {

        SharedPreferences settings = context.getSharedPreferences(

                PREFERENCE_NAME, Context.MODE_PRIVATE);

        SharedPreferences.Editor editor = settings.edit();

        editor.putString(key, value);

        return editor.commit();

    }

 

    /**

     * get string preferences

     * 

     * @param context

     * @param key

     *            The name of the preference to retrieve

     * @return The preference value if it exists, or null. Throws

     *         ClassCastException if there is a preference with this name that

     *         is not a string

     * @see #getString(Context, String, String)

     */

    public static String getString(Context context, String key) {

        return getString(context, key, null);

    }

 

    /**

     * get string preferences

     * 

     * @param context

     * @param key

     *            The name of the preference to retrieve

     * @param defaultValue

     *            Value to return if this preference does not exist

     * @return The preference value if it exists, or defValue. Throws

     *         ClassCastException if there is a preference with this name that

     *         is not a string

     */

    public static String getString(Context context, String key,

            String defaultValue) {

        SharedPreferences settings = context.getSharedPreferences(

                PREFERENCE_NAME, Context.MODE_PRIVATE);

        return settings.getString(key, defaultValue);

    }

 

    /**

     * put int preferences

     * 

     * @param context

     * @param key

     *            The name of the preference to modify

     * @param value

     *            The new value for the preference

     * @return True if the new values were successfully written to persistent

     *         storage.

     */

    public static boolean putInt(Context context, String key, int value) {

        SharedPreferences settings = context.getSharedPreferences(

                PREFERENCE_NAME, Context.MODE_PRIVATE);

        SharedPreferences.Editor editor = settings.edit();

        editor.putInt(key, value);

        return editor.commit();

    }

 

    /**

     * get int preferences

     * 

     * @param context

     * @param key

     *            The name of the preference to retrieve

     * @return The preference value if it exists, or -1. Throws

     *         ClassCastException if there is a preference with this name that

     *         is not a int

     * @see #getInt(Context, String, int)

     */

    public static int getInt(Context context, String key) {

        return getInt(context, key, -1);

    }

 

    /**

     * get int preferences

     * 

     * @param context

     * @param key

     *            The name of the preference to retrieve

     * @param defaultValue

     *            Value to return if this preference does not exist

     * @return The preference value if it exists, or defValue. Throws

     *         ClassCastException if there is a preference with this name that

     *         is not a int

     */

    public static int getInt(Context context, String key, int defaultValue) {

        SharedPreferences settings = context.getSharedPreferences(

                PREFERENCE_NAME, Context.MODE_PRIVATE);

        return settings.getInt(key, defaultValue);

    }

 

    /**

     * put long preferences

     * 

     * @param context

     * @param key

     *            The name of the preference to modify

     * @param value

     *            The new value for the preference

     * @return True if the new values were successfully written to persistent

     *         storage.

     */

    public static boolean putLong(Context context, String key, long value) {

        SharedPreferences settings = context.getSharedPreferences(

                PREFERENCE_NAME, Context.MODE_PRIVATE);

        SharedPreferences.Editor editor = settings.edit();

        editor.putLong(key, value);

        return editor.commit();

    }

 

    /**

     * get long preferences

     * 

     * @param context

     * @param key

     *            The name of the preference to retrieve

     * @return The preference value if it exists, or -1. Throws

     *         ClassCastException if there is a preference with this name that

     *         is not a long

     * @see #getLong(Context, String, long)

     */

    public static long getLong(Context context, String key) {

        return getLong(context, key, -1);

    }

 

    /**

     * get long preferences

     * 

     * @param context

     * @param key

     *            The name of the preference to retrieve

     * @param defaultValue

     *            Value to return if this preference does not exist

     * @return The preference value if it exists, or defValue. Throws

     *         ClassCastException if there is a preference with this name that

     *         is not a long

     */

    public static long getLong(Context context, String key, long defaultValue) {

        SharedPreferences settings = context.getSharedPreferences(

                PREFERENCE_NAME, Context.MODE_PRIVATE);

        return settings.getLong(key, defaultValue);

    }

 

    /**

     * put float preferences

     * 

     * @param context

     * @param key

     *            The name of the preference to modify

     * @param value

     *            The new value for the preference

     * @return True if the new values were successfully written to persistent

     *         storage.

     */

    public static boolean putFloat(Context context, String key, float value) {

        SharedPreferences settings = context.getSharedPreferences(

                PREFERENCE_NAME, Context.MODE_PRIVATE);

        SharedPreferences.Editor editor = settings.edit();

        editor.putFloat(key, value);

        return editor.commit();

    }

 

    /**

     * get float preferences

     * 

     * @param context

     * @param key

     *            The name of the preference to retrieve

     * @return The preference value if it exists, or -1. Throws

     *         ClassCastException if there is a preference with this name that

     *         is not a float

     * @see #getFloat(Context, String, float)

     */

    public static float getFloat(Context context, String key) {

        return getFloat(context, key, -1);

    }

 

    /**

     * get float preferences

     * 

     * @param context

     * @param key

     *            The name of the preference to retrieve

     * @param defaultValue

     *            Value to return if this preference does not exist

     * @return The preference value if it exists, or defValue. Throws

     *         ClassCastException if there is a preference with this name that

     *         is not a float

     */

    public static float getFloat(Context context, String key, float defaultValue) {

        SharedPreferences settings = context.getSharedPreferences(

                PREFERENCE_NAME, Context.MODE_PRIVATE);

        return settings.getFloat(key, defaultValue);

    }

 

    /**

     * put boolean preferences

     * 

     * @param context

     * @param key

     *            The name of the preference to modify

     * @param value

     *            The new value for the preference

     * @return True if the new values were successfully written to persistent

     *         storage.

     */

    public static boolean putBoolean(Context context, String key, boolean value) {

        SharedPreferences settings = context.getSharedPreferences(

                PREFERENCE_NAME, Context.MODE_PRIVATE);

        SharedPreferences.Editor editor = settings.edit();

        editor.putBoolean(key, value);

        return editor.commit();

    }

 

    /**

     * get boolean preferences, default is false

     * 

     * @param context

     * @param key

     *            The name of the preference to retrieve

     * @return The preference value if it exists, or false. Throws

     *         ClassCastException if there is a preference with this name that

     *         is not a boolean

     * @see #getBoolean(Context, String, boolean)

     */

    public static boolean getBoolean(Context context, String key) {

        return getBoolean(context, key, false);

    }

 

    /**

     * get boolean preferences

     * 

     * @param context

     * @param key

     *            The name of the preference to retrieve

     * @param defaultValue

     *            Value to return if this preference does not exist

     * @return The preference value if it exists, or defValue. Throws

     *         ClassCastException if there is a preference with this name that

     *         is not a boolean

     */

    public static boolean getBoolean(Context context, String key,

            boolean defaultValue) {

        SharedPreferences settings = context.getSharedPreferences(

                PREFERENCE_NAME, Context.MODE_PRIVATE);

        return settings.getBoolean(key, defaultValue);

    }

}

参考资料


下载 Demo

Android 演示 DownloadManager——Android 下载 apk 包并安装的更多相关文章

  1. Android 4.4(KitKat)中apk包的安装过程

    原文地址:http://blog.csdn.net/jinzhuojun/article/details/25542011 事实上对于apk包的安装.4.4和之前版本号没大的区别. Android中a ...

  2. Android项目实战(三十一):异步下载apk文件并安装(非静默安装)

    前言: 实现异步下载apk文件 并 安装.(进度条对话框显示下载进度的展现方式) 涉及技术点: 1.ProgressDialog   进度条对话框  用于显示下载进度 2.AsyncTask     ...

  3. 离线下载pip包进行安装【转】

    Host-A 不能上网,但是需要在上面安装Python-package 通过另外一台能上网的Host-B主机 1. 下载需要离线安装的Packages 在Host-B上执行如下命令: 安装单个Pack ...

  4. Android 使用 DownloadManager 管理系统下载任务的方法,android管理系统

    从Android 2.3(API level 9)开始Android用系统服务(Service)的方式提供了Download Manager来优化处理长时间的下载操作.Download Manager ...

  5. Android 使用 aapt 命令查看 apk 包名

    一.aapt 是什么 aapt 即Android Asset Packaging Tool,在SDK的build-tools目录下.该工具可以查看,创建, 更新ZIP格式的文档附件(zip, jar, ...

  6. 计算apk包的安装之后占用空间以及运行时占用内存

    1.统计结果如下 计算apk安装占用空间大小方式 为了方式apk包运行时出现缓存数据等对空间计算造成影响.应该先进行安装,然后分别计算空间变化 所有apk包安装完毕后再运行 开启两个cmd窗口 第一个 ...

  7. 【转】用yum只下载rpm包而不安装

    转自:http://liucheng.name/1950/ CentOS用yum安装软件是非常方便的,有时,我们只需要下载其中的rpm包,而不直接安装时咋办呢? 一般情况下,yum是不提供只下载的功能 ...

  8. 18、通过yum命令只下载rpm包不安装

    18.1.说明: 经常遇到服务器没有网络的情况下部署环境,或者创建自己的 yum 仓库等,这时就需要下载 rpm 包. 18.2.方法一,yumdownloader(推荐): 如果只想通过 yum 下 ...

  9. Android 使用 DownloadManager 管理系统下载任务的方法

    在红黑联盟上看到的.这几天一直考虑做一个Notification 的带下载功能的自己定义通知.但没搞出来.无意中在论坛看到这个.先Mark,明天试试. 从Android 2.3(API level 9 ...

随机推荐

  1. 《Go学习笔记 . 雨痕》方法

    一.定义 方法 是与对象实例绑定的特殊函数. 方法 是面向对象编程的基本概念,用于维护和展示对象的自身状态.对象是内敛的,每个实例都有各自不同的独立特征,以 属性 和 方法 来暴露对外通信接口.普通函 ...

  2. getsockname()/getpeername()函数第一次被调用得到0.0.0.0结果

    int getsockname(int sockfd, struct sockaddr *addr, socklen_t *addrlen); getsockname() returns the cu ...

  3. Python yield使用

    https://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/ 您可能听说过,带有 yield 的函数在 Python 中被称 ...

  4. windows nginx出现 was not signaled for 5s的看过来

    windows下 nginx 配置ssl的key是不能存储密码的,否则启动时会提示输入密码 输入后也启动不起来,会报错: 2011/04/18 09:49:09 [alert] 1992#4548: ...

  5. Linux 用户和用户操作

    1,创建组 groupadd test 增加一个test组 2,修改组 groupmod -n test2 test 将test组的名子改成test2 3,删除组 groupdel test2 删除  ...

  6. Git:常用命令(二)

    查看提交历史 git log 撤消操作 任何时候,你都有可能需要撤消刚才所做的某些操作.接下来,我们会介绍一些基本的撤消操作相关的命令.请注意,有些操作并不总是可以撤消的,所以请务必谨慎小心,一旦失误 ...

  7. python测试开发django-38.多对多(ManyToManyField)查询

    前言 一个学生可以对应多个老师,一个老师也可以教多个学生,这就是一种多对多的关系 models建表 新建一个老师表Teacher,和一个学生表Student class Teacher(models. ...

  8. 明星伙伴第一至八季/全集Entourage迅雷下载

    英文译名Entourage,第1-8季(04-2011)HBO.本季看点:<明星伙伴>这是一部HBO原创系列喜剧,讲述年少成名的男主人公文森 .蔡斯和他的三个少年时纽约皇后区的朋友一道冒险 ...

  9. LockSupport的park和unpark的基本使用,以及对线程中断的响应性

    LockSupport是JDK中比较底层的类,用来创建锁和其他同步工具类的基本线程阻塞原语.java锁和同步器框架的核心AQS:AbstractQueuedSynchronizer,就是通过调用Loc ...

  10. sys.usb.config webcam

    setprop persist.sys.usb.config webcamecho 0 > /sys/devices/virtual/android_usb/android0/enableech ...