MAUI Android 关联文件类型

发布时间 2023-05-26 16:10:39作者: 野生程序员

实现效果

打开某个文件,后缀是自己想要的类型,在弹出的窗口(用其它应用打开)的列表中显示自己的应用图标

点击后可以获得文件信息以便于后续的操作

用其它应用打开

实现步骤

以注册.bin后缀为例,新建一个MAUI项目

调整启动模式

修改Platforms\Android\MainActivity.cs

[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]

调整为

[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density, LaunchMode = LaunchMode.SingleTop)]

末尾增加了LaunchMode = LaunchMode.SingleTop

更改启动模式为栈顶模式,解释如下

SingleTop模式又称栈顶模式,每次启动一个Activity的时候,首先会判断当前任务栈的栈顶是否存在该Activity实例,
如果存在则重用该Activity实例,并且回调其onNewIntent()函数,否则就创建一个新实例。

这样,我们就可以在回调函数中获得文件路径

注册关联类型

还是修改Platforms\Android\MainActivity.cs

Activevity注册的下一行添加

[IntentFilter(new[] { Intent.ActionSend, Intent.ActionView }, Categories = new[] { Intent.CategoryDefault }, DataMimeType = @"application/octet-stream")]//.bin文件关联

application/octet-streamBin的Mime类型,根据自己的文件后缀,可以查询所有官方 MIME 类型的列表

监听意图

重写OnNewIntent拿到意图,并从中获取数据,通过 Messenger 进行数据传递

也可以通过试图跳转进行传递,具体参考:MAUI文档-传递数据

新建一个消息模型

引用 CommunityToolkit.Mvvm NuGet 包

创建消息模型

namespace ITLDG.Message
{
    public class NewFileMessage : ValueChangedMessage<Android.Net.Uri>
    {
        public NewFileMessage(Android.Net.Uri uri) : base(uri)
        {
        }
    }
}

发送消息

using Android.Content;//引用这个

...

	public class MainActivity : MauiAppCompatActivity
    {
	
		...
	
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            //这里调用下,不然首次启动没有意图
            OnNewIntent(Intent);
        }
        protected override void OnNewIntent(Intent intent)
        {
            base.OnNewIntent(intent);
            if (intent.Action == Intent.ActionView)
            {
                WeakReferenceMessenger.Default.Send(new NewFileMessage(intent.Data));
            }
        }
		
		
		...
		
    }
	
	...
	

接收消息

ViewModel中接收消息

WeakReferenceMessenger.Default.Register<NewFileMessage>(this, (r, m) =>
{
    if (m.Value == null) return;
    var intent = m.Value;
    //文件路径
    // var path = intent.Path
    //得到文件流
    var stream = CurrentActivity.ContentResolver.OpenInputStream(intent);
    var memoryStream = new MemoryStream();
    stream.CopyTo(memoryStream);
    //完整的数据
    var bytes=memoryStream.ToArray()
});

总结

起初,我使用视图跳转传递参数的方式传递获取到的Intent,尝试了几次无法传递到MainPage

后加了一个跳转页,拿到消息后传到到中转页,中专页拿到数据后再将数据回穿回来,但是这样传递,无法传递Intent类型和Uri类型,我不得不先将文件写到缓存目录,再传递缓存目录

这样的流程始终无法满意,最终改为使用Messenger 进行数据传递,问题解决

另外,起初首次打开文件唤醒APP,无法获取到Intent,APP后台运行打开文件唤醒正常

后来在stackoverflow找到了答案