android以编程方式更新apk并查看安装结果

Flo*_*anu 17 android android-intent apk android-install-apk

我正在为我的应用编写应用更新程序.确保我在设备上安装了apk后,这就是我在应用程序中执行的操作,我正在尝试更新:

Intent promptInstall = new Intent(Intent.ACTION_VIEW);
File f = new File(apkLocation);    
promptInstall.setDataAndType(Uri.fromFile(f), "application/vnd.android.package-archive");
_context.startActivity(promptInstall);
Run Code Online (Sandbox Code Playgroud)

这将启动我的安装程序,显示应用程序权限,然后我可以单击"安装".但是从这里应用程序只是关闭,我得不到任何消息(我会期望对话框告诉我安装成功,让我选择按"关闭"或"打开").它只是进入设备的主屏幕,恕不另行通知.

另外,当我手动打开它时,应用程序确实已更新.如何让安装程序按预期完成?是否有任何意图设定?

在写这篇文章的时候,我想知道这种情况发生的原因是当前应用程序只是在设备上被覆盖,从而关闭它并且程度上没有得到意图的结果,因为它的源被杀死了?

小智 16

您所能做的就是使用意图过滤器注册接收器,android.intent.action.PACKAGE_INSTALL或者android.intent.action.PACKAGE_REPLACED从中重新启动应用程序.

<receiver android:enabled="true" android:exported="true" android:label="BootService" android:name="com.project.services.BootService">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
            <data android:scheme="package"/>
        </intent-filter>
         <intent-filter>
            <action android:name="android.intent.action.PACKAGE_ADDED"/>
            <data android:scheme="package"/>
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.PACKAGE_INSTALL"/>
            <data android:scheme="package"/>
        </intent-filter>
         <intent-filter>
            <action android:name="android.intent.action.PACKAGE_CHANGED"/>
            <data android:scheme="package"/>
        </intent-filter>
         <intent-filter>
            <action android:name="android.intent.action.PACKAGE_REPLACED"/>
            <data android:scheme="package"/>
        </intent-filter>
    </receiver>
</application>
Run Code Online (Sandbox Code Playgroud)

public class BootService extends BroadcastReceiver {
  @Override
  public void onReceive(Context context, Intent intent) {

    if (intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED)) {
        Intent serviceIntent = new Intent();
        serviceIntent.setClass(context,Controller.class);
        serviceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(serviceIntent);
    } else if (intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED)) {
        Intent serviceIntent = new Intent();
        serviceIntent.setClass(context, Controller.class);
        serviceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(serviceIntent);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 我尝试过它,效果很好.我刚刚添加了`if(context.getApplicationInfo().packageName.equals((intent.getData()).getSchemeSpecificPart()))`检查以确保我已经捕获了正确的广播.没有它,我的应用程序将在商店内执行任何应用程序更新后启动. (4认同)
  • 两个身体条件是一样的,为什么你写`if``if else`陈述?!- 我错了吗 ? (2认同)