Launch APK Installer Oreo

守給你的承諾、 提交于 2019-12-05 12:18:35

Apparently if your app targets later versions of android the android.permission.REQUEST_INSTALL_PACKAGES permission is required in the manifest otherwise nothing happens except a single line error in the LogCat.

So include the following in manifest.xml file:

<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>

Manifest API for REQUEST_INSTALL_PACKAGES

Please add the <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/> permission in Manifest.xml first.

We should check the result of getPackageManager().canRequestPackageInstalls() if the SDK version is equal or large than 26.

The code is below:

private void checkIsAndroidO() {  
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {  
    boolean result = getPackageManager().canRequestPackageInstalls();  
    if (result) {  
      installApk();
    } else {  
      // request the permission 
      ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.REQUEST_INSTALL_PACKAGES}, INSTALL_PACKAGES_REQUESTCODE);  
    }  
  } else {
    installApk();  
  }  
}

@Override  
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {  
  super.onRequestPermissionsResult(requestCode, permissions, grantResults);

  switch (requestCode) {  
    case INSTALL_PACKAGES_REQUESTCODE:  
      if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {  
        installApk();  
      } else {  
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);  
        startActivityForResult(intent, GET_UNKNOWN_APP_SOURCES);  
      }  
    break;  
  }  
}

@Override  
protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  super.onActivityResult(requestCode, resultCode, data); 

  switch (requestCode) {  
    case GET_UNKNOWN_APP_SOURCES:  
      checkIsAndroidO();  
      break;  

    default:  
      break;  
  }  
}

I hope it will help you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!