BroadcastReceiver无法接收Intent

时间:2015-07-28 12:10:38

标签: android android-intent broadcastreceiver

我想编写一个BroadcastReceiver来接收应用程序安装操作。但它失败了,所以我测试我的接收器是否良好。所以定制了一个意图,它也提交了。下面是我的代码。请帮我纠正一下。     公共类MyInstallReceiver扩展BroadcastReceiver { // public MyInstallReceiver(){ //}

@Override
public void onReceive(Context context, Intent intent) {
    Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
    Log.d("receiver", "Intent Detected");
    if (intent.getAction (). equals ("android.intent.action.PACKAGE_ADDED")) {
        String packageName = intent.getDataString ();
        //System.out.println ("installed:" + packageName + "package name of the program");
        Log.d("receiver","installed:" + packageName + "package name of the program");
    }
}
}

自定义意图

public void installAPK(View v){
   startActivity(intent);
    Intent intent = new Intent();
    intent.setAction("com.tutorialspoint.CUSTOM_INTENT");
    sendBroadcast(intent);
    Log.d("receiver", "Intent sent");
}

的Manifest.xml

       <receiver
        android:name=".MyInstallReceiver"
        android:enabled="true"
        android:exported="true" >
        <Intent-filter>
            <action   android:name = "android.intent.action.PACKAGE_ADDED"/>
            <action   android:name = "android.intent.action.PACKAGE_REMOVED"/>

            <action android:name="com.tutorialspoint.CUSTOM_INTENT">
            </action>
            <Data   android:scheme = "package"   />
        </Intent-filter>
    </receiver>

enter code here

2 个答案:

答案 0 :(得分:0)

Everythong看起来很好,期待你的清单中有拼写错误。它应该是<intent-filter>而不是<Intent-filter>

答案 1 :(得分:0)

我不知道你的清单中的拼写是否正确,但这段代码肯定能很好地运作:

<receiver android:name=".MyInstallReceiver">
        <intent-filter>
            <action android:name="android.intent.action.PACKAGE_REMOVED" />
            <action android:name="android.intent.action.PACKAGE_ADDED" />
            <data android:scheme="package"/>
        </intent-filter>
</receiver>

每个应用程序安装/卸载都会触发此接收器。