Reputation: 50
I am trying to build a Home Launcher App in Xamarin
Currently I have a Xamarin Forms App with Access to Xamarin Android through interfaces. In Xamarin Android I have a method to find all package Names on the device like this:
[assembly: Xamarin.Forms.Dependency(typeof(Launcher.Droid.GetLauncher))]
namespace Launcher.Droid
{
class GetLauncher : MainActivity,IGetLauncher
{
public string GetPackageName(int index)
{
var apps = Android.App.Application.Context.PackageManager
.GetInstalledApplications(PackageInfoFlags.MatchAll);
return apps[index].PackageName; ;
}
}
}
I can access this function from Xamarin Forms to get the package names.
Now I want to launch an App with a certain package Name:
I have tried the following code also in Xamarin Android accessed by an Interface from Xamarin Forms:
[assembly: Xamarin.Forms.Dependency(typeof(Launcher.Droid.GetLauncher))]
namespace Launcher.Droid
{
class GetLauncher : MainActivity,IGetLauncher
{
public void RunApp(int index)
{
var apps = Android.App.Application.Context
.PackageManager.GetInstalledApplications(PackageInfoFlags.MatchAll);
Intent intent =
PackageManager.GetLaunchIntentForPackage(apps[index].PackageName);
StartActivity(intent);
}
}
}
which results in the following error:
Java.Lang.NullPointerException Nachricht = Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference
The Error occurs on the PackageManager.GetLaunchIntentForPackage Line. I am testing on a physical device.
Any Help or hints would be highly appreciated.
Upvotes: 1
Views: 1213
Reputation: 15011
Try to change your codes like below:
[assembly: Xamarin.Forms.Dependency(typeof(Launcher.Droid.GetLauncher))]
namespace Launcher.Droid
{
class GetLauncher : IGetLauncher
{
public void RunApp(int index)
{
var apps = Android.App.Application.Context.PackageManager.GetInstalledApplications(PackageInfoFlags.MatchAll);
Intent intent = Android.App.Application.Context.PackageManager.GetLaunchIntentForPackage(apps[index].PackageName);
Android.App.Application.Context.StartActivity(intent);
}
}
}
Upvotes: 1