我正在尝试设置一项服务,以检查何时在设备中安装了新的活动更新。我已经在应用程序活动中这样做了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()
不会被调用。
这是我的主要活动:
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()
不被调用?
谢谢你。
我的代码基于这两个参考: