I’m new to android and am desperately with trying to understand how broadcast receivers work. I have built an example which doesn’t work, but I cannot imagine why.
My usecase:
When the activity “TestApp” starts, it has to activate a broadcast receiver “Receiver”, this one starts another activity “Main” which is defined in the same manifest.
Here’s the receiver difinition in my manifest xml
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Main"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="stas.test.intent.action.blablub"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
<receiver android:name=".Receiver"
android:enabled="true">
<intent-filter>
<action android:name="stas.test.intent.action.myreceiver"/>
</intent-filter>
</receiver>
</activity>
</application>
this is the activity to be started by the receiver:
action android:name="stas.test.intent.action.blablub" (Main.java)
Here’s the receiver’s code
public class Receiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Intent newIntent = new Intent();
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
newIntent.setAction("stas.test.intent.action.blablub");
newIntent.addCategory("android.intent.category.DEFAULT");
System.out.println("dd");
context.startActivity(newIntent);
}
}
an here’s the initiating activity which calls the receiver
public class TestApp extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = new Intent();
intent.setAction("stas.test.intent.action.myreceiver");
getApplicationContext().sendBroadcast(intent);
}
}
When I start TestApp, Receiver will never start and Main not either.
Haven’t tested this, but isn’t the receiver supposed to be a child of the application node?