安卓在线下载并升级安装apk程序
以下为例程代码:
MainActivity:
package com.example.autoupdate;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* 远程下载安装Android程序
*/
public class MainActivity extends AppCompatActivity {
TextView mTextView;
EditText mEditText;
private Button mButton;
private String currentFilePath = "";
private String currentTempFilePath = "";
private String strURL = "";
private String fileEx = "";
private String fileName = "";
static String strAPKName = "";//保存每个zip的apk名称
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.installonline_text1);
mEditText = (EditText) findViewById(R.id.installonline_edittext1);
mEditText.setText("http://www.wqlcd.net:8000/bbs/forum.php?mod=attachment&aid=MzM5fDhlODlmZWZmfDE2NDYyODY1OTJ8NXwxMTk%3D");
mButton = (Button) findViewById(R.id.installonline_button1);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 将文件下载到本地
mTextView.setText("下载中...");
strURL = mEditText.getText().toString();
// 截取文件后缀
fileEx = strURL.substring(strURL.lastIndexOf('.') + 1,
strURL.length()).toLowerCase();
// 截取文件名
fileName = strURL.substring(strURL.lastIndexOf('/') + 1,
strURL.lastIndexOf('.'));
getFile(strURL);
}
});
}
private void getFile(final String strPath) {
if (currentFilePath.equals(strPath)) {
getDataSource(strPath);
}
currentFilePath = strPath;
Runnable r = new Runnable() {
@Override
public void run() {
getDataSource(strPath);
}
};
new Thread(r).start();
}
private void getDataSource(String url) {
if (!URLUtil.isNetworkUrl(url)) {
mTextView.setText("请填写正确的URL");
} else {
try {
//网络不能在主线程
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
URL myUrl = new URL(url);
// 取得连接
URLConnection conn = myUrl.openConnection();
// 连接
conn.connect();
// 获得输入流
InputStream is = conn.getInputStream();
if (is == null) {
throw new RuntimeException("stream is null");
}
// 创建临时文件
File myTempFile = File.createTempFile(fileName, "." + fileEx);
// 取得临时文件存放路径
currentTempFilePath = myTempFile.getAbsolutePath();
FileOutputStream fos = new FileOutputStream(myTempFile);
byte[] buf = new byte;
do {
// 返回现在所读缓冲区的大小
int numread = is.read(buf);
if (numread <= 0) {
break;
}
fos.write(buf, 0, numread);
} while (true);
//解压
Unzip( currentTempFilePath, "/mnt/sdcard/Download/");
File path1=new File("/mnt/sdcard/Download/" +strAPKName);
// 打开文件进行安装
openFile(path1);
//openFile(myTempFile);
is.close();
//delFile("/mnt/sdcard/Download/" +strAPKName);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void openFile(File file) {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
String type = getMimeType(file);
intent.setDataAndType(Uri.fromFile(file), type);
startActivity(intent);
}
private String getMimeType(File file) {
String type = "";
String fname = file.getName();
// 获得扩展名
String end = fname
.substring(fname.lastIndexOf('.') + 1, fname.length())
.toLowerCase();
// 按扩展名的类型决定MimeType
if ("m4a".equals(end) || "mp3".equals(end) || "mid".equals(end)
|| "xmf".equals(end) || "ogg".equals(end) || "wav".equals(end)) {
type = "audio";
} else if ("3gp".equals(end) || "mp4".equals(end)) {
type = "video";
} else if ("jpg".equals(end) || "gif".equals(end) || "png".equals(end)
|| "jpeg".equals(end) || "bmp".equals(end)) {
type = "image";
} else if ("apk".equals(end)) {
type = "application/vnd.android.package-archive";
} else if ("rar".equals(end) || "zip".equals(end)) {
type = "zip";
} else {
type = "*";
}
if ("apk".equals(end)) {
} else {
type += "/*";
}
return type;
}
private void delFile(String fileName){
File file = new File(fileName);
if(file.exists()){
file.delete();
}
}
@Override
protected void onPause() {
mTextView = (TextView) findViewById(R.id.installonline_text1);
mTextView.setText("下载成功");
super.onPause();
}
private static void Unzip(String zipFile, String targetDir) {
int BUFFER = 4096; //这里缓冲区我们使用4KB,
String strEntry; //保存每个zip的条目名称
try {
BufferedOutputStream dest = null; //缓冲输出流
FileInputStream fis = new FileInputStream(zipFile);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry; //每个zip条目的实例
while ((entry = zis.getNextEntry()) != null) {
try {
Log.i("Unzip: ","="+ entry);
int count;
byte data[] = new byte;
strEntry = entry.getName();
strAPKName = entry.getName();
File entryFile = new File(targetDir + strEntry);
File entryDir = new File(entryFile.getParent());
if (!entryDir.exists()) {
entryDir.mkdirs();
}
FileOutputStream fos = new FileOutputStream(entryFile);
dest = new BufferedOutputStream(fos, BUFFER);
while ((count = zis.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
zis.close();
} catch (Exception cwj) {
cwj.printStackTrace();
}
}
}activity_main.xml:界面文件请自行补全即可
AndroidManifest.xml:添加系统签名 android:sharedUserId="android.uid.system"
页:
[1]