gpt4 book ai didi

android - 带有 IntentFilter 的 BroadcastReceiver for Intent.ACTION_PACKAGE_REPLACED 在服务中不工作

转载 作者:太空宇宙 更新时间:2023-11-03 12:20:39 25 4
gpt4 key购买 nike

我正在尝试设置一项服务来检查设备中何时安装了 Activity 的新更新。我已经在应用程序 Activity 中这样做了,在 list 中声明了 Broadcastreceiver 并且它工作得很好。

但是,当我尝试在服务中运行该接收器并动态声明它时,我的 onReceive 永远不会被调用。这是我的服务代码:

public class UpdateService extends Service {    
private static String mPackage = "com.my.package";
private static String mActivityName = "myActivity";
private BroadcastReceiver mUpdateReceiver;

@Override
public void onCreate() {
super.onCreate();
mUpdateReceiver = new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent) {
Log.d("mTag","In the BroadcastReceiver onReceive()");
if (intent.getAction().equalsIgnoreCase(Intent.ACTION_PACKAGE_REPLACED)) {
// Log that a new update is has been found
Log.d("mTag","New version of the app has been installed.");
Log.d("mTag", "Intent data: " + intent.getDataString());
Log.d("mTag","My package: " + mPackage);
}
}
};

Log.d("mTag","In the service onCreate() method.");
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
registerReceiver(mUpdateReceiver,filter);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("mTag","UpdateService started");
return Service.START_STICKY;
}

@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mUpdateReceiver);
Log.d("mTag","Service destroyed");
}

@Override
public IBinder onBind(Intent arg0) {
return null;
}
}

服务 onCreate() 中的日志被调用,这告诉我服务已启动并正在运行。但是,在通过 adb 安装和替换一些应用程序后,BroadcastReceiver 中的任何日志都不会调用 onReceive() 方法。

这是我的主要 Activity :

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, UpdateService.class));
}
}

你们知道为什么 onReceive() 没有被调用吗?

谢谢。

我的代码基于这两个引用:

最佳答案

您应该将数据架构添加到您的 IntentFilter。

 IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_ADDED);

filter.addDataScheme("package");

registerReceiver(mUpdateReceiver,filter);

关于android - 带有 IntentFilter 的 BroadcastReceiver for Intent.ACTION_PACKAGE_REPLACED 在服务中不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16994926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com