MainActivity.java
package com.example.mybroadcastreceive5_3_2;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "sun";
//自定义广播名称
private static final String DYNAMICACTION = "com.example.mybroadcastreceive5_3_2.MY_TEST"; //动态广播的Action字符串
private Button sendmessage;
//定义接收器
private AnotherBroadcastReceiver anotherBroadcastReceiver;
private BroadcastTestreceive broadcastReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initdata();
sendmessage = (Button)findViewById(R.id.button);
sendmessage.setOnClickListener(this);
}
//设置过滤信息
private void initdata(){
anotherBroadcastReceiver = new AnotherBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
//设置优先级的方式
//intentFilter.setPriority(100);
intentFilter.addAction(DYNAMICACTION);
registerReceiver(anotherBroadcastReceiver,intentFilter);
}
//必须要记得销毁
@Override
protected void onDestroy(){
super.onDestroy();
if(anotherBroadcastReceiver != null){
unregisterReceiver(anotherBroadcastReceiver);
}
}
//发送广播
@Override
public void onClick(View v) {
Log.d(TAG,"1111111111");
Intent intent = new Intent();
intent.setAction(DYNAMICACTION);
//传递数据
intent.putExtra("key","how are you");
sendBroadcast(intent);
//有序广播的发送函数
// sendOrderedBroadcast(intent,null);
}
}
AnotherBroadcastReceiver.java
package com.example.mybroadcastreceive5_3_2;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class AnotherBroadcastReceiver extends BroadcastReceiver {
public static final String TAG = "sun";
private IntentFilter intentFilter;
@Override
public void onReceive(Context context, Intent intent) {
//根据action判断监听到的消息
if (intent.getAction().equals(DYNAMICACTION))
{
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Log.d(TAG,"Another receiver 4444444");
Toast.makeText(context,"received in AnotherBroadcastReceiver",Toast.LENGTH_SHORT).show();
//获取传递过来的数据
String msg = intent.getStringExtra("key");
Log.d(TAG,msg);
throw new UnsupportedOperationException("Not yet implemented");
}else{
Log.d(TAG,"Another receiver 5555555");
}
//中断广播的方式
//abortBroadcast();
}
}