1

我正在使用来自蓝牙聊天示例应用程序的代码。我希望用户离开应用程序时,他应该能够接收数据。所以如果我这样做:

 case MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                // construct a string from the valid bytes in the buffer
                String readMessage = new String(readBuf, 0, msg.arg1);
                mConversationArrayAdapter.add(mConnectedDeviceName+":  " + readMessage);
                /***************************ADDED***************************/
                System.out.println("Number is"+(int)(readMessage.charAt(0)));

                /***************************ADDED***************************/
                break;

我确实在 DDMS 中看到了 println 语句。

如果我这样做:

 case MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                // construct a string from the valid bytes in the buffer
                String readMessage = new String(readBuf, 0, msg.arg1);
                mConversationArrayAdapter.add(mConnectedDeviceName+":  " + readMessage);
                /***************************ADDED***************************/
                System.out.println("Number is"+(int)(readMessage.charAt(0)));
               Toast.makeText(getApplicationContext(), "received!! "
                        + mConnectedDeviceName, Toast.LENGTH_SHORT).show();

                /***************************ADDED***************************/
                break;

即使我离开应用程序并且我在其他应用程序中,我也会看到 toast 消息。

最后,我真正想要的是无论我的应用程序是否在我收到特定数据时没有运行,打开一个警报对话框,如果我按下是,例如做一些事情(我想在是时发出 http 请求,在否时被转移到我的应用程序。)

这是我的代码:

 case MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                // construct a string from the valid bytes in the buffer
                String readMessage = new String(readBuf, 0, msg.arg1);
                mConversationArrayAdapter.add(mConnectedDeviceName+":  " + readMessage);
                /***************************ADDED***************************/

                new AlertDialog.Builder(getApplicationContext())
                .setTitle("Title")
                .setMessage("Message")
                .setPositiveButton("Yes",
                 new DialogInterface.OnClickListener() {
                     public void onClick(DialogInterface dialog, int which) {
                          //make http request
                }
             })
                .setNegativeButton("No",
                          new DialogInterface.OnClickListener() {
                             // @Override
                              public void onClick(DialogInterface dialog, int which) {
                                   //open my app
                               }

                          }).show();


                /***************************ADDED***************************/
                break;

在这种情况下,当我离开我的应用程序并接收数据时,我会强制关闭。我想参数 getApplicationContext 是错误的,但我不知道该使用什么。

解决方案:我改用了通知。

4

0 回答 0