Xamarin.Forms替代StartActivityForResult

时间:2017-07-09 18:50:49

标签: android android-intent xamarin xamarin.forms ringtonemanager

我目前正在尝试从RingtoneManager.ActionRingtonePicker中选择Uri。我输入了所有额外的设置并设置了适当的标志。 但是,我只能致电StartActivity(intent)。无论如何,我从铃声选择器中获取选择并使用intent.getParceableExtra(RingtoneManager.ExtraRingtonePickedUri);。我的代码在下面,如果我可以用一个解决方法替换context.StartActivity(intent),那就太棒了。

public async Task<string> pickAndReceiveRingtone(string currentUri)
{
    Intent intent = new Intent(RingtoneManager.ActionRingtonePicker);
    intent.PutExtra(RingtoneManager.ExtraRingtoneShowSilent, false);
    intent.PutExtra(RingtoneManager.ExtraRingtoneTitle, "Select a ringtone");
    intent.PutExtra(RingtoneManager.ExtraRingtoneShowDefault, false);
    intent.PutExtra(RingtoneManager.ExtraRingtoneType, (int)RingtoneType.Alarm);
    intent.PutExtra(RingtoneManager.ExtraRingtoneExistingUri, RingtoneManager.GetDefaultUri(RingtoneType.Alarm));
    intent.SetFlags(ActivityFlags.NewTask);

    //Replace below
    /*await*/ context.StartActivity(intent);

    //Grab selected uri here
    currentUri = ...
    return  currentUri;

}

1 个答案:

答案 0 :(得分:1)

实际上,Xamarin.Forms存在于Activity中,Activity中的OnActivityResult方法仍然可以被调用。

DependencyService课程中,使用StartActivityForResult()方法,如下所示:

public void StartActivityInAndroid()
{
    Intent intent = new Intent(RingtoneManager.ActionRingtonePicker);
    intent.PutExtra(RingtoneManager.ExtraRingtoneShowSilent, false);
    intent.PutExtra(RingtoneManager.ExtraRingtoneTitle, "Select a ringtone");
    intent.PutExtra(RingtoneManager.ExtraRingtoneShowDefault, false);
    intent.PutExtra(RingtoneManager.ExtraRingtoneType, (int)RingtoneType.Alarm);
    intent.PutExtra(RingtoneManager.ExtraRingtoneExistingUri, RingtoneManager.GetDefaultUri(RingtoneType.Alarm));

    //intent.SetFlags(ActivityFlags.NewTask);// remember to delete this

    var activity = Forms.Context as Activity;

    activity.StartActivityForResult(intent, 0);
}

然后,您可以使用OnActivityResult方法接收结果:

    protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
    {
        base.OnActivityResult(requestCode, resultCode, data);
        if (resultCode != Result.Ok)
        {
            return;
        }
        else
        {
            Android.Net.Uri uri = (Android.Net.Uri)data.GetParcelableExtra(RingtoneManager.ExtraRingtonePickedUri);
            Log.Debug("onActivityResult====", "" + uri);

            Toast.MakeText(this, uri + "", ToastLength.Short).Show();
            if (uri != null)
            {
                switch (requestCode)
                {
                    case 0:
                        RingtoneManager.SetActualDefaultRingtoneUri(this, RingtoneType.Ringtone, uri);
                        break;
                }
            }
        }
    }