触发广播接收器,当我点击按钮(Trigger BroadcastReceiver when I cl

2019-09-01 04:52发布

我想recive广播接收器,当我点击的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>

上述清单文件接收器注册与我们自己的行动像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);

        }
    });
}

上述Activty类cantain按钮,当我点击该按钮广播接收器应触发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();
    }
}

Answer 1:

摆脱挂起的意图,并做到这一点是这样的:

上的onclick您的按钮的单击事件调用:

 public void onClick(View v) {
            // TODO Auto-generated method stub
           broadcastMsg("borad.cast");

        }
    });

//这里是函数的定义:

public void broadcastMsg(String intentName) {
        final Intent intent = new Intent(intentName);
        sendBroadcast(intent);
    }


文章来源: Trigger BroadcastReceiver when I click Button