如何清除android应用程序

时间:2017-02-16 17:40:02

标签: java android bluetooth

我在从谷歌获取大量代码后创建了一个应用程序。将它们放在一起后,应用程序似乎运行得很安静。当我启动应用程序时,它请求蓝牙访问。提供后,它会显示可用的蓝牙连接列表。单击时,它连接到Arduino板(HC-05模块)并发送命令。到目前为止,一切都很好。

现在,当我使用Back键关闭应用程序时,应用程序仍然保持连接打开。在Arduino上,While(Serial1.available)返回true。

当我使用断开连接按钮断开连接时,它会关闭连接并再次连接到电路板不会发送任何命令,只是连接状态已连接。

为了使它工作,我必须使用android studio重新安装应用程序,然后打开连接,它完美地工作。

我的怀疑是:在关闭申请之前是否有必须清除的东西?由于应用程序使用片段,我不知道如何清除所有缓存,堆栈或其他任何东西。我已添加以下代码进行检查。

请帮助。

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();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

onStop()

中执行您的代码

请参阅The Activity Lifecycle

另见question