Closing app on Backpress using Android Processing

edited May 2018 in Android Mode

I've been using this code indicated below:

public void onBackPressed() {
System.exit(0); return; }

It worked at processing 3.0, but it is not effective anymore in processing 3.3.7.

Any suggestion to make the code work on processing 3.3.7?

Answers

  • edited May 2018

    @myrds===

    try that

    this.getActivity().finish();

    • though i cannot see any reason to code the Back button because it is supposed to "finish" the current activity & put it in te background, which meas that "quitting" or "exiting" has no sense in the android world....
  • I already tried that, but it did not work. The reason why I try to include that code is because when I press the back button, my android device through a GUI app I created still stays connected to a target paired device and runs in the background.

    But once I re-access the GUI app, it reconnects to the paired device that is already connected, then detects it as it could not detect the target paired device.

    It works good with the home button but not with the back button, which in cases, should work the same on both.

  • As an additional, while the device could not reconnect using the GUI app, I close the app on the background and re-run the GUI app, the android device reconnects with the target paired device. This is the reason why I want to close the application on back press.

  • Is there a code to disconnect bluetooth on backpress temporarily. Maybe this could work.

  • @myrds===

    ok, now i understand; in this case, yes, its easy, you have to disconnect bluetooth in the onPause() method.

  • Can you post the code that I could use?

  • I tried the onPause(); it even affected the home button. So 2 problems, were gained, home button and onBackpressed.

  • edited May 2018

    @myrds===

    without knowing how you have created your blueTooth conn. it's difficult to answer...Yet, supposing that you have a broadcastReceiver running (called eg myDiscoverer) you have to code something like that::

          public void onPause(){
                    super.onPause();
    
                    if(myDiscoverer !=null){
                    getActivity().unregisterReceiver(myDiscoverer);
                    println("je désenregistre");
                    myDiscoverer=null;
                    }else{
                      println("désenregistré");
                    }
    
                    }
    
  • @myrds===

    see the activity (or fragment) lifeCycle for android; on pause is called whenever your app (or some activity if you have many ones) goes in the background, so it s called either with the home button or with the back button.

  • My coding is the same when we fixed the P2 codes for P3 codes, I already tested the codes that you gave me and it seems that I already know what the problem is.

    When pressing the home button, the app does not disconnect the bluetooth connection that is why it runs the application in the background efficiently.

    While the Back button when pressed, disconnects the bluetooth in the system without having the paired device being disconnected, creating the Issue.

    Is there a way that in pressing backpress button will not disconnect the bluetooth from the system?

  • edited May 2018

    Or if it is not possible, can we close the app completely upon backbutton press? Like just closing the application from the background?

  • If I remove the backpressed code, what I don't understand why it runs the application differently for the home and backpressed button.

  • Is there a syntax wherein backpressed will have the same action with that of the homebutton?

  • edited May 2018

    @myrds===

    • i cannot seen any reason why back button could disable bluetooth "in the system" (and home button will not)

    • it s impossible to "close completely" (i.e "quit") with android; for that you have to uninstall the app. Only the system can destroy an app (for memory reasons or others)

    • put your complete code as it is now (and dont forget onPause, on stop() && on resume())

    • there is no way to change the back button to home button: it does its job: back in the stack.

  • If you take a look at our discussion when we were converting P2 codes to P3 codes, that was the same issue before after we were able to make the codes work. And by that time I used System.exit(0), because of the existing problem.

  • @myrds===

    can you peut the code you are using now? - In order to be sure: everything is ok except that you want that when the back button is fired by the user bluetooth receiver continues to run?

  • edited May 2018

    I forgot how to put the codes, nevermind anyway. Thanks for the help. I think it is an issue in the processing version, wherein the issues keeps occurring affecting the performance of the codes that worked in previous versions.

  • I forgot how to put the codes, but the issues started on the indicated codes, for there were a lot of changes done after changing codes to adapt for P3. I am not hoping much for a solution anymore, but just in case, you would see the error.

    // *** For Bluetooth Features *** // public class myOwnBroadcastReceiver extends BroadcastReceiver { ConnectToBluetooth connectBT;

    @Override public void onReceive(Context context, Intent intent) { String action=intent.getAction();

    if(BluetoothDevice.ACTION_FOUND.equals(action)){ String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME); BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); foundDevice=true;

    if(discoveredDeviceName.equals("HMSoft")) {//name of device ToastMaster("Connecting you Now !!!"); connectBT = new ConnectToBluetooth(discoveredDevice); new Thread(connectBT).start();

    } else { ToastMaster("Please Turn on Target Device"); ToastMaster("Please Turn on Target Device"); ToastMaster("Please Turn on Target Device"); ToastMaster("Please Turn on Target Device"); ToastMaster("Please Turn on Target Device"); } }

    if(BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)){ ToastMaster("Already CONNECTED with Target Device"); while(scSocket==null){ } BTisConnected=true; if(scSocket!=null){ sendReceiveBT = new SendReceiveBytes(scSocket); new Thread(sendReceiveBT).start(); String red = "r"; byte[] myByte = stringToBytesUTFCustom(red); sendReceiveBT.write(myByte); } } } }

    // *** for Communication *** // public static byte[] stringToBytesUTFCustom(String str) { char[] buffer = str.toCharArray(); byte[] b = new byte [buffer.length << 1]; for (int i = 0; i < buffer.length; i++) { int bpos = i << 1; b[bpos] = (byte) ((buffer[i]&0xFF00)>>8); b[bpos + 1] =(byte) (buffer[i]&0x00FF); } return b; }

    ////////////////////////////////////////////////////////////////////////////////////////////// public void onBackPressed() { System.exit(0); } ////////////////////////////////////////////////////////////////////////////////////////////

    public class ConnectToBluetooth implements Runnable{ private BluetoothDevice btShield; private BluetoothSocket mySocket = null; private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    public ConnectToBluetooth(BluetoothDevice bluetoothShield) { btShield = bluetoothShield;

    try{ mySocket = btShield.createRfcommSocketToServiceRecord(uuid); } catch(IOException createSocketException){ Log.e("ConnectToBluetooth", "Error with Socket"); } }

    public void run() { bluetooth.cancelDiscovery();

    try{ mySocket.connect(); scSocket=mySocket; } catch (IOException connectException){ Log.e("ConnectToBluetooth", "Error with Socket Connection");

    try{ mySocket.close(); } catch(IOException closeException){ } return; } }

    public BluetoothSocket getSocket() { return mySocket; }

    public void cancel() { try { mySocket.close(); } catch (IOException e) { } } }

    // *** For GUI Communication *** // private class SendReceiveBytes implements Runnable { private BluetoothSocket btSocket; private InputStream btInputStream = null; private OutputStream btOutputStream = null; String TAG = "SendReceiveBytes"; public SendReceiveBytes(BluetoothSocket socket) { btSocket = socket; try { btInputStream = btSocket.getInputStream(); btOutputStream = btSocket.getOutputStream(); } catch (IOException streamError) { Log.e (TAG, "Error when getting input or output Stream"); } }

    public void run () { byte[] buffer = new byte [1024]; int bytes; while (true) { try { bytes = btInputStream.read(buffer); mHandler.obtainMessage (MESSAGE_READ, bytes, -1, buffer) .sendToTarget(); } catch (IOException e) { Log.e(TAG, "Error reading from btInputStream"); break; } } }

    public void write(byte[] bytes) {
    try { btOutputStream.write(bytes); } catch (IOException e) { Log.e(TAG, "Error when writing to btOutputStream"); } }

    public void cancel() { try { btSocket.close(); } catch (IOException e) { Log.e(TAG, "Error when closing the btSocket"); } } }

    void ToastMaster(String textToDisplay) { Toast myMessage = Toast.makeText(this.getActivity().getApplicationContext(), textToDisplay, Toast.LENGTH_LONG); myMessage.setGravity(Gravity.CENTER, 0, 0); myMessage.show(); }

  • I've been doing tests, and I thought of a solution. Indicated are the following observations.

    (1)Pressing the "background apps button" and the "home button" places the application on the background without disconnecting the bluetooth connection with the target device.

    (2)Pressing the "back button" places the application on the background disconnecting the bluetooth connection with the target device. A function placing the application onPause.

    The problem occurs when the back button is pressed due to the reason that the app disconnects the bluetooth but the target device does not disconnect its connection unless the app completely closes, which only can be done manually when accessing the application on the "backround applications" and closing it there.

    To efficiently reconnect the bluetooth connection of the app and the target device, the application should be completely closed, to also disconnect the bluetooth with the target device, but unfortunately, it is not possible. This makes "System.exit(0);" and "this.getActivity().finish();" not applicable. Also I tried removing the onBackpressed codes, and it works on (1) and (2) on default.

    Is there a way to do the other way around since it works on (1) and (2) on default. That onBackpressed, we avoid the application from disconnecting bluetooth connection?

    The truth is I already done everything I could, and I already want to give up. The only option that is left is how would I be able to work on the Bakpress button wothout disconnecting the bluetooth connection like the onPause.

  • edited May 2018

    I've just finished doing test doing "public void onPause, onStop, onResume and onStart" and also considered using "this.getActivity()" and System.exit(0);".

    The result are the following:

    (1) Based on the test, using "onPause" and "onStop" works. Also "System.exit(0);" should be used. It disconnects the bluetooth connection of both the application and the target device.

    (2) It keeps the application in the background and reconnects bluetooth connection with target paired device when re-accessed.

    But there is only one issue. When accessing app in the background, when displayed using the background applications button, the application does not respond on the first tap and displays or opens a different app. But reconnects on the second tap when app is re-accessed again.

    No major issue though, but unable to access the application on the first tap is not a good quality. The issue only arises when the background application is pressed, but no issues with the home and back button.

  • I just don't understand that if it worked with "onPause()" and "onStop()", why did it not work with "onBackPressed"?

  • edited May 2018

    Just an update guys for processing 3.3.7 android mode, please correct me if I am wrong, I think that the upgraded version of processing does not respond to codes using "public void onHomePressed()" and "public void onBackPressed()" syntax, that is why System.exit(0), did not activate using the codes for home and back. Though it works with "public void onPause()" and "public void onStop()". Am I not updated for the new syntax to run for processing 3.3.7 or it really does not really work at version 3.3.7. The app when installed, only runs on default Home, Back and Backround app buttons.

  • While doing research, I discovered that onBackPressed runs on an activity but not detected as an error that is why it does not run within the application. Is there a way wherein we can run onBackPressed in a fragment?

  • Answer ✓

    @myrds===

    that is not a 3XX problem; that is android. In order to be simple (& you can test each point):

    • When the user hits home button the activity goes in background without being killed except when the system decides it; if at this moment you are in an activity B, when the app resumes it restarts at the same activity. Think to a window or an app opened but not visible to the user, for a laptop. If for example you have a broadcast receiver or service registered it continues to run and you have probably (battery drain) to unregister it,in onPause() or (better) onStop() except in some cases (some service, an alarm with a pending intent: you app will do something each 25° day of the month at 12h: but the 24 other days it is sleeping).

    • When the user hits the back button that is not the case: if you are in an activity B, usually (see the last point) it kills it in the backStack and goes to activity A; all processes in B are stopped. It's like calling finish() on the activity B.

    • OnPause(), onStop() and so on are moments in the lifeCycle called one after the other; they are called in any case either when you hit the back button or the home one; that explains why overriding them affects the twos.

    • You can override back and/or home (of course you cannot "kill" them: the user is not your prisonner). Usually you do that to save some results or data or to open dialog window. Then using finish() in this case acts differently for the twos; it has not any effect with the Back one because this one calls finish() by itself (on the B Activity); with the Home one it kills all foregoing processes and on re-launch it restarts at the main activity.

    • Special case 1: you want to "disable" the back button; you are in C (from A to B) and you dont want to go to B nor A when back is pressed. In this case you have to destroy the whole backStack which is done adding "noHistory" to the Manifest.

    • Special case 2: you are in B and you want to preserve some results, as for example the list of all phones present with blue tooth activated, list you have got from the receiver; if back is pressed this list disappears (finish is called); in this case you can try to override onBackPressed with moveToTaskBack(true).

    • General cases for home && back: dont rely on them for your app especially the Home Button for security reasons:

    • This key is handled by the framework and is never delivered to applications. */ public static final int KEYCODE_HOME = 3; (more details here, line93: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/view/KeyEvent.java
  • Answer ✓

    Just to inform you, package on processing 3.3.7 is recognized as an error so I could not use the Keycode you sent me.

    But based on your inputs, with research and experimentation, indicated are the following details. (Please correct me if I am wrong).

    (1) I needed to use the System.exit(0); due to the reason that it is the only tested way I used to disconnect the target device with the app via bluetooth. When I don't use the indicated code, the app disconnects with the process but target device does not disconnect, creating an inefficiency in accessing app when placed on the background, which only happens when the back button is pressed.

    (2) onBackPressed(); onHomePressed(); is not read in processing 3.3.7. I think that the reason to this is that, onBackPressed and onHomePressed runs in an activity and not in a fragment. And P3.3.7 executes commands in a fragment

    (2) onStop(); onPause(); are affected by all buttons, that is why running System.exit(0); affected all buttons making all of the them disconnect application with the target device.

    (3)onStop(); onPause(); when used in running System.exit(0); affects the app background button, giving it a minor inefficiency, wherein when the button is pressed if it is the only app on the background, there is a situation wherein you need to re-access the application twice.

    (4) Based on my observation, pressing the backbutton destroys the app before it places it on the background, making the application disconnect without making the target device disconnect bluetooth connection. So due to this instead on focusing codes using onBackpress();, I used on onDestroy(); because it is not affect by the app backround button and homebutton. So applying system.exit(0); onDestroy, is just like executing the exit upon back button press.

    So tested and finalized, due to the reason that the application has no more issues when pressing the 3 buttons, I used the indicated code below in exchange for the code that I used in this thread.

    public void onDestroy(){ System.exit(0); }

    These is a shared effort, so I will just indicate it as answered from akenaton's last response. Thank you.

Sign In or Register to comment.