1

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

Mihriban Minaz
  • 3,025
  • 2
  • 31
  • 52
luna
  • 41
  • 1
  • 1
  • 5
  • issue with final variable. just declare the string app as global and refer in your button click – Ameer Mar 27 '16 at 06:25
  • what do you mean by " refer in your button click" can you explain it in detail. I am new to android – luna Mar 27 '16 at 07:37
  • check shree krishna's answer. – Ameer Mar 27 '16 at 09:28
  • Possible duplicate of [Launch an application from another application on Android](https://stackoverflow.com/questions/3872063/launch-an-application-from-another-application-on-android) – Mehdi Dehghani Apr 18 '19 at 12:22

3 Answers3

2

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);
    }
}
Muhammad Younas
  • 2,008
  • 21
  • 33
2

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
}
Adnan Amjad
  • 2,483
  • 1
  • 19
  • 29
  • thanks it works. But in my case, the application has to be chosen from the spinner . So I have used String to strore the package name – luna Mar 27 '16 at 07:24
1

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
}
Shree Krishna
  • 8,273
  • 6
  • 36
  • 67