nms
nms

Reputation: 577

Android Intent and startActivity in Libgdx (non Activity or AndroidApplication class)

Please help me how to run the below code in Libgdx thread - in render(),create(),etc...

public class MyGame implements ApplicationListener, InputProcessor {
...
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
.....
Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(
"http://market.android.com/details?id=" + getPackageName()));
startActivity(marketIntent);

The code has compilation errors. I googled some similar threads, but no exact code examples with "startActivity". Thanks.

Upvotes: 3

Views: 9175

Answers (2)

P.T.
P.T.

Reputation: 25177

LibGDX is a platform independent library, so all the code that uses the LibGDX platform netural APIs must itself be platform independent (so no Android, or Windows calls, etc). To access platform-specific features, the standard way is to define an interface, and use the interface from your platform-neutral code. Then create an implementation of the interface in the Android (or Desktop) specific projects for your application, and pass that implementation when you initialize your libGDX component.

This tutorial has more details: http://code.google.com/p/libgdx-users/wiki/IntegratingAndroidNativeUiElements3TierProjectSetup

Here's another description of the same approach (its better written, but the example isn't as clearly relevant to you): https://github.com/libgdx/libgdx/wiki/Interfacing-with-platform-specific-code

The tutorial is interested in accessing Android native UI elements, but the basic idea is the same as what you want.

Upvotes: 16

Raghav Sood
Raghav Sood

Reputation: 82583

You're getting an error because startActivity() is a method in the Activity class.

To be able to use this, your class must:

  1. Extend Activity or a class that extends Activity
  2. Have an Activity instance somewhere, possible passed in through the constructor

In the second case, you'll have something like:

public class MyNonActivity {
    Context mContext;
    public MyNonActivity(Context context) {
        mContext = context;
    }

    public void myMethod() {
        Intent intent = new Intent(mContext, Next.class);
        mContext.startActivity(intent);
    }
}

and to call your class from an Activity or Service or something else that subclasses Context or one of its subclasses:

MyNonActivity foo = new MyNonActivity(getBaseContext());

Make sure you do the above in or after onCreate() has been called.

Upvotes: 3

Related Questions