问题复现
最近做的项目遇到了一个这样的问题:当软件是覆盖安装时,系统会依次发出以下广播: 那我们如何知道 ADDED 和 REMOVED 的广播是由 REPLACED 发出的动作呢?
解决方案
intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)
通过它即可判断安装和卸载是否来自于覆盖安装的通知,附上代码:
public class AppReceiver extends BroadcastReceiver {
private AppReceiverListener mAppReceiverListener;
public interface AppReceiverListener {
void added(String pageName);
void remove(String pageName);
void replaced(String pageName);
}
public void setAppReceiverListener(AppReceiverListener appReceiverListener) {
mAppReceiverListener = appReceiverListener;
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_PACKAGE_ADDED.equals(action) && mAppReceiverListener != null
&& !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
String pageName = intent.getData().getSchemeSpecificPart();
mAppReceiverListener.added(pageName);
Log.e("AppReceiver", ": ACTION_PACKAGE_ADDED 软件已安装");
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && mAppReceiverListener != null
&& !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
String pageName = intent.getData().getSchemeSpecificPart();
mAppReceiverListener.remove(pageName);
Log.e("AppReceiver", ": ACTION_PACKAGE_REMOVED 软件已卸载");
} else if (Intent.ACTION_PACKAGE_REPLACED.equals(action) && mAppReceiverListener != null) {
String pageName = intent.getData().getSchemeSpecificPart();
mAppReceiverListener.replaced(pageName);
Log.e("AppReceiver", ": ACTION_PACKAGE_REPLACED 软件已覆盖");
}
}
}
思路来自于: android中的Package替换流程
|