Android 检查更新版本(带有通知栏,进度条,Notification)

最近听说友盟的自动更新后期会不让用了,所以自己谢了一个带有进度条通知栏的检查更新,请大家多提意见,话不多说,上代码。
首先,要去后台获取检查的接口判断是否要更新,如果需要更新,如下

                        String ver;//该参数为最新的版本号
                        String url;//最新apk的文件地址
                        String notes;//要显示的更新日志

                        UpdateManager manager = new UpdateManager(ver, url, notes, EasyHomeworkActivity.this);
                        // 检查软件更新
                        manager.checkUpdate();

第二步,弹出检查更新对话框选择更新并在通知栏显示进度
UpdateManager类基本就是封装好的一个完善的更新类

package com.easyhomework.more.data;

import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.easyhomework.R;
import com.easyhomework.context.EasyHomeworkActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 作者:lff
 * 时间;2016-4-11 14:38
 * 描述:检查更新
 */
public class UpdateManager {

    /* 下载中 */
    private static final int DOWNLOAD = 1;
    /* 下载结束 */
    private static final int DOWNLOAD_FINISH = 2;
    //判断是否更新中
    public static String tag = "1";//未点击更新

    /* 下载保存路径 */
    private String mSavePath;
    /* 记录进度条数量 */
    private int progress;
    /* 是否取消更新 */
    private boolean cancelUpdate = false;

    private String ver;//版本号
    private String urlapk;//apk地址
    private String notes;//升级说明
    private Context mContext;
    private int len;
    private NotificationManager manager;
    private Notification notif;
    /* 更新进度条 */
    private ProgressBar mProgress;
    private Dialog mDownloadDialog;
//    RemoteViews contentView;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 正在下载
                case DOWNLOAD:
                    // 设置进度条位置
                    mProgress.setProgress(progress);
progress, false);
                    notif.contentView.setTextViewText(R.id.content_view_text1, "正在下载...  "+progress+"%");
                    notif.contentView.setProgressBar(R.id.content_view_progress, 100, progress, false);
                    manager.notify(0, notif);
                    break;
                case DOWNLOAD_FINISH:
                    // 安装文件
                    notif.contentView.setTextViewText(R.id.content_view_text1, "下载完成!");
                    notif.contentView.setProgressBar(R.id.content_view_progress, 100, 100, false);
                    manager.notify(0, notif);
                    tag = "2";//更新完成开始安装
                    installApk();
                    break;
                default:
                    break;
            }
        }

        ;
    };

    public UpdateManager(String ver, String url, String notes, Context context) {
        this.mContext = context;
        this.ver = ver;
        this.urlapk = url;
        this.notes = notes;
    }

    public boolean isShowToast = true;

    /**
     * 检测软件更新
     */
    public void checkUpdate() {
        if (isUpdate()) {
            // 显示提示对话框
            if(tag.equals("1")){
                showNoticeDialog();
            }else{

            }

        } else {
            if(isShowToast){
                Toast.makeText(mContext, R.string.soft_update_no, Toast.LENGTH_LONG).show();
            }
        }
    }

    /**
     * 检查软件是否有更新版本
     *
     * @return
     */
    private boolean isUpdate() {
        // 获取当前软件版本
        int versionCode = getVersionCode(mContext);

        int serviceCode = Integer.valueOf(ver);
        // 版本判断
        if (serviceCode > versionCode) {
            return true;
        }

        return false;
    }

    /**
     * 获取软件版本号
     *
     * @param context
     * @return
     */
    private int getVersionCode(Context context) {
        int versionCode = 0;
        try {
            // 获取软件版本号,对应AndroidManifest.xml下android:versionCode
            versionCode = context.getPackageManager().getPackageInfo("com.easyhomework", 0).versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 显示软件更新对话框
     */
    private void showNoticeDialog() {
        // 构造对话框
        Builder builder = new Builder(mContext);
        builder.setTitle(R.string.soft_update_title);
        builder.setMessage(notes);
        // 更新
        builder.setPositiveButton(R.string.soft_update_updatebtn, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();


//                if (tag) {
                    Toast.makeText(mContext, "后台更新中,请稍后...", Toast.LENGTH_LONG).show();
                tag="3";//开始更新
//                } else {
//                    // 显示下载对话框
                    showDownloadDialog();
//                    Toast.makeText(mContext, "后台下载更新中...", Toast.LENGTH_LONG).show();
//                }

            }
        });
        // 稍后更新
        builder.setNegativeButton(R.string.soft_update_later, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        Dialog noticeDialog = builder.create();
        noticeDialog.show();
    }

    /**
     * 显示软件下载对话框
     */
    private void showDownloadDialog() {

        // 构造软件下载对话框
        Builder builder = new Builder(mContext);
        builder.setTitle(R.string.soft_updating);
        // 给下载对话框增加进度条
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.softupdate_progress, null);
        mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
        builder.setView(v);
        // 取消更新
        builder.setNegativeButton(R.string.soft_update_cancel, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                // 设置取消状态
                cancelUpdate = true;
            }
        });
        mDownloadDialog = builder.create();
