Search code examples
androidandroid-intentbroadcastreceiver

Android broadcast receiver not working


I try to get a broadcast receiver working. Should be as simple as possible, I have my manifest like this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mytest.intentRec" android:versionCode="1"
    android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name"
        android:debuggable="true">
        <activity android:name=".mainAct" 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="com.mytest.intentRec.MyIntentRec"
                  android:enabled="true" >
        </receiver>
    </application>
    <uses-sdk android:minSdkVersion="7" />
</manifest> 

As you can see I have a main activity mainAct, this does nothing but sending the broadcast once started:

public class mainAct extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        this.sendBroadcast(new Intent());
    }
}

and I have a class MyIntentRec, which is as simple as it could:

public class MyIntentRec extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.v("IntentRec", "got it");
    }
}

What I expect is that when I start my app that a broadcast is sent and being picked up and that a log entry is written. I don't see that log entry and I don't see any error. I'm suspecting to have either an error in the manifest or in sending the broadcast. I just created an empty intent there, does it need to be some intent with certain properties?


Solution

  • Please setClass for your Intent,

    EX:

    public class mainAct extends Activity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            Intent i=new Intent("any string");
            i.setClass(this, MyIntentRec.class);
            this.sendBroadcast(i);
        }
    }
    

    That is what it means " The absence of any filters means that it can be invoked only by Intent objects that specify its exact class name."

    [Old answer]
    You should register what kind of actions you need in the manifest.
    Ex:

        <receiver android:name="com.mytest.intentRec.MyIntentRec" android:enabled="true" >
            <intent-filter>
                <action  android:name="your.intent" />
            </intent-filter>
        </receiver>
    

    send it,

    this.sendBroadcast(new Intent("your.intent"));