Dialog not displaying when calling from JNI

这是一篇非常有用的问答,将其复制到这里。

I have a native C function (with JNI of course) that should callback a java method to display a dialog but this dialog is never displayed.

This is how this works:

  1. C code calls a java method
  2. The java method logs something
  3. Then it calls showDialog(SOME_ID)
  4. The onCreateDialog(SOME_ID) is called
  5. The dialog is constructed using AlertDialog.Builder
  6. When I call AlertDialog alert = builder.create() the application just stops right there (without crashing or freezing) but only when this call starts from the C code.

The code is as follows:

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case SOME_ID:
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Message");
        builder.setPositiveButton(...);
        builder.setNegativeButton(...);

        AlertDialog alert = builder.create();
        System.out.println("...Never called from JNI");
        return alert;
    }
    return null;
}

In 6 I mean that I log something before and after calling builder.create() but the log after the create method is never called so the method never returns and the dialog is never created. I have a button to trigger the dialog and, as expected, it works.

I did another test, I printed getApplicationContext() calling directly from onCreate() and from onCreateDialog() (called from C code) and it is the same, because one of the first things I thought was that the onCreateDialog() was being called from another Context or something.

Do you have any idea why the dialog is not displaying?

share | improve this question
  

1 Answer

up vote 1 down vote accepted

The problem was that when calling back from JNI the application wasn't on UI Thread so the dialog was never shown. To fix it I used a Handler (on Activity):

public final Handler dialogHandler = new Handler(){     
    public void handleMessage(Message msg){
        showDialog(SOME_ID);
    }   
};

So instead of directly call showDialog() I do it by calling dialogHandler.sendMessage().

share | improve this answer
  

Your Answer















 
or

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值