Android 应用更新

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34942689/article/details/80282899
public class UpdateManager {
    private static final String TAG = "UpdateManager";
    private Context context;
    public static final int NOTIFICATION_ID = 10;
    private NotificationManager mNotifyManager;
    private NotificationCompat.Builder mBuilder;
    private Notification notification;
    private String apkLocalUrl;
    private String apkFileName = "XXX.apk";

    public UpdateManager(Context context) {
        this.context = context;
        if(Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)){
            apkLocalUrl = Environment.getExternalStorageDirectory().getAbsolutePath() + "/install/";
        }else {
            apkLocalUrl = Environment.getDataDirectory() + "/install/";
        }
    }

    /**
     * 开始更新
     * @param downloadURL
     */
    public void update(String downloadURL) {
        L.e("xxx","downloadURL:"+downloadURL);
        if (TextUtils.isEmpty(downloadURL)) {
            return;
        }
        File file = new File(apkLocalUrl,apkFileName);

        if(file.exists()){
            file.delete();
        }
     /**
     * 这里写网络请求已经处理结果
     */

    }
    /**
     * 初始化通知栏
     */
    private void initNotificatin() {
        mNotifyManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        mBuilder = new NotificationCompat.Builder(context);
        notification = mBuilder.setContentTitle(context.getString(R.string.downloading))
                .setTicker(context.getString(R.string.start_update))
                .setContentText("")
                .setSmallIcon(R.mipmap.ic_launcher)
                .build();
        notification.defaults = Notification.DEFAULT_SOUND;
        notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE;
        mNotifyManager.notify(NOTIFICATION_ID, notification);
    }

    /**
     * 安装APK
     */
    public void installAPK(File file) {
        if (file != null && file.exists()) {
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            App.mContext.startActivity(intent);
        } else {
            Toast.makeText(context, context.getString(R.string.install_fail), Toast.LENGTH_LONG).show();
        }}

猜你喜欢

转载自blog.csdn.net/qq_34942689/article/details/80282899