广播的静态注册方式
程序结构:
activity_main.xml:
<androidx.constraintlayout.widget.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=".MainActivity">
<Button
android:id="@+id/broadcast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送广播!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java:
package cn.edu.cdut.broadcastdemo1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity {
static TextView info;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
info =findViewById(R.id.hello);
Button btn =findViewById(R.id.broadcast);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setComponent(new ComponentName("cn.edu.cdut.broadcastdemo1","cn.edu.cdut.broadcastdemo1.MyReceiver"));
intent.setAction("com.example.BROADCAST");
intent.putExtra("msg","这是一条广播消息");
sendBroadcast(intent);
}
});
}
}
MyRececiver.java:
package cn.edu.cdut.broadcastdemo1;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String info =intent.getStringExtra(“msg”);
Log.i(intent.getAction(),info);
MainActivity.info.setText(info);
}
}
AndroidMainfest.xml:
<?xml version="1.0" encoding="utf-8"?><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/Theme.BroadcastDemo1">
<activity android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyReceiver"
android:exported="true">
<intent-filter>
<action android:name="com.example.BRAODCAST"></action>
</intent-filter>
</receiver>
</application>