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

让人想犯罪 __ 提交于 2019-12-05 02:54:25

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/12693992/android-intent-and-startactivity-in-libgdx-non-activity-or-androidapplication-c

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