Android下载,在通知栏更新进度

Notification长使用的使用的属性

常量:
DEFAULT_ALL 使用所有默认值,比如声音,震动,闪屏等等
DEFAULT_LIGHTS 使用默认闪光提示
DEFAULT_SOUNDS 使用默认提示声音
DEFAULT_VIBRATE 使用默认手机震动
【说明】:加入手机震动,一定要在manifest.xml中加入权限:

<uses-permission android:name="android.permission.VIBRATE" />

以上的效果常量可以叠加,即通过
notification.defaults =DEFAULT_SOUND|DEFAULT_VIBRATE;
notification.defaults |= DEFAULT_SOUND (最好在真机上测试,震动效果模拟器上没有)

设置flag位
FLAG_AUTO_CANCEL 该通知能被状态栏的清除按钮给清除掉
FLAG_NO_CLEAR 该通知能被状态栏的清除按钮给清除掉
FLAG_ONGOING_EVENT 通知放置在正在运行
FLAG_INSISTENT 是否一直进行,比如音乐一直播放,知道用户响应

常用字段:
contentIntent 设置PendingIntent对象,点击时发送该Intent
defaults 添加默认效果
flags 设置flag位,例如FLAG_NO_CLEAR等
icon 设置图标
sound 设置声音
tickerText 显示在状态栏中的文字
when 发送此通知的时间戳
ledARGB闪光颜色
ledOnMS闪光时间,毫秒

NotificationManager常用方法介绍:
public void cancelAll() 移除所有通知(只是针对当前Context下的Notification)
public void cancel(int id) 移除标记为id的通知 (只是针对当前Context下的所有Notification)
public void notify(String tag ,int id, Notification notification) 将通知加入状态栏,标签为tag,标记为id
public void notify(int id, Notification notification) 将通知加入状态栏,标记为id

下载的代码

主要的类就两个,一个是文件工具类,一个是继承Service的下载类

文件工具类

public class FileUtil {

    /**
     * 返回应用程序的缓存目录.缓存目录被创建在SD卡
     * <i>("/Android/data/[app_package_name]/cache")</i> (如果安装了SD卡并且有权限).
     *
     * @param context Application context
     * @return Cache {@link File 目录}.<br />
     * <b>NOTE:</b> 在一些不可预知的情况下可以为空 (如果SD卡未安装并且
     * {@link Context#getCacheDir() Context.getCacheDir()} returns null).
     */
    public static File getCacheDirectory(Context context) {
        return getCacheDirectory(context, true);
    }
    /**
     * 返回应用程序的缓存目录.缓存目录被创建在SD卡
     * <i>("/Android/data/[app_package_name]/cache")</i> (如果安装了SD卡并且有权限).
     *
     * @param context        Application context
     * @param preferExternal 目录是否创建在SD卡
     * @return Cache {@link File 目录}.<br />
     * <b>NOTE:</b> 在一些不可预知的情况下可以为空 (如果SD卡未安装并且
     * {@link Context#getCacheDir() Context.getCacheDir()} returns null).
     */
    public static File getCacheDirectory(Context context, boolean preferExternal) {
        File appCacheDir = null;
        String externalStorageState;
        try {
            externalStorageState = Environment.getExternalStorageState();
        } catch (NullPointerException e) {
            externalStorageState = "";
        } catch (IncompatibleClassChangeError e) {
            externalStorageState = "";
        }
        if (preferExternal && MEDIA_MOUNTED.equals(externalStorageState)) {
            appCacheDir = getExternalCacheDir(context);
        }
        if (appCacheDir == null) {
            appCacheDir = context.getCacheDir();
        }
        if (appCacheDir == null) {
            String cacheDirPath = "/data/data/" + context.getPackageName() + "/cache/";
            L.w("Can't define system cache directory! '%s' will be used.", cacheDirPath);
            appCacheDir = new File(cacheDirPath);
        }
        return appCacheDir;
    }

    private static File getExternalCacheDir(Context context) {
        File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data");
        File appCacheDir = new File(new File(dataDir, context.getPackageName()), "cache");
        if (!appCacheDir.exists()) {
            if (!appCacheDir.mkdirs()) {
                L.w("Unable to create external cache directory");
                return null;
            }
        }
        return appCacheDir;
    }
}

继承Service的下载类

public class UpdateService extends Service {
    public static final String KEY_DOWN_URL = "Key_Down_Url";

    private static final int DOWN_STEP_CUSTOM = 3;
    private static final int TIMEOUT = 10 * 1000;// 超时
    private static final int DOWN_OK = 1;
    private static final int DOWN_ERROR = 0;

    private static String down_url;
    private String app_name;

    private NotificationManager notificationManager;
    private Notification progressNotification;
    private RemoteViews contentView;
    private File apkFile;

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        app_name = getResources().getString(R.string.app_name);
        down_url = intent.getStringExtra(KEY_DOWN_URL);

        // create file,应该在这个地方加一个返回值的判断SD卡是否准备好,文件是否创建成功,等等!
        File directory = FileUtil.getCacheDirectory(getBaseContext());
        if (directory != null) {
            apkFile = new File(directory, app_name + ".apk");
            createNotification();
            startDownLoadThread();
        }else {
            To.makeText(getApplicationContext(), getResources().getString(R.string.insert_card));
            //停止服务
            stopSelf();
        }

