自省自律自尊
2022-04-28 16:20
采纳率: 66.7%
浏览 15

这是andriod蓝牙项目开发中的问题,但也不是蓝牙的问题,很奇怪

img

这里本来应该是要进去的,但是它并没有跳进去,直接跳过了,我换了contains()也是一样的效果

img

跳到了这里,这个我就不懂了,有些什么原因嘛?
下面是源码,请大家帮我看看

package com.example.wisdomclassroom;

import static androidx.constraintlayout.motion.utils.Oscillator.TAG;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wisdomclassroom.controller.BlueToothController;
import com.example.wisdomclassroom.utils.ToastUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class InClassActivity extends AppCompatActivity {

    private Button mBtnClassOver;
    private Button mBtClassIn;
    private TextView mTvConnect2;
    private ListView mLvConnect3;
    private final int PERMISSION_REQUEST_COARSE_LOCATION = 0xb01;
    //学生数组
    private ArrayList<String> Students = new ArrayList<>();
    // 弹窗
    private Toast mToast;
    private static final int REQ_PERMISSION_CODE = 1;
    // 蓝牙权限列表
    public ArrayList<String> requestList = new ArrayList<>();
    // 实例化蓝牙控制器
    public BlueToothController btController = new BlueToothController();
    // 搜索蓝牙广播
    private IntentFilter foundFilter;
    //
    public ArrayAdapter<String> adapter;
    //定义一个列表,存蓝牙设备名称,用于显示。
    public ArrayList<String> deviceName = new ArrayList<>();

    private ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Log.e(TAG, "run方法里");
            // 注册广播接收器
            // 接收蓝牙发现
            foundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            foundFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
            foundFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
            registerReceiver(bluetoothReceiver, foundFilter);
            btController.findDevice();
        }
    };

    // 搜索蓝牙广播
    private BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) throws SecurityException {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String name = device.getName();
                if (name != null && !deviceName.contains(name)) {
                    deviceName.add(name);//将搜索到的蓝牙名称添加到列表。
                    adapter.notifyDataSetChanged();//更新
//                    for (String student : Students) {
//                        if (name.equals(student)) {
//                            deviceName.add(name);//将搜索到的蓝牙名称添加到列表。
//                            adapter.notifyDataSetChanged();//更新
//                        }
//                    }
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                ToastUtil.showMsg(InClassActivity.this, "搜索结束");
                deviceName.clear();
                adapter.clear();
                unregisterReceiver(this);
            } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                ToastUtil.showMsg(InClassActivity.this, "搜索开始");
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_in_class);

        mBtnClassOver = findViewById(R.id.btn_classOver);
        mBtClassIn = findViewById(R.id.bt_classIn);
        mTvConnect2 = findViewById(R.id.tv_connect2);
        mLvConnect3 = findViewById(R.id.lv_connect3);

        if (Build.VERSION.SDK_INT >= 6.0) {
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
            }
        }
//      获取本班的所有学生
        getStudentsName();
//      listView遍历
        adapter = new ArrayAdapter(InClassActivity.this, android.R.layout.simple_list_item_1, deviceName);
        mLvConnect3.setAdapter(adapter);

        mBtClassIn.setOnClickListener(this::onClickClassIn);
        mBtnClassOver.setOnClickListener(this::onClickClassOver);
    }

    /**
     * 获取本班的所有学生
     */
    private void getStudentsName() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String url = "http://192.168.0.101:8082/Student/getStudentsName?tName=" + getIntent().getStringExtra("tName");
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(url).get().build();
                Call call = client.newCall(request);
                try {
                    Response response = call.execute();
                    String body = response.body().string();
                    String[] split = body.split("\\[")[1].split("\\]")[0].split(",");
                    Students = new ArrayList<>(Arrays.asList(split));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 上课
     */
    private void onClickClassIn(View v) {

        // 获取蓝牙权限
        getPerMission();
        // 判断是否支持蓝牙
        if (btController.isSupportBlueTooth() != true) {
            ToastUtil.showMsg(this, "当前设备不支持蓝牙");
            Intent intent = new Intent(InClassActivity.this, InClassActivity.class);
            startActivity(intent);
        }
        // 打开蓝牙
        btController.turnOnBlueTooth(this, 1);
        //打开蓝牙可见
//        btController.enableVisibly(this);

        mBtClassIn.setVisibility(View.GONE);
        mTvConnect2.setVisibility(View.VISIBLE);
        mLvConnect3.setVisibility(View.VISIBLE);
//        //开启定时任务
        executorService.scheduleAtFixedRate(runnable, 0, 10, TimeUnit.SECONDS);

    }

    /**
     * 下课
     */
    private void onClickClassOver(View v) {
        executorService.shutdown();
        Log.e(TAG, "关闭定时任务");
        Intent intent = new Intent(InClassActivity.this, MenuActivity.class).putExtra("tName", getIntent().getStringExtra("tName"));
        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            ToastUtil.showMsg(this, "打开蓝牙成功");
        } else {
            ToastUtil.showMsg(this, "打开蓝牙失败");
        }
    }

    /**
     * 动态申请权限
     */
    public void getPerMission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            requestList.add(Manifest.permission.BLUETOOTH_SCAN);
            requestList.add(Manifest.permission.BLUETOOTH_ADVERTISE);
            requestList.add(Manifest.permission.BLUETOOTH_CONNECT);
            requestList.add(Manifest.permission.ACCESS_FINE_LOCATION);
            requestList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            requestList.add(Manifest.permission.BLUETOOTH);
        }
        if (requestList.size() != 0) {
            ActivityCompat.requestPermissions(this, requestList.toArray(new String[0]), REQ_PERMISSION_CODE);
        }
    }

    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.i(TAG, "获取蓝牙权限成功");
                }
                return;
            }
        }
    }


}

1条回答 默认 最新

相关推荐 更多相似问题