1.新建一个项目,在activiy_main.xml中新建一个按钮,我们用来发送广播
activiy_main.xml↓↓↓
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="mylistview.lmq.cn.broadcasttest2.MainActivity01">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</android.support.constraint.ConstraintLayout>
2.点击查看图片建立接收者的方法![J%V%BBR9V6R0Y(J$N~Z)OR.png
建立一个接受者 broader cast receiver ,名字随你定,这里我叫AnotherRecieviercastReciver,里面放置一个Toast就可以,让其显示信息我接收到了
package mylistview.lmq.cn.broadcasttest2;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AnotherReceivercastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
Toast.makeText(context,"recived in anotherBroadcastReceiver",Toast.LENGTH_SHORT).show();
}
}
3.我们要配置AndroidMainifest.xml,我们在建立broadcastReceiver之后,系统自己给我门在这里面注册了
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="mylistview.lmq.cn.broadcasttest2">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity01">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver//这一部分就是啦
android:name=".AnotherReceivercastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>//这一句是我们加的
<action android:name="com.example.broadcasttest.MY_BROADCAST"/>
//我们接受的广播是com.example.broadcasttest.MY_BROADCAST这一种的广播
</intent-filter>
</receiver>
</application>
</manifest>
4.我们来写MainActivity
将button加上监听,点击就会发送com.example.broadcasttest.MY_BROADCAST这一种的广播
package mylistview.lmq.cn.broadcasttest2;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity01 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main01);
Button button=findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent("com.example.broadcasttest.MY_BROADCAST");
sendBroadcast(intent);
}
});
}
}