'Launching Android Applications through Unity / Java plugins
I'm attempting to connect my Unity project to Java via plugin in order to launch another application, and have been unsuccessful with attempts to do so.
Unity (C#):
public void AndroidCallNonStatic() {
using (AndroidJavaClass javaClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) {
using (AndroidJavaObject activity = javaClass.GetStatic<AndroidJavaObject>("currentActivity")) {
object[] targs = new object[1] { "org.mozilla.firefox" };
activity.Call("nonStaticMethod", targs);
}
}
}
Java (Android):
import com.unity3d.player.UnityPlayerActivity;
public class Main extends UnityPlayerActivity {
public static Context mContext;
public static PackageManager mManager;
@Override
protected void onCreate(Bundle bundle)
{
super.onCreate(bundle);
mContext = this;
mManager = getPackageManager();
}
public void nonStaticMethod(String s)
{
Log.d("TAG","nonStatic method was called");
launchApp(s);
}
public static void StaticMethod(String s)
{
Log.d("TAG","Static method was called " + s);
launchApp(s);
}
public void launchApp(String packageName)
{
Intent intent = getPackageManager().getLaunchIntentForPackage(packageName);
if (intent != null)
{
// Activity was found, launch new app
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else
{
// Activity not found. Send user to market
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("market://details?id="+packageName));
startActivity(intent);
}
}
}
Can anyone help me out with this? I've exhausted the extent of my Android/Unity knowledge and can't understand why it's not working. My thoughts are that it has something to do with the package name.
Solution 1:[1]
You can launch an Android application from Unity directly in C#:
public void LaunchApp(String packageName)
{
AndroidJavaClass unityPlayer;
AndroidJavaObject currentActivity;
AndroidJavaObject packageManager;
AndroidJavaObject launchIntent;
unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
packageManager = currentActivity.Call<AndroidJavaObject>("getPackageManager");
launchIntent = packageManager.Call<AndroidJavaObject>("getLaunchIntentForPackage", packageName);
currentActivity.Call("startActivity", launchIntent);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jox |