//        mDownloadDialog.show();   //不让下载进度条显示

            //点击通知栏后打开的activity
            Intent intent = new Intent(mContext,EasyHomeworkActivity.class);
            PendingIntent pIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
            manager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
            notif = new Notification();
            notif.icon = R.drawable.app_icon;
            notif.tickerText = "更新通知";
            //通知栏显示所用到的布局文件
            notif.contentView = new RemoteViews(mContext.getPackageName(), R.layout.p);
            notif.contentIntent = pIntent;
            manager.notify(0, notif);
        // 下载文件
        downloadApk();
    }

    /**
     * 下载apk文件
     */
    private void downloadApk() {
        // 启动新线程下载软件

        new downloadApkThread().start();
    }
    int downloadCount = 0;
    /**
     * 下载文件线程
     *
     * @author coolszy
     * @date 2012-4-26
     * @blog http://blog.92coding.com
     */
    private class downloadApkThread extends Thread {
        @Override
        public void run() {
            try {

                // 判断SD卡是否存在,并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    // 获得存储卡的路径
                    String sdpath = Environment.getExternalStorageDirectory() + "/";
                    mSavePath = sdpath + "download";
                    URL url = new URL(urlapk);
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    // 获取文件大小
                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();

                    File file = new File(mSavePath);
                    // 判断文件目录是否存在
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    File apkFile = new File(mSavePath, "easy.apk");
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中


                    do {
                        int numread = is.read(buf);
                        count += numread;

                        // 计算进度条位置
                        progress = (int) (((float) count / length) * 100);
                        Log.i("progress","progress==="+progress);
                        Log.i("progress","count==="+count+numread);
                        // 更新进度
                        //为了防止频繁的通知导致应用吃紧,百分比增加10才通知一次
                        if(downloadCount == 0 || progress-5>downloadCount){
                            downloadCount+=5;
                            mHandler.sendEmptyMessage(DOWNLOAD);
                        }
                        if (numread <= 0) {
                            // 下载完成
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numread);
                    } while (!cancelUpdate);// 点击取消就停止下载.
                    fos.close();
                    is.close();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    ;

    /**
     * 安装APK文件
     */
    private void installApk() {

        File apkfile = new File(mSavePath, "easy.apk");
        if (!apkfile.exists()) {
            return;
        }
        // 通过Intent安装APK文件
;
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
        mContext.startActivity(intent);

    }
}

还有一个是通知栏的布局

通知栏布局 p

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout

xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#00000000"
    android:orientation="vertical"
    android:padding="7dp"

>
    <ImageView
        android:id="@+id/content_view_image"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:src="@drawable/app_icon"

        />
    <TextView
        android:id="@+id/content_view_text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0%"
        android:textColor="#969191"
        android:layout_toRightOf="@id/content_view_image"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="5dp"
        android:layout_marginLeft="15dp"
        />
    <ProgressBar
        android:id="@+id/content_view_progress"
        android:layout_width="fill_parent"
        android:layout_height="6dp"
        style="@android:style/Widget.ProgressBar.Horizontal"
        android:max="100"
        android:layout_below="@id/content_view_image"
        android:layout_marginTop="7dp"
        android:progressDrawable="@drawable/progressbar_color"
        />

</RelativeLayout>

大家仔细看UpdateManager 注释,很简单的,最近比较忙,这个博客有点粗糙,有什么问题可以加我QQ群大家一起探讨一下。

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: Android通知是一种用于显示应用程序通知的用户界面元素。它可以在屏幕的顶部或底部显示,并且可以包含文本、图像、声音和其他交互元素。通知可以帮助用户及时了解应用程序的状态和事件,例如新消息、更新、提醒和警告等。开发人员可以使用Android SDK提供的通知API来创建和管理通知,以便好地与用户进行交互。 ### 回答2: Android 通知是一种提供给用户显示有关当前状态和行动的信息的方式,以便用户可以及时地采取必要的行动。通知可以显示来自应用程序和系统的通知消息,例如电子邮件、信息和其他事件,可以让用户在不离开当前应用的情况下对这些消息进行响应。 在通知中,每个通知都包含一个图标、标题、简短的消息文本和通知时间。用户可以从通知中直接打开应用程序或查看通知的详细信息。通知还可以显示多个通知,按照时间顺序进行排序。 开发人员可以使用 Android SDK 提供的 Notification 类来创建自定义通知。可以设置通知的图标、文本、声音、震动和延迟时间等属性。还可以指定通知的优先级,以便系统在有限的屏幕空间中为用户先显示最重要的通知通知还可以与 PendingIntent 实例相关联,以便在用户单击通知时执行特定的操作,例如打开应用程序,启动活动或显示通知详细信息的专用活动。 总之,Android 通知是一种非常有用的功能,可以让用户及时了解应用程序和系统中的重要事件,并采取及时的行动。开发人员可以使用通知来实现好的用户体验。 ### 回答3: Android 通知是一种非常有用的功能,它可以让你的应用程序以一种全新的方式与用户进行交互。在 Android 应用程序中,通知是一种特殊的 UI 元素,它显示在屏幕的顶部,并显示当前状态、事件或提示。通知通常包含一组小图标,可以展开或折叠以显示多详细信息。 Android 通知有许多不同的用途,例如提醒用户新的消息、电子邮件、电话、提醒等等。发送通知的应用程序无需与用户保持连接,这使得通知非常适合后台服务或其他形式的低功耗通信。通知还允许用户直接从通知菜单中操作应用程序。例如,当用户收到新的电子邮件时,他们可以在通知中选择该电子邮件并立即查看其内容,而无需打开电子邮件应用程序。 Android 通知的另一个优点是它的可定制性。可以轻松地修改通知的外观、行为和内容,以满足不同应用程序的需求和设计要求。您可以为通知添加各种元素,如纯文本、小图标、大图标、进度指示器、按钮等等。这样,您可以轻松地创造与您的品牌和应用程序设计语言保持一致的通知。 在实现通知之前,您需要确保该应用程序已获得了通知权限。如果您的应用程序需要通知用户任何内容,则必须获得 Android 手机上的通知权限。可以在应用程序设置中找到此选项。 虽然 Android 通知很有用,但在某些情况下,它们可能会变得令人分心。因此,应该仔细考虑应用程序通知的数量和类型,以确保用户不会感到困扰。通知还可以消耗设备电池,因此也应考虑优化应用程序以最小化资源消耗。 Android 通知作为 Android 应用程序非常重要的一部分,可以帮助您在应用程序和用户之间建立紧密的联系,并提供有关应用程序状态、事件和提示的有用信息。通过努力优化您的应用程序通知,您可以确保用户感到受到了关注,并且同时不会让他们感到困扰。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值