        return super.onStartCommand(intent, flags, startId);
    }



    /** update UI */
    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWN_OK:

                    /*********下载完成,点击安装***********/
                    Notification.Builder builder = new Notification.Builder(UpdateService.this);
                    builder.setContentTitle(app_name);
                    builder.setContentText(getString(R.string.down_sucess));
                    builder.setAutoCancel(true);
                    builder.setSmallIcon(R.mipmap.ic_launcher);
                    PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), R.layout.notification_item, getInstallIntent(apkFile), PendingIntent.FLAG_ONE_SHOT);
                    builder.setContentIntent(pendingIntent);
                    Notification notification = builder.getNotification();
                    notification.flags = Notification.FLAG_AUTO_CANCEL;
                    notificationManager.notify(R.layout.notification_item, notification);

                    /*****安装APK******/
                    installApk(apkFile);

                    /***stop service*****/
                    stopSelf();
                    break;

                case DOWN_ERROR:
                    Notification.Builder builderFaild = new Notification.Builder(UpdateService.this);
                    builderFaild.setContentTitle(app_name);
                    builderFaild.setContentText(getString(R.string.down_fail));
                    builderFaild.setSmallIcon(R.mipmap.ic_launcher);
                    Notification errorNotification = builderFaild.getNotification();
                    errorNotification.flags = Notification.FLAG_AUTO_CANCEL;
                    notificationManager.notify(R.layout.notification_item, errorNotification);
                    /***stop service*****/
                    stopSelf();
                    break;

                default:
                    stopSelf();
                    break;
            }
        }
    };

    private void installApk(File file) {
        UpdateService.this.startActivity(getInstallIntent(file));
    }
    /** 下载完成,点击安装 */
    private Intent getInstallIntent(File file){
        Uri uri = Uri.fromFile(file);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        return intent;
    }

    /**
     * 方法描述:开线程下载
     */
    public void startDownLoadThread() {
        new DownLoadThread().start();
    }


    private class DownLoadThread extends Thread{
        @Override
        public void run() {
            Message message = new Message();
            try {
                boolean download = downloadUpdateFile(down_url, apkFile.toString());
                if (download) {
                    message.what = DOWN_OK;
                    handler.sendMessage(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
                message.what = DOWN_ERROR;
                handler.sendMessage(message);
            }
        }
    }

    /**
     * 方法描述:createNotification方法
     */
    public void createNotification() {
        Notification.Builder builder = new Notification.Builder(getBaseContext());
        builder.setSmallIcon(R.mipmap.ic_launcher);
        progressNotification = builder.getNotification();
        progressNotification.flags = Notification.FLAG_ONGOING_EVENT;
        /*** 自定义  Notification 的显示****/
        contentView = new RemoteViews(getPackageName(),R.layout.notification_item);
        contentView.setTextViewText(R.id.notificationTitle, app_name + getString(R.string.is_downing));
        contentView.setTextViewText(R.id.notificationPercent, "0%");
        contentView.setProgressBar(R.id.notificationProgress, 100, 0, false);
        progressNotification.contentView = contentView;

        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(R.layout.notification_item, progressNotification);
    }

    /***
     * 下载文件
     * @throws Exception
     */
    public boolean downloadUpdateFile(String down_url, String file) throws Exception{

        int totalSize;// 文件总大小
        InputStream inputStream = null;
        OutputStream outputStream = null;

        HttpURLConnection httpURLConnection = createConnection(down_url);
        // 获取下载文件的size
        totalSize = httpURLConnection.getContentLength();

        if (httpURLConnection.getResponseCode() == 404) {
            throw new Exception("fail!");
        }

        try {
            inputStream = httpURLConnection.getInputStream();
        } catch (IOException e) {
            IoUtils.closeSilently(inputStream);
            throw e;
        }
        try {
            outputStream = new FileOutputStream(file, false);// 文件存在则覆盖掉
        } catch (FileNotFoundException e) {
            IoUtils.closeSilently(outputStream);
            throw e;
        }

        try {
            outputDownLoadFile(inputStream, outputStream, totalSize);
        }finally {
            httpURLConnection.disconnect();
            IoUtils.closeSilently(inputStream);
            IoUtils.closeSilently(outputStream);
        }

        return true;
    }

    /**
     * 根据url创建一个请求
     * @param down_url url
     * @throws IOException
     */
    private HttpURLConnection createConnection(String down_url) throws IOException {
        URL url = new URL(down_url);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setConnectTimeout(TIMEOUT);
        httpURLConnection.setReadTimeout(TIMEOUT);
        return httpURLConnection;
    }

    /**
     * 输入文件,并更新notification的进度条
     * @param totalSize 文件的总大小
     * @throws IOException
     */
    private void outputDownLoadFile(InputStream inputStream, OutputStream outputStream, int totalSize) throws IOException{
        int downloadCount = 0;// 已经下载好的大小
        int updateCount = 0;// 已经上传的文件大小

        byte buffer[] = new byte[1024];
        int readSize;

        while ((readSize = inputStream.read(buffer)) != -1) {

            outputStream.write(buffer, 0, readSize);
            downloadCount += readSize;// 时时获取下载到的大小
            /*** 每次增张3%**/
            if (updateCount == 0 || (downloadCount * 100 / totalSize - DOWN_STEP_CUSTOM) >= updateCount) {
                updateCount += DOWN_STEP_CUSTOM;
                // 改变通知栏
                contentView.setTextViewText(R.id.notificationPercent, updateCount + "%");
                contentView.setProgressBar(R.id.notificationProgress, 100, updateCount, false);
                progressNotification.contentView = contentView;
                notificationManager.notify(R.layout.notification_item, progressNotification);
            }
        }
    }
}

使用的代码

String url = "文件的网络地址";
Intent intent = new Intent(this,UpdateService.class);
intent.putExtra(UpdateService.KEY_DOWN_URL, url);
startService(intent);

就这些了,基本没什么
http://download.csdn.net/detail/wu_liao_de_ren_sheng/9471198

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值