Почему мой код не запускает закрепленный ярлык моего приложения в Android 8+ (Oreo+)?
Я пытаюсь закрепить некоторые динамические ярлыки моего приложения, они будут созданы, когда пользователь создаст пользовательское время.
У меня есть две версии кода, которые я запускаю код из WebView с использованием JavaScriptInterface, но ни одна из них не работает должным образом, так как одна из них пытается открыть Play Store, а вторая говорит: "Приложение не работает "не существует", когда я создал ярлык из приложения.
Этот запускает магазин Play Store:
[Export]
[JavascriptInterface]
public void PinCustomTime(string time)
{
var manager = context.GetSystemService(Context.ShortcutService) as ShortcutManager;
if (manager.IsRequestPinShortcutSupported)
{
try
{
//Create the new intent
var intent = new Intent(Intent.ActionView);
//Set the flag of the new task
intent.AddFlags(ActivityFlags.NewTask);
//Get the apps from the Play Store
intent.SetData(Android.Net.Uri.Parse("market://details?id=" + context.PackageName));
//Set the custom time as a variable
intent.PutExtra("customTime", time);
//Set the info of the shortcut
var info = new ShortcutInfo.Builder(context, $"tmTimer_{DateTime.Now.ToString("yyMMddHHmmss")}")
.SetShortLabel("TM Timer")
.SetLongLabel("TM Timer")
.SetIcon(Icon.CreateWithResource(context, Resource.Drawable.iconInv))
.SetIntent(intent)
.Build();
//Set values
var successCallback = PendingIntent.GetBroadcast(context, /* request code */ 0,
intent, /* flags */ 0);
//Creates the shortcut
manager.RequestPinShortcut(info, successCallback.IntentSender);
}
catch (System.Exception ex)
{
}
}
}
Это говорит о том, что приложение не существует:
[Export]
[JavascriptInterface]
public void PinCustomTime(string time)
{
var manager = context.GetSystemService(Context.ShortcutService) as ShortcutManager;
if (manager.IsRequestPinShortcutSupported)
{
try
{
//Set the info of the shortcut with the App to open
var info = new ShortcutInfo.Builder(context, $"tmTimer_{DateTime.Now.ToString("yyMMddHHmmss")}")
.SetShortLabel("TM Timer")
.SetLongLabel("TM Timer")
.SetIcon(Icon.CreateWithResource(context, Resource.Drawable.iconInv))
.SetIntent(new Intent(Intent.ActionView).SetData(Android.Net.Uri.Parse(context.PackageName)))
.Build();
//Create the new intent
var intent = manager.CreateShortcutResultIntent(info);
intent.PutExtra("customTime", time);
//Set values
var successCallback = PendingIntent.GetBroadcast(context, /* request code */ 0,
intent, /* flags */ 0);
//Creates the shortcut
manager.RequestPinShortcut(info, successCallback.IntentSender);
}
catch (System.Exception ex)
{
}
}
}
Я попробовал третий код, но тот пытался открыть любое приложение, которое не было моим собственным. Кто-нибудь испытывал нечто подобное? Или знаете, что мне не хватает?
Я следовал за несколькими уроками и примерами, подобными этим:
Спасибо за поддержку.
PS:
- Все мои тесты были сделаны под Android Pie.
- Я построил код на Xamarin.Android на C#, но если у вас есть идея на Kotlin или Java, я могу перенести ее.
2 ответа
Когда пользователь нажимает на ярлык, это намерение будет запущено:
new Intent(Intent.ActionView).SetData(Android.Net.Uri.Parse(context.PackageName))
Чтобы запустить конкретное действие, замените его на (в Java):
Intent i = new Intent(context.getApplicationContext(), MainActivity.class);
i.setAction(Intent.ACTION_VIEW);
Перевод на C# следующий:
[Export]
[JavascriptInterface]
public void PinCustomTime(string time)
{
var manager = context.GetSystemService(Context.ShortcutService) as ShortcutManager;
if (manager.IsRequestPinShortcutSupported)
{
//Create the new intent
var intent = new Intent(context, typeof(MainActivity));
//Set the flag of the new task
intent.SetAction(Intent.ActionView);
//Set the Time
intent.PutExtra("customTime", time);
//Set the info of the shortcut
var info = new ShortcutInfo.Builder(context, $"tmTimer_{DateTime.Now.ToString("yyMMddHHmmss")}")
.SetShortLabel("TM Timer")
.SetLongLabel("TM Timer")
.SetIcon(Icon.CreateWithResource(context, Resource.Drawable.iconInv))
.SetIntent(intent)
.Build();
//Set values
var successCallback = PendingIntent.GetBroadcast(context, /* request code */ 0,
intent, /* flags */ 0);
//Creates the shortcut
manager.RequestPinShortcut(info, successCallback.IntentSender);
}
}
Я получил некоторую поддержку от:
Как получить MainActivity для Intent, созданного в другом классе в проекте Xamarin.Droid?