简体   繁体   中英

BroadcastReceiver is not able to receive the Intent

I want to write a BroadcastReceiver to receive the application install action. But it failed, so I test if my receiver is well or not. So custom a intent, it also filed. below is my code. Please help me correct it. public class MyInstallReceiver extends 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");
    }
}
}

custom intent

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

Everythong looks good, expect a typo in your manifest. It should be <intent-filter> and not <Intent-filter>

I don't know about correct spelling in your manifest, but this code is definitely works very well:

<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>

Every application install/uninstall will trigger this receiver.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM