我使用名为“com.lpj.test”的自定义动作静态定义broadcastreceiver。正如在AndroidManifest.xml中注册的那样:
<receiver android:name=".TestBroadcast">
<intent-filter>
<action android:name="com.lpj.test"/>
</intent-filter>
coustome BroadcastReceiver Class是这样的:
public class TestBroadcast extends BroadcastReceiver {
public static final String RECEIVER = "com.lpj.test";
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(RECEIVER)){
Log.i("BroadcastTest", "Broadcast Start!");
Toast.makeText(context, "Broadcast Start!",
Toast.LENGTH_LONG).show();
}
}
}
然后在主要活动中向我的BroadcastReceiver发送意图
public class replyer extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_replyer);
this.findViewById(R.id.button).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
sendBroadcast(new Intent("com.lpj.test"));
}
});
}
}
当我点击按钮时它根本不起作用.Logcat没有提供TAG“BroadcastTest”的消息,也没有Toast-Box弹出。没有发生。
答案 0 :(得分:1)
我认为操作名称中的问题是。(点),请尝试以下方式,
<receiver android:name=".TestBroadcast">
<intent-filter>
<action android:name="comLpjTest"/>
</intent-filter>
@Override
public void onClick(View v)
{
sendBroadcast(new Intent("comLpjTest"));
}