我尝试打开设备的图库,以便用户选择一张照片,然后我得到它的路径...但是我的Stream总是返回null,然后,我有一个例外,因为... 我不知道出了什么问题 有人能帮我吗? 它是一个xamarin表单项目,现在我正在使用android进行测试。
我的主要活动
[Activity(Label = "neoFly_Montana", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = false, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
//inicializa imageCircle
ImageCircleRenderer.Init();
//inicializa o mapa
global::Xamarin.FormsMaps.Init(this, bundle);
LoadApplication(new App());
}
// Field, property, and method for Picture Picker
public static readonly int PickImageId = 1000;
public TaskCompletionSource<Stream> PickImageTaskCompletionSource { set; get; }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent intent)
{
base.OnActivityResult(requestCode, resultCode, intent);
if (requestCode == PickImageId)
{
if ((resultCode == Result.Ok) && (intent != null))
{
Android.Net.Uri uri = intent.Data;
Stream stream = ContentResolver.OpenInputStream(uri);
// Set the Stream as the completion of the Task
PickImageTaskCompletionSource.SetResult(stream);
}
else
{
PickImageTaskCompletionSource.SetResult(null);
}
}
}
}
在我的android项目中我也有这个类: (在此 PicturePickerImplementation:IPicturePicker 不起作用,IPicturePicker无法识别...我不知道为什么
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System.Threading.Tasks;
using System.IO;
using Xamarin.Forms;
using neoFly_Montana.Droid;
[assembly: Dependency(typeof(PicturePickerImplementation))]
namespace neoFly_Montana.Droid
{
public class PicturePickerImplementation : IPicturePicker
{
public Task<Stream> GetImageStreamAsync()
{
// Define the Intent for getting images
Intent intent = new Intent();
intent.SetType("image/*");
intent.SetAction(Intent.ActionGetContent);
// Get the MainActivity instance
MainActivity activity = Forms.Context as MainActivity;
// Start the picture-picker activity (resumes in MainActivity.cs)
activity.StartActivityForResult(
Intent.CreateChooser(intent, "Select Picture"),
MainActivity.PickImageId);
// Save the TaskCompletionSource object as a MainActivity property
activity.PickImageTaskCompletionSource = new TaskCompletionSource<Stream>();
// Return Task object
return activity.PickImageTaskCompletionSource.Task;
}
}
}
我在pcl中的界面:
public interface IPicturePicker
{
Task<Stream> GetImageStreamAsync();
}