简体   繁体   中英

How to clear android application on close

I have created an application after taking a lot of code from google. After putting them all together, the application seems to be running quiet well. When I start the application, it request for bluetooth access. Once provided, it show a list of bluetooth connections available. When clicked, it connects to an Arduino board (HC-05 Module) and sends commands. Everything is fine till now.

Now, when I close the application using Back key, the application still keeps the connection open. On Arduino, While(Serial1.available) returns true.

When I disconnect using the disconnect button, it closes the connection and again connecting to the board does not send any commands, but just that the connection status is connected.

To make it work, I have to reinstall the application using android studio and then open the connection and it works perfectly.

My doubts are: Is there something that has to be cleared before closing the application? Since the application uses fragments, I have no idea how to clear all cache, or stack or anything else. I have added the code below to check.

Kindly help.

public class MainActivityFragment extends Fragment {

    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private static BluetoothAdapter mAdapter = null;
    private static OutputStream outStream = null;
    private int message = 0;
    private int aButton = 1;
    private int bButton = 1;
    private int cButton = 1;
    private int dButton = 1;
    private int eButton = 1;
    private int fButton = 1;
    private int gyButton = 0;
    private float xcoord = 0;
    private float ycoord = 0;

    private int f1;
    private int s2;
    private int t3;
    private int f4;
    private int CS;

    private int case_ = 0;
    private int xPower = 0; // processed x-y power
    private int yPower = 0;
    private float initX = 0; // initial touch position
    private float initY = 0;
    private float origX = 0; // joystick button locations
    private float origY = 0;
    private long data_ = 0;

    private double joyPower = 0;
    private double joyAngle = 0;

    private static BluetoothSocket mSocket = null;
    private static Timer timer;
    private final Handler handler = new Handler();
    private static BluetoothDevice device;
    private ImageView btButton;
    private ImageView disconnectButton;
    private static TimerTask sendMessage;
    private static boolean isSchedule = false;

    public MainActivityFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        final TextView serO = (TextView) rootView.findViewById(R.id.serialOut);
        final Vibrator vibr = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);

        timer = new Timer();
        sendMessage = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (outStream != null) {

                            try {
                                message = 100;
                                outStream.write(message);
                            } catch (Exception e) {
                            }
                        }
                    }
                });
            }
        };
        // Get Bluetooth adapter
        mAdapter = BluetoothAdapter.getDefaultAdapter();
        checkBTState();

        // Set aButton = 1 when A is pressed
        final ImageButton a = (ImageButton) rootView.findViewById(R.id.a);
        //Button a = (Button) rootView.findViewById(R.id.a);
        a.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        aButton = 0;
                        //Toast.makeText(getActivity().getBaseContext(), "A Action Down" + aButton, Toast.LENGTH_LONG).show();
                        Vibrator vibr = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
                        vibr.vibrate(50);
                        a.setImageResource(R.drawable.white_bg);
                        return true;
                    case MotionEvent.ACTION_UP:
                        aButton = 1;
                        a.setImageResource(R.drawable.trans_bg);
                        return true;
                }
                return false;
            }
        });

    private void checkBTState() {
        if (mAdapter == null) {
            Toast.makeText(getActivity().getApplicationContext(), "Bluetooth Not Supported", Toast.LENGTH_SHORT).show();
        } else {
            if (!mAdapter.isEnabled()) {
                startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 1);
            }
        }
    }

    private static BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
        if (Build.VERSION.SDK_INT >= 10) {
            try {
                final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[]{UUID.class});
                return (BluetoothSocket) m.invoke(device, MY_UUID);
            } catch (Exception e) {

            }
        }
        return device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
    }

    public static void connect(String address, Context context) {
        try {
            device = mAdapter.getRemoteDevice(address);
        } catch (Exception e) {
            Toast.makeText(context, "Invalid Address", Toast.LENGTH_LONG).show();
        }

        try {
            mSocket = createBluetoothSocket(device);
        } catch (Exception e) {

        }

        mAdapter.cancelDiscovery();

        try {
            // try connecting to socket
            mSocket.connect();
        } catch (Exception e) {
            try {
                mSocket.close();
            } catch (Exception e1) {
                Log.e("E4", "Socket Connection Exception");
            }
        }

        try {
            outStream = mSocket.getOutputStream();
            if (!isSchedule) {
                timer.schedule(sendMessage, 0, 500);
                isSchedule = true;
            } else {
                Log.e("Timer", "Timer already schedule");
            }
            Toast.makeText(context, "Connection Established", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
        }
    }


    public static boolean isConnected() {
        // Check if the phone has already connected to bluetooth device
        return device != null;
    }

    private void disconnectDevice() {
        if (device != null) {
            device = null;

            try {
                outStream.close();
            } catch (Exception e) {
            }
            outStream = null;
            mSocket = null;
            Toast.makeText(getActivity(), "Bluetooth Device Disconnected", Toast.LENGTH_SHORT).show();
        }
    }
}

Do your code in onStop()

See The Activity Lifecycle

Also see this question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM