You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中如何通过分享选项列表获取共享文本?

嘿,看起来你已经搞定了让应用出现在分享列表里的第一步,很棒!要获取被分享的实际文本,其实只需要在你的TextRecieve Activity里处理传入的Intent就可以啦,我给你一步步拆解:

第一步:确认Activity的Intent Filter配置

首先要确保你的Activity(通过Xamarin的Activity特性)配置了正确的Intent Filter——不过你已经能收到分享请求,这一步大概率没问题,但还是贴出来给你核对下:

[Activity(Label = "TextRecieve", Icon = "@drawable/ic_home", Theme = "@style/MainTheme", MainLauncher = true)]
[IntentFilter(new[] { Intent.ActionSend },
              Categories = new[] { Intent.CategoryDefault },
              DataMimeType = "text/plain")]
public class TextRecieveActivity : AppCompatActivity
{
    // 你的Activity代码
}

这里的DataMimeType = "text/plain"是核心,确保你的应用只接收文本类型的分享请求。

第二步:在Activity中提取共享文本

接下来分两种场景处理,覆盖应用首次启动和后台唤醒的情况:

场景1:应用首次启动时接收分享

在OnCreate方法里加入处理逻辑:

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    SetContentView(Resource.Layout.your_layout);

    // 检查当前Intent是否是文本分享请求
    if (Intent.Action == Intent.ActionSend && Intent.Type == "text/plain")
    {
        string sharedText = Intent.GetStringExtra(Intent.ExtraText);
        if (!string.IsNullOrEmpty(sharedText))
        {
            // 这里就拿到了共享的文本!
            // 比如你可以把它显示在TextView里:
            // TextView displayText = FindViewById<TextView>(Resource.Id.tv_shared_text);
            // displayText.Text = sharedText;
        }
    }
}

场景2:应用在后台运行时接收分享

如果你的应用已经在后台,收到分享请求会触发OnNewIntent方法,所以也要在这里处理:

protected override void OnNewIntent(Intent intent)
{
    base.OnNewIntent(intent);
    // 更新当前Activity的Intent为新的分享请求
    Intent = intent;

    // 重复提取文本的逻辑
    if (Intent.Action == Intent.ActionSend && Intent.Type == "text/plain")
    {
        string sharedText = Intent.GetStringExtra(Intent.ExtraText);
        if (!string.IsNullOrEmpty(sharedText))
        {
            // 处理共享文本的逻辑
        }
    }
}
小提醒
  • 一定要做空值判断哦,避免因为分享时没有传递文本导致崩溃
  • 如果之后想支持其他类型的分享(比如图片),只需要修改DataMimeType或者添加额外的IntentFilter就行

这样就能顺利获取到用户分享的文本啦!

内容的提问来源于stack exchange,提问作者mainlikn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:12:28