布局
话不多说直接上代码 布局<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="@+id/dow"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:visibility="visible">
<ProgressBar
android:id="@+id/pbar"
style="@android:style/Widget.ProgressBar.Horizontal"
android:layout_width="400dp"
android:layout_height="10dp"
android:layout_centerInParent="true"
android:progressDrawable="@drawable/progressbar" />
<TextView
android:id="@+id/downthisnumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/pbar"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:text="已完成"
android:textSize="18dp" />
<TextView
android:id="@+id/pvalue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/pbar"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="正在下载新版本"
android:textColor="@color/blue"
android:textSize="20dp" />
</RelativeLayout>
</RelativeLayout>
Android java 控制类
import android.Manifest;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import print.ylsoft.displaywork.R;
import print.ylsoft.displaywork.home.login.MainActivity;
import print.ylsoft.displaywork.httputil.HttpInfo;
import print.ylsoft.displaywork.loadview.LoadView;
public class SelectBuild extends Activity {
private ProgressDialog progressDialog;
private int fileSize;
private int downLoadFileSize;
private ProgressBar progressBar;
private TextView mTextDown;
private File file;
private LoadView loadView;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1:
loadView.cancelProgressDialog();
progressBar.setMax(fileSize);
break;
case 2:
Toast.makeText(SelectBuild.this,"检查更新失败",Toast.LENGTH_SHORT).show();
break;
case 3:
loadView.cancelProgressDialog();
progressBar.setProgress(downLoadFileSize);
mTextDown.setText(downLoadFileSize * 100 / fileSize + "%");
break;
case 4:
loadView.cancelProgressDialog();
Intent intent = new Intent(SelectBuild.this,MainActivity.class);
startActivity(intent);
finish();
break;
case 33:
loadView.cancelProgressDialog();
openApk(SelectBuild.this);
break;
case 31:
loadView.cancelProgressDialog();
install();
break;
default:
break;
}
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_builde);
requestPermission(this);
progressBar = (ProgressBar) findViewById(R.id.pbar);
mTextDown = (TextView) findViewById(R.id.downthisnumber);
getBuilder();
loadView = new LoadView();
loadView.buildProgressDialog("检查更新中,请稍后",SelectBuild.this);
}
public void getBuilder() {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(这里是你自己服务器地址 + "/output.json");
//开启一个连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(40000);
connection.setReadTimeout(40000);
connection.setRequestMethod("GET");
if (connection.getResponseCode() == 200) {
InputStream is = connection.getInputStream();
InputStreamReader isReader = new InputStreamReader(is);
// String json = StreamUtil.streamToString(isReader);
BufferedReader bufferedReader = new BufferedReader(isReader);
String son = bufferedReader.readLine();
//String json = bufferedReader.readLine();
/*while((json = bufferedReader.readLine())!=null){
System.out.println(json);
}
isReader.close();
System.out.println("fdsfasdfa"+json);
JSONObject jsonObject = new JSONObject(json);*/
JSONArray jsonArray = new JSONArray(son);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String apkInfo = jsonObject.optString("apkInfo");
JSONObject jsonObjectVersionCode = new JSONObject(apkInfo);
String versionCode = jsonObjectVersionCode.optString("versionCode");
int newVersionCode = Integer.parseInt(versionCode);
int loaclVersionCode = getVerCode(SelectBuild.this);
if (newVersionCode > loaclVersionCode) {
Log.i("新版本", String.valueOf(newVersionCode));
Log.i("本机版本", String.valueOf(loaclVersionCode));
requestPermission(SelectBuild.this);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
intentFilter.addDataScheme("package");
// 注册一个广播
registerReceiver(broadcastReceiver, intentFilter);
downFile(这里是你自己服务器地址+ "app.apk");
} else {
//跳转到登录
Message message = new Message();
message.what = 4;
mHandler.sendMessage(message);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
public static int getVerCode(Context context) {
int verCode = -1;
try {
verCode = context.getPackageManager().getPackageInfo(
"print.ylsoft.displaywork", 0).versionCode;
} catch (Exception e) {
e.printStackTrace();
}
return verCode;
}
//设备API大于6.0时,主动申请权限
private void requestPermission(Activity context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
}
}
// 接收到安装完成apk的广播
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("接收到安装完成apk的广播");
Message message = mHandler.obtainMessage();
message.what = 33;
mHandler.sendMessage(message);
openApk(SelectBuild.this);
}
};
/**
* 打开已经安装好的apk
*/
private void openApk(Context context) {
Intent mainActivityIntent = new Intent(context, MainActivity.class); // 要启动的Activity
mainActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(mainActivityIntent);
}
/**
* 根据传过来url创建文件
*/
private File getFile(String url) {
File files = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(), getFilePath(url));
return files;
}
/**
* 截取出url后面的apk的文件名
*
* @param url
* @return
*/
private String getFilePath(String url) {
return url.substring(url.lastIndexOf("/"), url.length());
}
public void hideAct() {
if (progressDialog == null) {
progressDialog = new ProgressDialog(SelectBuild.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
}
progressDialog.setMessage("检查新版本中请稍候......");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
public void install() {
File fss = file;
Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {// android.os.FileUriExposedException
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri installURI = FileProvider.getUriForFile(SelectBuild.this, "print.ylsoft.displaywork", file);
intent.setDataAndType(installURI,
"application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
}
startActivity(intent);
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 后台在下面一个Apk 下载完成后返回下载好的文件
*
* @param httpUrl
* @return
*/
private File downFile(final String httpUrl) {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
FileOutputStream fileOutputStream = null;
InputStream inputStream;
if (connection.getResponseCode() == 200) {
inputStream = connection.getInputStream();
if (inputStream != null) {
try{
file = getFile(httpUrl);
fileSize = connection.getContentLength();
Message message = new Message();
message.what = 1;
mHandler.sendMessage(message);
fileOutputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length = 0;
while ((length = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, length);
downLoadFileSize += length;
Message ms = new Message();
ms.what = 3;
mHandler.sendMessage(ms);
}
fileOutputStream.close();
fileOutputStream.flush();
}catch (Exception e){
e.printStackTrace();
}
}
inputStream.close();
//Log.e("Mr.Kang", "run: "+"下载完成");
// 往handler发送一条消息 更改button的text属性
Message message = mHandler.obtainMessage();
message.what = 31;
mHandler.sendMessage(message);
}else {
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
return file;
}
@Override
public void onActivityReenter(int resultCode, Intent data) {
super.onActivityReenter(resultCode, data);
}
}
就这么简单,请注意不要忽略权限的使用(读写权限和网络权限)