Trigger BroadcastReceiver when I click Button

爱⌒轻易说出口 提交于 2019-12-01 10:46:19

问题


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();
    }
}

回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!