标准广播
- 新建一个类 MyBoradcastReceiver 接受广播
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
/**
* Created by yi on 2017/3/30.
*/
public class MyBoradcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"received in MyBroadcastReceiver",Toast.LENGTH_SHORT).show();
}
}
- 在AndroidManifest.xml的applicaton文件中增加一个receiver标签
<receiver
android:name=".MyBoradcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.broadcase.MyBoradcastReceiver.MY_BROADCAST"/>
</intent-filter>
</receiver>
3.在layout.xml文件中增加按钮标签
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Click"/
- 在Activity中增加一个按钮点击触发事件
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("com.broadcase.MyBoradcastReceiver.MY_BROADCAST");
sendBroadcast(intent);
}
});