【发布时间】:2014-10-02 13:41:52
【问题描述】:
我是 android 新手,非常想了解广播接收器的工作原理。我建立了一个不起作用的示例,但我无法想象为什么。
我的用例:
当活动“TestApp”启动时,它必须激活一个广播接收器“Receiver”,这个接收器启动另一个活动“Main”,它在同一个清单中定义。
这是我的清单 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>
这是接收者要启动的活动:
action android:name="stas.test.intent.action.blablub" (Main.java)
这是接收者的代码
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);
}
}
这里是调用接收者的启动活动
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);
}
}
当我启动 TestApp 时,Receiver 永远不会启动,Main 也不会。
【问题讨论】: