【问题标题】:How to clear android application on close如何在关闭时清除android应用程序
【发布时间】:2017-02-16 17:40:02
【问题描述】:

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

现在,当我使用返回键关闭应用程序时,应用程序仍然保持连接打开。在 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();
        }
    }
}

【问题讨论】:

    标签: java android bluetooth


    【解决方案1】:

    onStop()做你的代码

    The Activity Lifecycle

    另见question

    【讨论】:

    • 是的。我确实检查了活动生命周期的链接。但正如我之前确认的那样,我不知道该放什么,因为我所做的只是在没有 android 背景知识的情况下弄乱了代码。顺便说一句,我应该在这段代码中的哪里添加 onStop() ?也不知道Java。我认为这是我可以通过将不同的代码组合在一起来学习的一种方法。如果您能提供一种添加方法的帮助,那将很有帮助。
    • onStop() 是您可以在 Activity 中覆盖的方法,就像覆盖 onCreate 一样
    • 你是什么意思:I do not know what to put where
    • 我想知道在哪里添加代码。如果要添加为覆盖,我的问题是:我需要显式调用该函数吗?由于我来自 C 背景,我认为应该调用任何函数才能使其工作。所以,我的问题是,我应该添加覆盖代码并在活动中的某个地方调用它吗?像 onStop();?
    • @Praveen 当您的活动达到此周期时,将自动调用活动生命周期方法。我的意思是,如果您在 Activity 中重写了 onStop() 方法并在其中添加了一些代码,那么当此 Activity 到达它即将停止的周期时,onStop() 将自动执行,并且您在其中的代码将起作用。跨度>
    猜你喜欢
    • 1970-01-01
    • 2013-06-09
    • 2012-03-23
    • 2022-01-09
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    相关资源
    最近更新 更多