ni看我屌不
2016-01-06 09:58
采纳率: 92.9%
浏览 1.6k

Android软件更新的问题

正在做一款软件,要求是检测到有更新之后自动下载并且安装,不弹出安装界面,网上找了好多都不能实现。求解
PS:不是流氓软件,类似于银行叫号机的软件

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • keyborad_boy 2016-01-07 02:57
    已采纳

    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;

    import org.json.JSONObject;

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.content.SharedPreferences;
    import android.content.SharedPreferences.Editor;
    import android.content.pm.PackageInfo;
    import android.content.pm.PackageManager;
    import android.content.pm.PackageManager.NameNotFoundException;
    import android.graphics.AvoidXfermode.Mode;
    import android.net.Uri;
    import android.os.Environment;
    import android.os.Handler;
    import android.os.Message;
    import android.util.Log;
    import android.widget.ProgressBar;
    import android.widget.TextView;
    import android.widget.Toast;

    import com.golfor.api.RequstClient;
    import com.golfor.api.UIHelper;
    import com.golfor.app.AppContext;
    import com.golfor.constants.Iconstants;
    import com.golfor.http.AsyncHttpResponseHandler;
    import com.golfor.ui.common.DownloadDialog;
    import com.golfor.ui.common.DownloadDialog.MyCancelClickListener;
    import com.golfor.ui.common.UpdateConfirmDialog;
    import com.golfor.ui.common.UpdateConfirmDialog.DialogClickListener;

    /**

    public class UpdateManager {
    /* 下载中 /
    private static final int DOWNLOAD = 1;
    /
    下载结束 /
    private static final int DOWNLOAD_FINISH = 2;
    /
    下载保存路径 /
    private String mSavePath;
    private String mAppName;
    private String versionName;
    /
    记录进度条数量 /
    private int progress;
    /
    是否取消更新 /
    private boolean cancelUpdate = false;
    private Context mContext;
    /
    更新进度条 /
    private ProgressBar mProgress;
    private TextView tv_pro;
    /
    *用来保存版本号*/
    private SharedPreferences mSaveVersionCode,mSaveName;
    private Editor mEt,mSn;

    private DownloadDialog downloadProgress;
    private final String tag = "_TEST";
    private DownloadDialog mDialog;
    //上一个版本名
    String beforName = "1.0";
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            // 正在下载
            case DOWNLOAD:
                String pro = msg.obj.toString();
                tv_pro.setText("正在下载(" + pro + ")");
                // 设置进度条位置
                mProgress.setProgress(progress);
                break;
            case DOWNLOAD_FINISH:
                // 安装文件
                installApk();
                break;
            default:
                break;
            }
        };
    };
    
    private String downUrl;
    

    // public UpdateManager(Context context, String appName, String downUrl) {
    // this.mContext = context;
    // mAppName = appName;
    // this.downUrl = downUrl;
    // }
    public UpdateManager(Context context) {
    this.mContext = context;
    }
    /**
    * 从服务器上获取版本信息
    /
    public void getVersionDataFromWeb(final String str){
    RequstClient.getVersionCode(new AsyncHttpResponseHandler(){
    @Override
    public void onFailure(Throwable error, String content) {
    // TODO Auto-generated method stub
    super.onFailure(error, content);
    UIHelper.cloesLoadDialog();
    }
    @Override
    public void onSuccess(int statusCode, String content) {
    // TODO Auto-generated method stub
    super.onSuccess(statusCode, content);
    UIHelper.cloesLoadDialog();
    Log.e("TEST", " 从服务器上获取版本信息");
    try {
    JSONObject obj = new JSONObject(content);
    JSONObject data = obj.getJSONObject("data");
    String apkUrl = data.getString("apkPath");
    String serviceVersion = data.getString("apkVersion");
    String apkMessage = data.getString("apkMessage");
    String apkName = data.getString("apkName");
    versionName = data.getString("apkVersionName");
    AppContext.getInstance().setAppVersion(versionName);
    mAppName = apkName;
    Log.e(tag, apkUrl+">>>"+apkMessage+"//"+Integer.parseInt(serviceVersion)+"/"+apkName+"/"+versionName);
    downUrl = apkUrl;
    checkUpdate(versionName,apkMessage,str);
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    UIHelper.cloesLoadDialog();
    }
    }
    });
    }
    /
    *
    * 检测软件更新
    /
    public void checkUpdate(String versionName, String content,String flag) {
    if (isUpdate(versionName)) {
    // 显示提示对话框
    showNoticeDialog(content);
    } else{
    if(flag.equals(Iconstants.MINE_FRAGMENT)){
    UIHelper.showToasts("处于最新版本");
    }
    return ;
    }
    }
    /
    *
    * 检查软件是否有更新版本
    * @return
    /
    private boolean isUpdate(String versionName) {
    mSaveVersionCode = mContext.getSharedPreferences("version", mContext.MODE_PRIVATE);
    mSaveName = mContext.getSharedPreferences("beforename", mContext.MODE_PRIVATE);
    mEt = mSaveVersionCode.edit();
    mSn = mSaveName.edit();
    beforName = mSaveName.getString("beforename", "1.0");
    // 获取当前软件版本
    String currentVersionName = getVersionCode(mContext,beforName);
    Log.e(tag, "当前软件版本:"+currentVersionName+""+"下载的版本:"+versionName);
    if (versionName.equals(currentVersionName)) {
    // mEt.putInt("versionCode", serviceCode);
    return false;
    }else{
    return true;
    }
    }
    /
    *
    * 获取软件版本号
    *
    * @param context
    * @return
    */
    public String getVersionCode(Context context,String beforeName) {
    String version = mSaveVersionCode.getString("versionName",null);
    if(version == null){
    // String pkg = context.getPackageName();
    // 获取软件版本号,对应AndroidManifest.xml下android:versionCode
    PackageManager manager = context.getPackageManager();
    PackageInfo info;
    try {
    info = manager.getPackageInfo(context.getPackageName(), 0);
    version = info.versionName;
    Log.e(tag, "上一个版本版本:"+beforeName+""+"保存的版本:"+version);
    } catch (NameNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }else{
    //更新后的版本号
    version = mSaveVersionCode.getString("versionName", null);
    mSn.putString("name", version);
    mSn.commit();
    Log.e(tag, "更新后保存的版本:"+beforName);
    }
    return version;
    }

    /**
     * 显示软件更新对话框
     */
    public void showNoticeDialog(String content) {
        // 构造对话框
        UpdateConfirmDialog dialog = new UpdateConfirmDialog(mContext);
        dialog.setCustomTitle("发现新版本");
        dialog.setUpdateContent(content);
        dialog.setConfirm("立即下载");
        dialog.setCancel("稍后更新");
        dialog.setCanceledOnTouchOutside(false);
        dialog.setClickListener(new DialogClickListener() {
            @Override
            public void onConfirmClickListener() {
                mEt.putString("versionName", versionName);
                mEt.commit();
                // 显示下载对话框
                showDownloadDialog();
            }
    
            @Override
            public void onCancelClickListener() {
    
            }
        });
        dialog.show();
    }
    
    /**
     * 显示软件下载对话框
     */
    private void showDownloadDialog() {
        // 构造软件下载对话框
        mDialog = new DownloadDialog(mContext);
        mDialog.setTitle("下载更新");
        mProgress = mDialog.getProgressBar();
        tv_pro = mDialog.getMessage();
        //取消
    

    // dialog.setMyClickListener(new MyCancelClickListener() {
    // public void onCancelClickListener() {
    // cancelUpdate = true;
    // }
    // });
    mDialog.show();
    // 现在文件
    downloadApk();
    }

    /**
     * 下载apk文件
     */
    private void downloadApk() {
        // 启动新线程下载软件
        new downloadApkThread().start();
    }
    
    /**
     * 下载文件线程
     * 
     * @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(downUrl);
                    // 创建连接
                    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, mAppName);
                    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);
                        Message msg = new Message();
                        msg.obj = progress + "%";
                        msg.what = DOWNLOAD;
                        // 更新进度
                        mHandler.sendMessage(msg);
                        if (numread <= 0) {
                            // 下载完成
                            mDialog.cancel();
                            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();
            }
    
            // 取消下载对话框显示
            if (downloadProgress != null ) {
                downloadProgress.dismiss();
            }
        }
    };
    
    /**
     * 安装APK文件
     */
    private void installApk() {
        File apkfile = new File(mSavePath, mAppName);
        if (!apkfile.exists()) {
            return;
        }
        // 通过Intent安装APK文件
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
        mContext.startActivity(i);
    }
    /**
     * 
     */
    

    }

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • 另一花生 2016-01-06 10:07
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题