关闭活动时,按后退或完成()不起作用

时间:2017-07-12 12:49:55

标签: java android bluetooth

我有一个不断通过蓝牙接收数据的Android应用,并将数据从MainActivity推送到MainActivity2IntentMainActivity有一个ImageButton,允许切换到MainActivity2

我使用的变量Clicked在点击true时为ImageButton,在false时为onBackpressed()。当我点击true/false时,我使用ImageButton条件启动蓝牙接收。我能够在MainActivity2收到蓝牙数据,但onBackpressed关闭MainActivity2返回MainActivity。然后,只要新数据到达,它就会再次自动启动MainActivity2。 我希望MainActivity2仅在我点击ImageButtononBackPressed时获取数据,MainActivity2永久关闭,但不会发生。

MainActivity - ImgButtonFunction

public void onImgButtClick(View view){
    Intent getNameScreenIntent = new Intent(MainActivity.this, MainActivity2.class);
    final int result=1;
    Clicked=true;

    startActivityForResult(getNameScreenIntent,result);
}

MainActivity - 数据接收处理程序的一小部分

if (action.equals(UartService.ACTION_DATA_AVAILABLE)) {

    final byte[] txValue = intent.getByteArrayExtra(UartService.EXTRA_DATA);
    runOnUiThread(new Runnable() {
        public void run() {
            try {
                String text = new String(txValue, "UTF-8");
                /*Character[] Chararray = new Character[text.length()];

                for (int i = 0; i < text.length(); i++) {
                    Chararray[i] = new Character(text.charAt(i));
                }*/

                /*  Character[] Chararray = new Character[text.length()];
                    byte txByte=0;
                    for (int i = 0; i < txValue.length(); i++) {
                    Chararray[i] = new Character(text.charAt(i));}
                */

                String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());

                /*for (String retval: text.split("\n")) {
                    Chararray[i]=retval;
                    listAdapter.add("[" + currentDateTimeString + "] RecvX: " + retval + "km/h");
                }*/            

                String  str1 = String.valueOf(txValue[0]);
                listAdapter.add("[" + currentDateTimeString + "] RecvX: " +str1 + "km/h");
                messageListView.smoothScrollToPosition(listAdapter.getCount() - 1);
                if (Clicked==true) {
                    Intent ii = new Intent(MainActivity.this, MainActivity2.class);
                    ii.putExtra("RxString", str1);
                    startActivity(ii);
                }
            } catch (Exception e) {
                  Log.e(TAG, e.toString());
            }
        }
    });
}

MainActivity2 - onBackPressed处理程序

@Override
public void onBackPressed() {
    Intent i=new Intent(this, MainActivity.class);
    i.putExtra("Clicked",false);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_SINGLE_TOP);
    startActivity(i);
    finish();
}

1 个答案:

答案 0 :(得分:0)

启动activity2时,请通过startActivityByResult()

启动它

onBackPressed()执行setResult(RESULT_OK, new Intent().putExtra("clicked", false))并致电完成()

在您的activity1中,您可以在

中获得结果
onActivityResult()