Android App以编程方式安装(自动更新)中的问题

时间:2018-09-04 06:03:26

标签: java android apk android-install-apk

自动更新中的问题。如果有可用更新,则会下载新应用,然后卸载当前应用并安装新应用。直到目标SDK 22都可以正常工作,但是在目标SDK 24或更新API级别2以上的Phone os之后,此功能将无法正常工作。因为已经有旧的应用程序,因此我们正在尝试安装新的应用程序。

targetSDK:24

compileSDK:28

minSDK:19

这是一段代码:

public class UpdateActivity extends AppCompatActivity implements AppConstants {

    public static final String TAG = UpdateActivity.class.getSimpleName();
    private String appName = "XYZ.apk";
    private final Handler mHideHandler = new Handler();
    private View mContentView;
    private TextView txtDownloading;
    private NumberProgressBar numberProgressBar;
    private String updateUrl = "";

    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {
            // Delayed removal of status and navigation bar

            mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update);
        updateUrl = getIntent().getStringExtra("url");
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitAll().build());
        mContentView = findViewById(R.id.fullscreen_content);
        mHideHandler.post(mHidePart2Runnable);
        numberProgressBar = (NumberProgressBar) findViewById(R.id.numberbar8);
        txtDownloading = (TextView) findViewById(R.id.txtDownload);
        try {
            new DownloadFileFromURL().execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class DownloadFileFromURL extends AsyncTask<String, Integer, String> {

        DownloadFileFromURL() {
        }

        protected void onPreExecute() {
            super.onPreExecute();
            }

        protected String doInBackground(String... f_url) {
            try {
                HttpURLConnection c = (HttpURLConnection) new URL(updateUrl).openConnection();
                c.setRequestMethod("POST");
                c.setDoOutput(false);
                c.connect();
                int lengthOfFile = c.getContentLength();
                File file = new File(Environment.getExternalStorageDirectory().getPath() + "/Download/");
                file.mkdirs();
                File outputFile = new File(file, appName);
                if (outputFile.exists()) {
                    outputFile.delete();
                }
                FileOutputStream fos = new FileOutputStream(outputFile);
                InputStream is = c.getInputStream();
                byte[] data = new byte[AccessibilityNodeInfoCompat.ACTION_NEXT_HTML_ELEMENT];
                long total1 = 0;
                while (true) {
                    int count = is.read(data);
                    if (count == -1) {
                        break;
                    }
                    total1 += (long) count;
                    Integer[] strArr = new Integer[1];
                    strArr[0] = DOWNLOAD_COUNT + ((int) ((100 * total1) / ((long) lengthOfFile)));
                    publishProgress(strArr);
                    fos.write(data, 0, count);
                }
                fos.close();
                is.close();
                installApp();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }
            return null;
        }

        protected void onProgressUpdate(Integer... progress) {
            try {
                numberProgressBar.setUnreachedBarColor(Color.parseColor("#CCCCCC"));
                numberProgressBar.setProgressTextSize(30.0f);
                if (progress[0] > 0 && progress[0] <= 20) {
                    numberProgressBar.setProgressTextColor(Color.parseColor("#E74C3C"));
                    numberProgressBar.setReachedBarColor(Color.parseColor("#E74C3C"));
                    txtDownloading.setTextColor(Color.parseColor("#E74C3C"));
                }
                if (progress[0] > 20 && progress[0] <= 40) {
                    numberProgressBar.setProgressTextColor(Color.parseColor("#FF3D7F"));
                    numberProgressBar.setReachedBarColor(Color.parseColor("#FF3D7F"));
                    txtDownloading.setTextColor(Color.parseColor("#FF3D7F"));
                }
                if (progress[0] > 40 && progress[0] <= 60) {
                    numberProgressBar.setProgressTextColor(Color.parseColor("#FFC73B"));
                    numberProgressBar.setReachedBarColor(Color.parseColor("#FFC73B"));
                    txtDownloading.setTextColor(Color.parseColor("#FFC73B"));
                }
                if (progress[0] > 60 && progress[0] <= 80) {
                    numberProgressBar.setProgressTextColor(Color.parseColor("#6DBCDB"));
                    numberProgressBar.setReachedBarColor(Color.parseColor("#6DBCDB"));
                    txtDownloading.setTextColor(Color.parseColor("#6DBCDB"));
                }
                if (progress[0] > 80 && progress[0] <= 100) {
                    numberProgressBar.setProgressTextColor(Color.parseColor("#70A800"));
                    numberProgressBar.setReachedBarColor(Color.parseColor("#70A800"));
                    txtDownloading.setTextColor(Color.parseColor("#70A800"));
                }
                numberProgressBar.setProgress(progress[0]);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        protected void onPostExecute(String file_url) {
            numberProgressBar.setVisibility(View.GONE);

        }
    }

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

    private void installApp() {
        try {
            File apkFile = new File(Environment.getExternalStorageDirectory().getPath() + "/Download/", appName);
            Intent intent = new Intent("android.intent.action.VIEW");
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    }

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,并使用以下方法解决了该问题:

  • 从playstore应用程序禁用Google Play Protect可以解决问题,即它阻止了外部来源的安装,并且我摆脱了解析错误。

  • 在Android N及更高版本上,要授予对特定文件或文件夹的访问权限以使其可被其他应用程序访问,您不能使用File Uri,而必须使用FileProvider类中的Provider Uri ,否则我们将获得FileUriExposedExceptionandroid.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

有关如何设置FileProvider的更多信息,请参阅以下指南: https://developer.android.com/reference/android/support/v4/content/FileProvider

希望这会有所帮助。