我正在尝试使用intents
和broadcast receiver
获取所有已安装的应用程序,但问题是我从不直接使用onReceive
方法,因此无法获取任何包名称。我使用以下代码:
killappbcr.java
public class KillAppBCR extends Activity {
private static final String TAG = "BroadcastReceiver";
BroadcastReceiver receiver;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
receiver = new TestBroadcastReceiver();
registerReceiver(receiver, filter);
Log.e(TAG, "onCreate");
Toast.makeText(KillAppBCR.this,"onCreate",Toast.LENGTH_SHORT).show();
}
testbroadcastReceiver.java测试广播接收器
public class TestBroadcastReceiver extends BroadcastReceiver
{
private static final String TAG = "TestBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent)
{
String actionStr = intent.getAction();
Log.e(TAG, "onReceive");
Toast.makeText(context,"onReceive",Toast.LENGTH_SHORT).show();
if (Intent.ACTION_PACKAGE_ADDED.equals(actionStr)) {
Uri data = intent.getData();
}
}
}
androidmanifest.xml文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.KillAppBCR"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".KillAppBCR"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".TestBroadcastReceiver">
<intent-filter>
<action android:name="com.KillAppBCR" />
</intent-filter>
</receiver>
</application>
</manifest>
原木分类
07-19 18:39:48.768: ERROR/BroadcastReceiver(512): CC
07-19 18:39:49.008: INFO/ActivityManager(58): Displayed activity com.KillAppBCR/.KillAppBCR: 685 ms (total 685 ms)
07-19 18:39:54.338: DEBUG/dalvikvm(121): GC_EXPLICIT freed 259 objects / 12032 bytes in 157ms
07-19 18:42:58.943: DEBUG/SntpClient(58): request time failed: java.net.SocketException: Address family not supported by protocol
07-19 18:47:58.989: DEBUG/SntpClient(58): request time failed: java.net.SocketException: Address family not supported by protocol
问题在哪里?请帮助我,我想接收所有已安装应用程序的广播。
谢谢
最佳答案
为什么你的活动代码很可能不起作用:你只是暂时用registerReceiver
注册了接收者。所以在你关闭你的活动后,安卓会再次杀死你的接收器。
您需要做的是在androidmanifest.xml中将com.KillAppBCR
替换为android.intent.action.PACKAGE_ADDED
。这告诉android永久注册你的接收器。