Android使用广播发送消息
本文实例为大家分享了Android使用广播发送消息的具体代码,供大家参考,具体内容如下
1.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:orientation="vertical" tools:context=".MainActivity"> <EditText android:id="@+id/edit" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入要发送的内容" /> <Button android:id="@+id/send" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="发送"/> </LinearLayout>
2.MainActivity
import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private EditText edit; private Button send; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //输入框id edit = (EditText) findViewById(R.id.edit); //按钮id send = (Button) findViewById(R.id.send); //点击按钮发送广播 send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //获取输入的文本 String content=edit.getText().toString(); Intent intent = new Intent(); //包名 intent.setAction("xx.xx.xx"); intent.putExtra("msg", content); sendBroadcast(intent); } }); } }
3.创建广播MyReceiver
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.Toast; public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //跳转新的页面 //Intent i = new Intent(context, MainActivity2.class); //i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //context.startActivity(i); //获取广播内容 String content=intent.getStringExtra("msg"); Toast.makeText(context, "广播接受者:"+content, Toast.LENGTH_SHORT).show(); } }
清单文件中记得注册广播
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="com.xxx.xxx"> <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" tools:ignore="GradleOverrides,OldTargetApi" /> <application ... /> <receiver android:name=".MyReceiver" android:permission="TODO" tools:ignore="ExportedReceiver"> <intent-filter > <action android:name="com.xxx.xxx"/> </intent-filter> </receiver> ... </application> </manifest>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)