3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Android App でInstallerを呼び出すときのメモ

Last updated at Posted at 2019-08-02

久々にUpdateやInstallをするアプリを作成しようとしたところ、色々と権限周りで変わっていたので、そのメモ書き

#環境
compileSdkVersion 29
minSdkVersion 24
targetSdkVersion 29

#ソースコード
Intentでinstallerに飛ばしてあげる際のpermissionは下記を使う

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

DowloadしたapkをInstallするにはFileProvider経由でなくてはいけない
いろいろな記事ではまだSupportLibrary.v4を使っているものが多いが今回はandroidxを使用する

build.gradle
implementation 'androidx.core:core:{current version}'

FileProviderは下記の様に追加する

AndroidManifest.xml
<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true" >
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths"/>
</provider>

あとは色々な記事でも書かれているように、AndroidVersionごとにあったIntentで飛ばしてあげるだけ

MainActivity.java
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Uri fileUri = FileProvider.getUriForFile(MainActivity.this,
                        MainActivity.this.getApplicationContext().getPackageName() + ".fileprovider",
                        file);
                Intent i = new Intent(Intent.ACTION_INSTALL_PACKAGE);
                i.setData(fileUri);
                i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                MainActivity.this.startActivity(i);
            } else {
                Uri fileUri = Uri.fromFile(file);
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setDataAndType(fileUri, APK_MIME_TYPE);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                MainActivity.this.startActivity(i);
            }

環境によって変わってくることはあると思うが、これでいける
以上

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?