简体   繁体   中英

how to launch an app from another app in android

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

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
}

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
}

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM