为什么我没有收到已安装的应用广播?

时间:2011-07-19 09:49:29

标签: android android-manifest broadcastreceiver

我正在尝试使用intentsbroadcast 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>

Log Cat

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

问题出在哪里?请帮帮我,我想收到所有已安装应用的广播。

谢谢

2 个答案:

答案 0 :(得分:3)

为什么您的活动代码很可能不起作用:您只是暂时使用registerReceiver注册接收器。因此,关闭您的活动后,Android将再次终止您的接收器。

您需要做的是在AndroidManifest.xml中将com.KillAppBCR替换为android.intent.action.PACKAGE_ADDED。这告诉Android永久注册您的接收器。

答案 1 :(得分:0)

我认为你必须确保你的应用程序只运行gui,也许它应该有一个服务组件,它可以记录所有正在进行的安装。恕我直言,你试图只阅读新装置,对吗?因为这就是代码应该做的事情,但是正如TomTasche指出的那样,如果你远离它,你的应用程序显然会被杀死。一旦你的申请死了,没什么,虚无...没有意图,没有通知,简单。