目录
一.本章要学习的内容
- 了解使用Intent进行组件通信的原理;
- 了解Intent过滤器的原理和匹配机制;
- 掌握发送和接收广播的方法
任务1、普通广播;
任务2、系统广播;
任务3、有序广播;
1、练习使用静态方法和动态方法注册广播接收器
2、练习发送广播消息的方法;
二.代码部分
(一)创建项目
(二)项目结构
(三)MainActivity
package com.example.demo5;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void staticSys(View view){
Intent intent = new Intent(MainActivity.this, StaticReceiver.class);
startActivity(intent);
}
public void actionSys(View view){
Intent intent = new Intent(MainActivity.this, ActionReceiver.class);
startActivity(intent);
}
}
(四)ActionReceiver
package com.example.demo5;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.Nullable;
import com.example.demo5.MyReceiver;
import com.example.demo5.R;
public class ActionReceiver extends Activity {
protected static final String ACTION = "com.example.demo5.ACTION_CUSTOM_EVENT";
private MyReceiver myReceiver;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actionlayout);
}
public void sendAct(View view){
Intent intent=new Intent(); //实例化Intent
intent.setAction(ACTION); //设置Intent的action属性
intent.putExtra("info","动态方法");
sendBroadcast(intent);
}
@SuppressLint("UnspecifiedRegisterReceiverFlag")
public void register(View view){
myReceiver = new MyReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION);
registerReceiver(myReceiver, filter);
}
public void unregister(View view){
unregisterReceiver(myReceiver);
}
}
(五)MyOrderReceiverOne
package com.example.demo5;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyOrderReceiverOne extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("我收到有序的啦");
}
}
(六)MyReceiver
package com.example.demo5;
import android.content.BroadcastReceiver;