我正在为我的应用程序编写应用程序更新程序。在我确保我在设备上有我的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);
这会启动我的安装程序,显示应用程序的权限,我可以点击"安装"。但从这里,应用程序只是关闭,我没有得到任何消息(我本以为对话框告诉我安装成功,给我选择"关闭"或"打开")。它直接进入设备的主屏幕,无需进一步通知。
顺便说一句,当我手动打开它时,应用程序确实更新了。如何使安装程序按照预期的方式运行?有什么要确定的意图吗?
在写这篇文章的时候,我想知道这种情况发生的原因是当前的应用程序只是在设备上被覆盖,从而关闭它,并且在某种程度上没有得到意图的结果,因为它的源被杀死了?
你所能做的就是用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>
和
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);
}
}
}
要成功更新,你需要启动intent,并使用URI指示你的更新应用作为新任务。
final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(PATH_TO_APK));
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
我的帖子如下:
Android应用程序更新问题
首先,除非您是根用户或具有系统权限,否则无法在没有提示的情况下安装。我想你不是在问这个,但是你的一段话不清楚。
其次,如果安装一个正在运行的应用程序的更新版本,你看到的行为是意料之中的:应用程序被强制关闭和更新。你不能就地更新。您可以检测安装何时中止,因为调用安装程序的活动将被恢复。
为了更新一个正在运行的应用程序并保持它运行,你需要一个单独的进程(app)来监控安装和重启你的应用程序。