问题描述
- 关于安卓全局喇叭的问题,我是新手
-
我要发送一个保准的广播,内容是MY_BROADCAST,首先我定义了一个类,集成BroadcastReceiver,在里面的onReceiver函数中写出收到这条广播后的反应,代码如下:
package com.example.broadcasttest;import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;public class MyBroadcastReceiver extends BroadcastReceiver{
@Override public void onReceive(Context context,Intent intent) { Toast.makeText(context, "received in mybroadcastreceiver", Toast.LENGTH_LONG).show(); }
}
然后我为这个类和接收的广播做注册,代码如下:最后我在为主函数添加按钮并且写事件监听,代码如下:
Button button01=(Button)findViewById(R.id.button_01);
button01.setOnClickListener(new OnClickListener()
{
public void onClick(View view)
{
Intent intent=new Intent("com.example.broadcasttest.MY_BROADCAST");
sendBroadcast(intent);
}
});
但是事实上我在运行程序的时候按完按钮却什么也不显示,请问各位大神们这是怎么回事呀?
解决方案
你得先注册广播,注册广播分为两种,一种 是静态注册,一种是动态注册,而且你的public void onReceive(Context context,Intent intent)
{
Toast.makeText(context, "received in mybroadcastreceiver", Toast.LENGTH_LONG).show();
}
写错了
得这样写:
public void onReceive(Context context,Intent intent)
{ if(intent.getAction().equals("com.example.broadcasttest.MY_BROADCAST")){
Toast.makeText(context, "received in mybroadcastreceiver", Toast.LENGTH_LONG).show();
}
Toast.makeText(context, "received in mybroadcastreceiver", Toast.LENGTH_LONG).show();
}
解决方案二:
public void onReceive(Context context,Intent intent)
{ if(intent.getAction().equals("com.example.broadcasttest.MY_BROADCAST")){
Toast.makeText(context, "received in mybroadcastreceiver", Toast.LENGTH_LONG).show();
}
}