I'm a newbie in multithreading, and can't understand why onActivityResult() is never called in my code.
I need to pause a thread until my needed variable is changed. I call java function ShowFileDialog() from cocos2d-x using jni, and it's called from a thread other than UI thread. Then I start activity to pick an image from gallery, and all this is done on UI thread. After that I need to wait until filePath variable is changed, and when it will happen - return filePath string to cocos2d-x.
This is my code:
private static MyActivity thisActivity;
private static String filePath;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
thisActivity = this;
}
public static String ShowFileDialog() {
filePath = new String();
thisActivity.runOnUiThread(new Runnable() {
public void run() {
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
thisActivity.startActivityForResult(photoPickerIntent, 1);
}
});
synchronized(filePath)
{
try {
filePath.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return filePath;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
...
filePath.notifyAll();
}
Activity from Intent is started, but onActivityResult() is never called. I can't understand why it happens - does it mean that UI thread is somehow blocked?
filePath.wait() blocks your GLThread in GLSurfaceView because Cocos2d-x mainloop was called from the GLThread. And calling startActivityForResult() will cause to call onPause() of the current active Activity, it's Cocos2dxActivity. Cocos2dxActivity.onPause() will call GLSurfaceView.onPause(). GLSurfaceView.onPause() will call sGLThreadManager.wait(). But the GLThread was blocked by your code. Thus the deadlock will occur.
I recommend you to use callback mechanism instead of just waiting on GLThread. In this case, you might be able to use this CCImagePicker.