您的位置:首页 > 其它

版本更新与文件下载

2017-12-28 10:53 162 查看
我们as版本号的位置

defaultConfig {
applicationId "com.example.xsj.updataapp"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "2.0.1" //版本号
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

用的是ok网络请求导入依赖
compile 'com.squareup.okhttp3:okhttp:3.9.1'
compile 'com.google.code.gson:gson:2.8.1'
需要的权限

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
获得版本号的类
package com.example.xsj.updataapp;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

/**
* Created by xsj on 2017/12/27.
*/

public class VersionUtils {

public static String getVersionName(Context context) {
String versionName = "";
//获得包的管理者
PackageManager packageManager = context.getPackageManager();
//获得包名
String packageName = context.getPackageName();
try {
PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);
//获得工程的版本号
versionName = packageInfo.versionName;
} catch (Exception e) {
e.printStackTrace();
}
return versionName;
}
}
网络请求类
package com.example.xsj.updataapp;

import android.os.Handler;
import android.os.Message;

import com.google.gson.Gson;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
* Created by xsj on 2017/12/27.
*/

public class HttpUtils {

private static volatile HttpUtils instance;
private final OkHttpClient client;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};

public static HttpUtils getInstance() {
if (null == instance) {
synchronized (HttpUtils.class) {
if (instance == null) {
instance = new HttpUtils();
}
}
}
return instance;
}

public HttpUtils() {
client = new OkHttpClient.Builder().build();
}

public void getData(String url, Map<String,String> map, Class clazz, final Pview pv){

StringBuffer buffer = new StringBuffer();
buffer.append(url);

//如果存在
if(buffer.indexOf("?")!=-1){
//如果?不在最后一位
if(buffer.indexOf("?")!=buffer.length()-1){
buffer.append("&");
}
}else {
buffer.append("?");
}

//meiyou
for (Map.Entry<String,String> en : map.entrySet()){
buffer.append(en.getKey())
.append("=")
.append(en.getValue())
.append("&");
}

buffer.deleteCharAt(buffer.lastIndexOf("&"));

Request request = new Request.Builder().get().url(buffer.toString()).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {

}

@Override
public void onResponse(Call call, Response response) throws IOException {
String string = response.body().string();
final UpdataBean updataBean = new Gson().fromJson(string, UpdataBean.class);
handler.post(new Runnable() {
@Override
public void run() {
pv.onSuccess(updataBean);
}
});
}
});
}

//下载
public void download(String url, final File file, final DownLoadListener listener){

// 查看父目录是否存在
File parentFile = file.getParentFile();
if(!parentFile.exists()){
parentFile.mkdir();
}

// 文件是否存在
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}

Request request = new Request.Builder()
.url(url)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
listener.failed(e);
}
4000

@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();

//获取文件长度
long totalLength = body.contentLength();
int sum = 0;

//下载文件(io)
InputStream inputStream = body.byteStream();
int read=0;
byte[] buffer= new byte[1024];
FileOutputStream fileOutputStream = new FileOutputStream(file);
while ((read =inputStream.read(buffer))!=-1){
//监听进度
sum+=read;
long progress = sum*100/totalLength;
listener.progress(progress);

//写文件下载文件
fileOutputStream.write(buffer,0,read);
}

//刷新 关流
fileOutputStream.flush();
fileOutputStream.close();
inputStream.close();

listener.success(file.getAbsolutePath());
}
});
}
}


下载的接口
package com.example.xsj.updataapp;

/**
* Created by xsj on 2017/12/27.
*/

//下载的接口
public interface DownLoadListener {
void success(String path);
void failed(Exception e);
void progress(long progress);
}
请求成功的接口
package com.example.xsj.updataapp;

/**
* Created by xsj on 2017/12/27.
*/

public interface Pview {
void onSuccess(Object o);
}
Activity 主代码
package com.example.xsj.updataapp;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

private String path = "/download/";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//获得本工程的版本号
String versionName = VersionUtils.getVersionName(MainActivity.this);

HashMap<String, String> map = new HashMap<>();
map.put("version",versionName);

//设置地址
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File absolutePath = Environment.getExternalStorageDirectory();
path=absolutePath+path;
}

HttpUtils.getInstance().getData("http://www.wuxirui.com/api/checkversion.php", map, UpdataBean.class, new Pview() {
@Override
public void onSuccess(Object o) {
if(o!=null){
UpdataBean updataBean = (UpdataBean) o;
final UpdataBean.ResultBean result = updataBean.getResult();

//是否需要立即更新
boolean isMust = result.isMust_update();

if(result.isHas_new_version()){
//有更新
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("更新提示");
builder.setMessage(isMust ? "需要立即更新" : "是否需要更新");
builder.setPositiveButton("更新", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {

//获得新版本的url地址
String url = result.getUrl();
// http://www.wuxirui.com/download/jinritoutiao.apk //如果包含“.”
if(url.contains(".")){
String typeName = url.substring(url.lastIndexOf(".") + 1);
if(url.contains("/")){
String substring = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("."));
path=path+substring+"."+typeName;
}
}

//下载文件
HttpUtils.getInstance().download(url, new File(path), new DownLoadListener() {
@Override
public void success(String path) {
Log.i("TAG", "success: " + path);
// 启动自动安装
installApk(new File(path));
}

@Override
public void failed(Exception e) {

}

@Override
public void progress(long progress) {
Log.e("TAG", "progress: " + progress);
}
});
}
});

if(!isMust){
builder.setNegativeButton("稍候", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {

}
});
}
builder.create().show();
}
}
}
});
}

/**
* 安装apk
* @param file
*/
private void installApk(File file) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory("android.intent.category.DEFAULT");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
startActivity(intent);
android.os.Process.killProcess(android.os.Process.myPid());
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: