1-首先将APK文件放到服务器上,存放位置:根目录下
2-EditTest中写入:http://39.105.59.30:80/fei.apk
3-服务器是ubuntu,这个app想要实现的功能是点击下载后,从服务器上下载指定的
APK并进行安装。
4-运行时出现解析安装包失败
代码如下:
public class MainActivity extends AppCompatActivity {
private EditText main_et_1;
private File apkFile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
main_et_1 = findViewById(R.id.main_et_1);
}
public void downloadAPK(View view) {
final ProgressDialog dialog = new ProgressDialog(this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.show();
apkFile = new File(getExternalFilesDir(null),"update.apk");
//启动分线程
new Thread(new Runnable() {
@Override
public void run() {
try {
//得到链接对象
String path = main_et_1.getText().toString();
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置
//connection.setRequestMethod("GET"); //默认为get
connection.setConnectTimeout(5000);
connection.setReadTimeout(10000);
//链接
connection.connect();
//请求并得到响应码
if((connection.getResponseCode())==200){
//设置Dialog的最大进度
dialog.setMax(connection.getContentLength());
//得到包含APK文件数据的InputStream
InputStream is = connection.getInputStream();
//创建指向apkFile的FileOutputStream
FileOutputStream fos = new FileOutputStream(apkFile);
//边读边写
byte[] buffer = new byte[1024];
int len = -1;
while((len=is.read(buffer))!=-1){
fos.write(buffer,0,len);
//显示下载进度
dialog.incrementProgressBy(len);
}
fos.close();
is.close();
}
//下载完成
connection.disconnect();
runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.dismiss();
installAPK();
}
});
} catch (Exception e) {
e.printStackTrace();
dialog.dismiss();
}
}
}).start();
}
/*
启动安装APK
*/
private void installAPK(){
Intent intent = new Intent("android.intent.action.INSTALL_PACKAGE");
intent.setDataAndType(Uri.fromFile(apkFile),"application/vnd.android.package-archive");
startActivity(intent);
}
}
浏览器能不能把包下下来。 手机上如果已安装apk,卸载掉再试
大佬,没有尝试过从浏览器下载,APP已经卸载重装了,还是显示解析程序安装包时出现问题,难道是我的代码有问题吗?