当应用程序在后台时,我有一个运行正常的PackageBroadcastReceiver。我需要它来关闭在关闭时添加/删除的包。但是,事实并非如此。
有没有办法用BroadcastReceiver做这个或者我应该转移到服务?
这里是代码:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="23" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.cresan.antivirus.StockingActivity"
android:label="@string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="com.tech.applications.coretools.advertising.PackageBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.PACKAGE_INSTALL" />
<action android:name="android.intent.action.PACKAGE_ADDED" />
<data android:scheme="package"/>
</intent-filter>
</receiver>
</application>
我的PackageBroadcastReceiver:
public class PackageBroadcastReceiver extends BroadcastReceiver
{
static IPackageChangesListener _listener;
static public void setPackageBroadcastListener(IPackageChangesListener listener)
{
_listener=listener;
}
@Override
public void onReceive(Context ctx, Intent intent)
{
if(_listener!=null && Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction()))
_listener.OnPackageAdded(intent);
if(_listener!=null && Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction()))
_listener.OnPackageRemoved(intent);
}
}
干杯。
答案 0 :(得分:0)
您肯定需要实施后台服务才能执行此操作。见the developer guide.
然后,您可以在服务中以编程方式注册BroadcastReceiver:
private PackageBroadcastReceiver packageBroadcastReceiver;
@Override
public void onCreate() {
super.onCreate();
this.packageBroadcastReceiver = new PackageBroadcastReceiver();
this.packageBroadcastReceiver.setPackageBroadcastListener(new IPackageChangesListener() {
public void OnPackageAdded(Intent i) {
//do something here- probably start an activity
}
...
});
IntentFilter packageFilter = new IntentFilter("android.intent.action.PACKAGE_ADDED");
packageFilter.addAction("android.intent.action.PACKAGE_INSTALL");
packageFilter.addDataScheme("package");
this.registerReceiver(this.packageBroadcastReceiver, packageFilter);
}
@Override
public void onDestroy(){
super.onDestroy();
this.unregisterReceiver(this.packageBroadcastReceiver);
}
答案 1 :(得分:0)
尝试在服务中注册广播接收器。活动被破坏后,接收器将被销毁,因此您将无法获得广播事件。