一、同一包内自定义广播
1.首先新建一个广播接收器类MyReceiver.java
File-new-other-Brodecast Receiver,然后在弹出框输入广播接收器的类名
然后修改其中的代码
package com.klns.demobroadcast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"克里诺斯的新广播",Toast.LENGTH_SHORT).show();
}
}
修改AndroidManifest.xml代码:
箭头所指的包名要和软件的包名相同不然就会无响应,后面也是如此
修改activity_main.xml,添加一个发送按钮
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="发送广播"/>
</LinearLayout>
修改MainActivity.java,添加点击事件:
package com.klns.demobroadcast;
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;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent("com.klns.demobroadcast.MY_BROADCAST");
intent.setComponent(new ComponentName(getPackageName(),"com.klns.demobroadcast.MyReceiver"));
sendBroadcast(intent);
}
});
}
}
没有加intent.setComponent(new ComponentName(getPackageName(),“com.example.broadcasttest.MyBroadcastReceiver”)); 这一句,程序运行后是没有响应的。
第一个参数是目标广播接收器所在应用的包名,第二个参数是目标广播接收器类全路径(即MyReceiver类的路径)。
运行截图:
不同包内接收广播:
还没想到怎么写,我先空着。。。。。