I am trying to recive BroadcastReceiver when i click button on main.xml
**mainfest.xml**
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".boardCast">
<intent-filter>
<action android:name="borad.cast"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
</application>
above manifest file receiver Register with our own action like android.action= "broad.cast"
**mainActivty.java**
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button samll = (Button)findViewById(R.id.button1);
samll.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent ii = new Intent(getApplicationContext(),boardCast.class);
PendingIntent pp = PendingIntent.getBroadcast(getApplicationContext(), 0, ii, 0);
}
});
}
above Activty class cantain button and when i click that button BroadcastReceiver should trigger boardcast.java
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if(intent.getAction().equals("borad.cast")){
Toast.makeText(context, "sample", Toast.LENGTH_LONG).show();
}
}
get rid of the pending intent and do it this way:
on the onclick for your button's click event call:
public void onClick(View v) {
// TODO Auto-generated method stub
broadcastMsg("borad.cast");
}
});
// and here is the function definition:
public void broadcastMsg(String intentName) {
final Intent intent = new Intent(intentName);
sendBroadcast(intent);
}
来源:https://stackoverflow.com/questions/16238297/trigger-broadcastreceiver-when-i-click-button