欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

.Net的Android应用程序BroadcastReceiver使用记录一个pit-3.app1广播

最编程 2024-03-21 19:11:35
...

广播为了方便测试,加了一个输入框和按钮,方便点击按钮发送广播查看效果。
app1广播代码:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:orientation="vertical"  
    android:padding="16dp"  
    android:gravity="center_horizontal">  
  
    <EditText  
        android:id="@+id/inputText"  
        android:layout_width="200dp"  
        android:layout_height="wrap_content"  
        android:hint="请输入"  
        android:inputType="text"  
        android:layout_marginBottom="16dp" />  
  
    <Button  
        android:id="@+id/buttonSubmit"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="提交"  
        android:background="?android:attr/textColorPrimaryInverse"  
        android:textColor="@android:color/black"  
        android:layout_gravity="center_horizontal"  
        android:padding="10dp" />  
  
</LinearLayout>

MainActivity

protected override void OnCreate(Bundle? savedInstanceState)
{
    base.OnCreate(savedInstanceState);

    // Set our view from the "main" layout resource
    SetContentView(Resource.Layout.activity_main);

    // 获取布局中的控件  
    EditText inputText = FindViewById<EditText>(Resource.Id.inputText);
    Button buttonSubmit = FindViewById<Button>(Resource.Id.buttonSubmit);

    // 为按钮设置点击事件监听器  
    buttonSubmit.Click += (sender, e) => {
        // 获取输入框中的文本  
        string text = inputText.Text;
        // 在这里处理文本,例如显示一个Toast或者发送数据到服务器等  
        Toast.MakeText(this, "广播: " + text, ToastLength.Short).Show();
        BroadcastMessage(text);
    };
}

private void BroadcastMessage(string value)
{
    // 创建一个新的Intent对象  
    Intent intent = new Intent("test");

    //intent.SetPackage("com.companyname.AndroidApp2");
    //intent.SetComponent(new ComponentName("com.companyname.AndroidApp2", ".Receiver"));
    // 如果你想传递额外的数据,可以添加到Intent的Extras中  
    intent.PutExtra("key", value);

    // 发送广播  
    SendBroadcast(intent);//, "com.companyname.permissions.my_broadcast"
}

为了尝试这个广播接收淌了很多坑,像intent.SetPackage和intent.SetComponent发送的时候都不是必须指定的(新旧版本都不需要),唯一需要指定的就是new Intent(“test”)中的这个action。
到这里发送广播就完事了。