hlb*_*llo 6 android share xamarin.forms
我创建了一个 Xamarin Forms (PCL) 解决方案,目前我专注于 Android 项目。我正在尝试使用依赖服务实现图像共享。图像位于 Android 项目的 drawable 文件夹中。但是,每次运行下面的代码时,应用程序都会崩溃:发生未处理的异常。我检查了输出日志,但没有什么特别之处。是否有人能够查看我的代码并告诉我其中是否有错误?
非常感谢
界面:
public interface IShare
{
void Share(ImageSource imageSource);
}
Run Code Online (Sandbox Code Playgroud)
Xml:
<ContentPage.Content>
<Image x:Name="LogoImage" Source="icon.png"/>
</ContentPage.Content>
Run Code Online (Sandbox Code Playgroud)
代码隐藏:
private void Action_Clicked(object sender, EventArgs e)
{
DependencyService.Get<IShare>().Share(LogoImage.Source);
}
Run Code Online (Sandbox Code Playgroud)
ShareClass(在Android项目中):
[assembly: Dependency(typeof(ShareClass))]
namespace MyProject.Droid
{
public class ShareClass : Activity, IShare
{
public async void Share(ImageSource imageSource)
{
var intent = new Intent(Intent.ActionSend);
intent.SetType("image/png");
var handler = new ImageLoaderSourceHandler();
var bitmap = await handler.LoadImageAsync(imageSource, this);
var path = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads
+ Java.IO.File.Separator + "logo.png");
using (var os = new System.IO.FileStream(path.AbsolutePath, FileMode.Create))
{
bitmap.Compress(Bitmap.CompressFormat.Png, 100, os);
}
intent.PutExtra(Intent.ExtraStream, Android.Net.Uri.FromFile(path));
Forms.Context.StartActivity(Intent.CreateChooser(intent, "Share Image"));
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我用于 ShareClass 的代码,以最终实现共享意图,希望它对某人有所帮助:
[assembly: Xamarin.Forms.Dependency(typeof(ShareClass))]
namespace MyProject.Droid
{
public class ShareClass: MainActivity, IShare
{
public async void Share(ImageSource imageSource)
{
var intent = new Intent(Intent.ActionSend);
intent.SetType("image/jpeg");
IImageSourceHandler handler;
if (imageSource is FileImageSource)
{
handler = new FileImageSourceHandler();
}
else if (imageSource is StreamImageSource)
{
handler = new StreamImagesourceHandler(); // sic
}
else if (imageSource is UriImageSource)
{
handler = new ImageLoaderSourceHandler(); // sic
}
else
{
throw new NotImplementedException();
}
var bitmap = await handler.LoadImageAsync(imageSource, CrossCurrentActivity.Current.Activity);
Java.IO.File path = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads
+ Java.IO.File.Separator + "MyDiagram.jpg");
using (System.IO.FileStream os = new System.IO.FileStream(path.AbsolutePath, System.IO.FileMode.Create))
{
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, os);
}
intent.AddFlags(ActivityFlags.GrantReadUriPermission);
intent.AddFlags(ActivityFlags.GrantWriteUriPermission);
intent.PutExtra(Intent.ExtraStream, FileProvider.GetUriForFile(CrossCurrentActivity.Current.Activity, "com.mypackagename.fileprovider", path));
CrossCurrentActivity.Current.Activity.StartActivity(Intent.CreateChooser(intent, "Share Image"));
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5016 次 |
最近记录: |