Android P实现静默安装的方法示例(官方Demo)

 更新时间:2020年02月27日 08:31:36   作者:WagonWagon  
这篇文章主要介绍了Android P实现静默安装,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

Android9.0无法通过以下两种方式实现静默安装:

1.runtime执行shell cmd
2.PackageInstall 反射机制

但是Google已经给我们推荐了相关的APIDemos,所以建议大家多看看源码~

在frameworks/base/core/java/android/content/pm/PackageInstaller.java有段关于该类的介绍:

  1. The ApiDemos project contains examples of using this API:
  2. <code>ApiDemos/src/com/example/android/apis/content/InstallApk*.java</code>.
/**
 * Offers the ability to install, upgrade, and remove applications on the
 * device. This includes support for apps packaged either as a single
 * "monolithic" APK, or apps packaged as multiple "split" APKs.
 * <p>
 * An app is delivered for installation through a
 * {@link PackageInstaller.Session}, which any app can create. Once the session
 * is created, the installer can stream one or more APKs into place until it
 * decides to either commit or destroy the session. Committing may require user
 * intervention to complete the installation.
 * <p>
 * Sessions can install brand new apps, upgrade existing apps, or add new splits
 * into an existing app.
 * <p>
 * Apps packaged as multiple split APKs always consist of a single "base" APK
 * (with a {@code null} split name) and zero or more "split" APKs (with unique
 * split names). Any subset of these APKs can be installed together, as long as
 * the following constraints are met:
 * <ul>
 * <li>All APKs must have the exact same package name, version code, and signing
 * certificates.
 * <li>All APKs must have unique split names.
 * <li>All installations must contain a single base APK.
 * </ul>
 * <p>
 * ###########此处告诉开发者如何调用API安装apk##############
 * The ApiDemos project contains examples of using this API:
 * <code>ApiDemos/src/com/example/android/apis/content/InstallApk*.java</code>.  
 */
public class PackageInstaller

翻阅源码,InstallApk*.java相关的一共两个demo
InstallApkSessionApi.java //静默安装
InstallApk.java //普通安装,调用系统install intent进行安装

下面是InstallApkSessionApi.java的具体demo

package com.example.android.apis.content;

// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageInstaller;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


/**
 * Demonstration of package installation and uninstallation using the package installer Session
 * API.
 *
 * @see InstallApk for a demo of the original (non-Session) API.
 */
public class InstallApkSessionApi extends Activity {
  private static final String PACKAGE_INSTALLED_ACTION =
      "com.example.android.apis.content.SESSION_API_PACKAGE_INSTALLED";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.install_apk_session_api);

    // Watch for button clicks.
    Button button = (Button) findViewById(R.id.install);
    button.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        PackageInstaller.Session session = null;
        try {
          PackageInstaller packageInstaller = getPackageManager().getPackageInstaller();
          PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
              PackageInstaller.SessionParams.MODE_FULL_INSTALL);
          int sessionId = packageInstaller.createSession(params);
          session = packageInstaller.openSession(sessionId);

          addApkToInstallSession("HelloActivity.apk", session);

          // Create an install status receiver.
          Context context = InstallApkSessionApi.this;
          Intent intent = new Intent(context, InstallApkSessionApi.class);
          intent.setAction(PACKAGE_INSTALLED_ACTION);

          //此处也可以使用getBoradcast或者getService回调通知
          PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
          IntentSender statusReceiver = pendingIntent.getIntentSender();

          // Commit the session (this will start the installation workflow).
          session.commit(statusReceiver);
        } catch (IOException e) {
          throw new RuntimeException("Couldn't install package", e);
        } catch (RuntimeException e) {
          if (session != null) {
            session.abandon();
          }
          throw e;
        }
      }
    });
  }

  private void addApkToInstallSession(String assetName, PackageInstaller.Session session)
      throws IOException {
    // It's recommended to pass the file size to openWrite(). Otherwise installation may fail
    // if the disk is almost full.
    try (OutputStream packageInSession = session.openWrite("package", 0, -1);
       InputStream is = getAssets().open(assetName)) {
      byte[] buffer = new byte[16384];
      int n;
      while ((n = is.read(buffer)) >= 0) {
        packageInSession.write(buffer, 0, n);
      }
    }
  }

  // Note: this Activity must run in singleTop launchMode for it to be able to receive the intent
  // in onNewIntent().
  @Override
  protected void onNewIntent(Intent intent) {
    Bundle extras = intent.getExtras();
    if (PACKAGE_INSTALLED_ACTION.equals(intent.getAction())) {
      int status = extras.getInt(PackageInstaller.EXTRA_STATUS);
      String message = extras.getString(PackageInstaller.EXTRA_STATUS_MESSAGE);

      switch (status) {
        case PackageInstaller.STATUS_PENDING_USER_ACTION:
          // This test app isn't privileged, so the user has to confirm the install.
          Intent confirmIntent = (Intent) extras.get(Intent.EXTRA_INTENT);
          startActivity(confirmIntent);
          break;

        case PackageInstaller.STATUS_SUCCESS:
          Toast.makeText(this, "Install succeeded!", Toast.LENGTH_SHORT).show();
          break;

        case PackageInstaller.STATUS_FAILURE:
        case PackageInstaller.STATUS_FAILURE_ABORTED:
        case PackageInstaller.STATUS_FAILURE_BLOCKED:
        case PackageInstaller.STATUS_FAILURE_CONFLICT:
        case PackageInstaller.STATUS_FAILURE_INCOMPATIBLE:
        case PackageInstaller.STATUS_FAILURE_INVALID:
        case PackageInstaller.STATUS_FAILURE_STORAGE:
          Toast.makeText(this, "Install failed! " + status + ", " + message,
              Toast.LENGTH_SHORT).show();
          break;
        default:
          Toast.makeText(this, "Unrecognized status received from installer: " + status,
              Toast.LENGTH_SHORT).show();
      }
    }
  }
}

