How to show Dialog from a static method

谁说我不能喝 提交于 2019-12-10 18:14:22

问题


In my game, which is done for both Android and IOS using cocos2dx, I have to show video(for Android). I am planning to show it in Dialog(on top of game view). Problem is that, I don't have any Activity referenced to show Dialog(as Dialogs can only be shown in Activities). Even though, In cocos2dx lib folder, there is a Cocos2dxActivity but I am not getting how to make use of it. From C++ code, I am calling a static method from Java class as below

void LMJNICommunicator::showVideo()
{
     LOGD("initialiseDatabase inside LMJNICommunicator");

     jmethodID methodID = 0;
     JNIEnv *pEnv = 0;
     pEnv = getJNIEnv();
     jclass ret = pEnv->FindClass("com/mobinius/lostmonstersclass/LMDatabaseDataManager");
     methodID = pEnv->GetStaticMethodID(ret, "showVideo", "()V");

     if (! methodID)
     {
          LOGD("Failed to find static method id of %s", "showVideo");
          return;
     }

     pEnv->CallStaticVoidMethod(ret,methodID);
     pEnv->DeleteLocalRef(ret);

}

Static method(which is in normal Java class) which I am calling from C++ code

Class LMDatabaseDataManager {

    public static void showVideo() {

         Dialog dialog = new Dialog(Cocos2dxActivity.getInstance());
         dialog.show();
        // getting Can't create handler inside thread that has not called Looper.prepare() error
    }
}

I tried to make use of Handler like this but did not get result(got same error in that post). Also tried to get a static Context like this.

So, is my way correct? If not correct, please suggest a way how can I implement the same. Thanks.

Edit:

Finally got answer for this. Earlier I tried running on UI thread with Application static context as in this link but did not get... with Cocos2dxActivity activity instance I got it.

Class LMDatabaseDataManager {

    public static void showVideo() {        

    Cocos2dxActivity.getInstance().runOnUiThread(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            Dialog dialog = new Dialog(Cocos2dxActivity.getInstance());
            dialog.show();            
        }
    });

    }
}

回答1:


Try adding the appropriate lines in Cocos2dxActivity:

public class Cocos2dxActivity extends Activity {
    private static Cocos2dxActivity instance = null;
   @Override public void onCreate(Bundle b) {
     ...
     this.instance = this;
     }

     public static Cocos2dxActivity getInstance() {
        return instance;
     }



}

When you want to create your dialog:

if (Cocos2dxActivity.getInstance() != null)  {
    AlertDialog dialog = new AlertDialog(Cocos2dxActivity.getInstance());
    // rest of your dialog code goes here
}


来源:https://stackoverflow.com/questions/13377300/how-to-show-dialog-from-a-static-method

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