Android内安装apk文件遇到的坑

二种情况:7.0前后

1.把apk放到raw文件夹下,首先复制文件到内部存储中。

public void copyRawFile(Context context) {

try {

InputStream is = context.getResources().openRawResource(R.raw.home);

FileOutputStream fos = context.openFileOutput("home.apk",

context.MODE_PRIVATE);

//            FileOutputStream fos = new FileOutputStream(mFile,context.MODE_PRIVATE);

            byte[] mbyte =new byte[1024];

int len =0;

while((len = is.read(mbyte)) >0){

fos.write(mbyte,0, len);

}

is.close();

fos.flush();

fos.close();

}catch (Exception e) {

Log.d("TAG","copyRawFile: 异常了"+e.getMessage());

}

}

public void install() {

File file =new File(this.getFilesDir().getPath() + File.separator +"home.apk");

Boolean bol = isAppInstall(mContext,"air.PTClient.home");//是否已安装

    if (bol)return;

setUpdateDir(file);//相关权限

    Intent intent =new Intent(Intent.ACTION_VIEW);

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Log.d("TAG","正常进行安装" + file);

intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");

startActivity(intent);

}

private boolean isAppInstall(Context mContext, String packageName) {

PackageInfo mInfo;

try {

mInfo = mContext.getPackageManager().getPackageInfo(packageName,0);

}catch (Exception e) {

mInfo =null;

Log.i(TAG,"没有发现安装的包名");

}

if (mInfo ==null) {

return false;

}else {

return true;

}

}

/**

* @param updateDir 就是可以执行的文件

*  void  修改文件的权限,可读、可写、可执行

*/

private void setUpdateDir(File updateDir) {

try {

Process p = Runtime.getRuntime().exec("chmod 777 " + updateDir);

int status = p.waitFor();

}catch (IOException e) {

e.printStackTrace();

}catch (InterruptedException e) {

e.printStackTrace();

}

}

2. 这个需要自己实测,参考几篇博文。

http://www.czhzero.com/2016/12/21/how-to-install-apk-on-Android7-0/

https://www.cnblogs.com/newjeremy/p/7294519.html

https://blog.csdn.net/liu540885284/article/details/78834971

https://www.jianshu.com/p/ad751e66f575

https://blog.csdn.net/czhpxl007/article/details/53781464

你可能感兴趣的:(Android内安装apk文件遇到的坑)