另外,权限要求:

需要系统签名
permission

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

 到此这篇关于Android P实现静默安装的方法示例(官方Demo)的文章就介绍到这了,更多相关Android P 静默安装 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Android 更新RecyclerView的好方法

    Android 更新RecyclerView的好方法

    在使用RecyclerView的时候不免要修改RecyclerView的数据,使用notifyDataSetChanged()来刷新界面,但是当数据多,而只是修改了一点的数据,或者刷新比较频繁,这样就会导致界面卡顿,用户交互特别不好,这时可以使用RecyclerView方法解决,具体实现代码大家参考下本文吧
    2017-06-06
  • Android自定义Chronometer实现短信验证码秒表倒计时功能

    Android自定义Chronometer实现短信验证码秒表倒计时功能

    这篇文章主要介绍了Android自定义ChronometerView实现类似秒表倒计时,短信验证码倒计时功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-11-11
  • Android编程开发实现多线程断点续传下载器实例

    Android编程开发实现多线程断点续传下载器实例

    这篇文章主要介绍了Android编程开发实现多线程断点续传下载器,涉及Android多线程,文件传输及断点续传的相关技巧,需要的朋友可以参考下
    2016-01-01
  • 在Android中访问WebService接口的方法

    在Android中访问WebService接口的方法

      最近公司有个项目需要从Android平台访问WebService接口,实现向发布的函数传递对象。在网上找了一些资料,发现使用ksoap2可以调用WebService传递对象。
    2013-05-05
  • Android中传递图片的2种方法

    Android中传递图片的2种方法

    这篇文章主要介绍了Android中传递图片的2种方法,本文分别给出种方法的操作代码实例,需要的朋友可以参考下
    2015-04-04
  • Android底部导航栏的三种风格实现

    Android底部导航栏的三种风格实现

    这篇文章主要介绍了Android底部导航栏的三种风格实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-06-06
  • Android GridView实现动画效果实现代码

    Android GridView实现动画效果实现代码

    这篇文章主要介绍了 Android GridView实现动画效果实现代码的相关资料,需要的朋友可以参考下
    2017-03-03
  • Android异常 java.lang.IllegalStateException解决方法

    Android异常 java.lang.IllegalStateException解决方法

    这篇文章主要介绍了Android异常 java.lang.IllegalStateException解决方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-11-11
  • Android Studio实现音乐播放器

    Android Studio实现音乐播放器

    这篇文章主要为大家详细介绍了Android Studio实现音乐播放器,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-11-11
  • android自定义View之复合控件

    android自定义View之复合控件

    这篇文章主要为大家详细介绍了android自定义View之复合控件,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-06-06

最新评论