how to launch an app from another app in android

怎甘沉沦 提交于 2019-12-13 10:28:43

问题


I am developing an app in which i want to launch any application installed on my device. I have tried the following code.

Button bClock = (Button) findViewById(R.id.button1);
String app="com.whatsapp";
bClock.setOnClickListener(new OnClickListener() {
  public void onClick(View v) {
    Intent i = new Intent(Intent.ACTION_MAIN);
    PackageManager managerclock = getPackageManager();
    i = managerclock.getLaunchIntentForPackage(app);
    i.addCategory(Intent.CATEGORY_LAUNCHER);
    startActivity(i);
  }
});

It shows error:

Cannot refer to a non-final variable app inside an inner class defined in a different method

But if I directly use "com.whatsapp" instead of storing in String, it is working. Help me to solve this issue


回答1:


For your code correction please make String app="com.whatsapp"; a final variable or you can use package name directly like following

You should use the function of the package manager.

Context ctx=this; // or you can replace **'this'** with your **ActivityName.this**
try {
Intent i = ctx.getPackageManager().getLaunchIntentForPackage("com.whatsapp");
ctx.startActivity(i);
} catch (NameNotFoundException e) {
    // TODO Auto-generated catch block
}



回答2:


If so then make it final

final String app="com.whatsapp";

OR

Declare it as global variable of class like

public class MyClass {

String app="com.whatsapp";

//Other methods
}



回答3:


Use the Following Function

public void startNewActivity(Context context, String packageName) {
    Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
    if (intent != null) {
        // We found the activity now start the activity
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    } else {
        // Bring user to the market or let them choose an app?
        intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setData(Uri.parse("market://details?id=" + packageName));
        context.startActivity(intent);
    }
}


来源:https://stackoverflow.com/questions/36244479/how-to-launch-an-app-from-another-app-in-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!