android7.0开启蓝牙搜索设备

package com.ansen.massage.chair.activity;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ansen.massage.chair.R;
import com.ansen.massage.chair.adapter.BluetoothListAdapter;
import com.ansen.massage.chair.base.MCBaseActivity;
import com.ansen.massage.chair.base.Presenter;
import com.ansen.massage.chair.form.BluetoothDeviceForm;
import com.ansen.massage.chair.iview.IBluetoothListView;
import com.ansen.massage.chair.presenter.BluetoothListPresenter;
import com.ansen.massage.chair.util.CacheUtils;
import com.ansen.massage.chair.util.Constant;
import com.ansen.massage.chair.util.Utils;

/**
 * Created by garbage ansen
 * Create Time 2017-04-19
 */
public class BluetoothListActivity extends MCBaseActivity implements IBluetoothListView {
    private String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
    private final int PERMS_REQUEST_CODE = 200;

    private final int BLUETOOTH_DISCOVERABLE_DURATION = 250;
    private final int REQUEST_CODE_BLUETOOTH_ON = 1313;

    private BluetoothListPresenter presenter;
    private ListView listView;
    private BluetoothListAdapter adapter;

    private TextView tvSearchState;
    private BluetoothAdapter mBtAdapter;
    private TextView tv_massage_chair;
    private String language;
    private TextView tv_device;
    private Button bt_refresh;

    @Override
    protected void onCreateContent(Bundle savedInstanceState) {
        super.onCreateContent(savedInstanceState);
        setContentView(R.layout.activity_bluetooth_list);

        language = CacheUtils.getString(this, CacheUtils.FILE_NAME, "10");
        tv_massage_chair = (TextView) findViewById(R.id.tv_massage_chair);
        tv_device = (TextView) findViewById(R.id.tv_device);
        bt_refresh = (Button) findViewById(R.id.bt_refresh);
        bt_refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchDevice();
            }
        });
        switch ((Utils.hexString2Bytes(language)[0] & 0xF0) >> 4) {
            case Constant.LANGUAGE_CHINESE:
                tv_massage_chair.setText("按摩椅APP");
                tv_device.setText("设备列表");
                bt_refresh.setText("重新扫描");
                break;
            case Constant.LANGUAGE_ENGLISH:
                tv_massage_chair.setText("Massage chair APP");
                tv_device.setText("Device list");
                bt_refresh.setText("Searching again");
                break;
            case Constant.LANGUAGE_KOREAN:
                tv_massage_chair.setText("안마의자 APP");
                tv_device.setText("설비목록");
                bt_refresh.setText("재검색");
                break;
        }
        tvSearchState = (TextView) findViewById(R.id.tv_search_state);

        listView = (ListView) findViewById(R.id.listview);

        listView.setAdapter(adapter = new BluetoothListAdapter(this, presenter));

        listView.setOnItemClickListener(onItemClickListener);

        mBtAdapter = BluetoothAdapter.getDefaultAdapter();

        if (System.currentTimeMillis() > 1514563200000L) {
//            Toast.makeText(this, "您的当前版本已过期,请下载更新", Toast.LENGTH_LONG).show();
            new AlertDialog.Builder(BluetoothListActivity.this)
                    .setTitle("注意")
                    .setMessage("当前版本已过期,请下载更新")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent();
                            intent.setAction("android.intent.action.VIEW");
                            Uri content_url = Uri.parse("http://116.62.218.136:10000/%E6%8C%89%E6%91%A9%E6%A4%85/%E6%8C%89%E6%91%A9%E6%A4%85.apk");
                            intent.setData(content_url);
                            startActivity(intent);
                            finish();
                        }
                    })
                    .setCancelable(false)
                    .show();

        } else {
            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            this.registerReceiver(mReceiver, filter);
            // Register for broadcasts when discovery has finished
            filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
            this.registerReceiver(mReceiver, filter);
        }

        if (mBtAdapter == null) {//手机不支持蓝牙
            showToast("您的手机不支持蓝牙");
            return;//手机不支持蓝牙就啥也不用干了,关电脑睡觉去吧
        }
        if (!mBtAdapter.isEnabled()) {// 如果蓝牙还没有打开
            //请求打开 Bluetooth
            Intent requestBluetoothOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            //设置 Bluetooth 设备可以被其它 Bluetooth 设备扫描到
            requestBluetoothOn.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            //设置 Bluetooth 设备可见时间
            requestBluetoothOn.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, BLUETOOTH_DISCOVERABLE_DURATION);
            //请求开启 Bluetooth
            this.startActivityForResult(requestBluetoothOn, REQUEST_CODE_BLUETOOTH_ON);
            return;
        }

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {//Android 6.0以上版本需要获取权限
            requestPermissions(perms, PERMS_REQUEST_CODE);//请求权限
        } else {
            searchDevice();//搜索任务
        }
    }

    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            BluetoothDevice bluetoothDevice = presenter.getItem(position);
            BluetoothDeviceForm bluetoothDeviceForm = new BluetoothDeviceForm(bluetoothDevice.getAddress());
            goTo(MainActivity.class, bluetoothDeviceForm);

            finish();
        }
    };

    @Override
    public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults) {
        switch (permsRequestCode) {
            case PERMS_REQUEST_CODE:
                boolean storageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                if (storageAccepted) {
                    searchDevice();//搜索任务
                } else {
                    Log.i("MainActivity", "没有权限操作这个请求");
                }
                break;
        }
    }

    private void searchDevice() {
        if (mBtAdapter.isDiscovering()) {
            mBtAdapter.cancelDiscovery();
        }
        Log.i("BluetoothListActivity", "扫描蓝牙中...");
        mBtAdapter.startDiscovery();

        presenter.getListInfo().clear();
        bt_refresh.setVisibility(View.INVISIBLE);
        switch ((Utils.hexString2Bytes(language)[0] & 0xF0) >> 4) {
            case Constant.LANGUAGE_CHINESE:
                tvSearchState.setText("扫描蓝牙中...");
                break;
            case Constant.LANGUAGE_ENGLISH:
                tvSearchState.setText("Searching for bluetooth...");
                break;
            case Constant.LANGUAGE_KOREAN:
                tvSearchState.setText("블루투스검색중...");
                break;
        }
    }

    @Override
    protected Presenter getPresenter() {
        if (presenter == null) {
            presenter = new BluetoothListPresenter(this);
        }
        return presenter;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        Log.i("ansen","onDestroy");
        if (mBtAdapter != null) {
            mBtAdapter.cancelDiscovery();
        }
        this.unregisterReceiver(mReceiver);
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {//搜索到蓝牙设备
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Log.i("MainActivity", "device name:" + device.getName() + " BondState:" + device.getBondState());
//                && device.getName().toUpperCase().contains("MASSAGE")
//                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                presenter.addBluetoothDevice(device);
                adapter.notifyDataSetChanged();
//                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {//搜索完成广播
                bt_refresh.setVisibility(View.VISIBLE);
                switch ((Utils.hexString2Bytes(language)[0] & 0xF0) >> 4) {
                    case Constant.LANGUAGE_CHINESE:
                        bt_refresh.setText("重新扫描");
                        tvSearchState.setText("扫描蓝牙完成");
                        break;
                    case Constant.LANGUAGE_ENGLISH:
                        bt_refresh.setText("Searching again");
                        tvSearchState.setText("Scanning bluetooth");
                        break;
                    case Constant.LANGUAGE_KOREAN:
                        bt_refresh.setText("재검색");
                        tvSearchState.setText("청아를 스캔 하여 완성하다");
                        break;
                }
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i("ansen", "requestCode:" + requestCode + " resultCode:" + resultCode);
        if (requestCode == REQUEST_CODE_BLUETOOTH_ON && resultCode == 250) {//用户选择开启 Bluetooth
            Log.i("ansen", "开启蓝牙成功");
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {//Android 6.0以上版本需要获取权限
                requestPermissions(perms, PERMS_REQUEST_CODE);//请求权限
            } else {
                searchDevice();//搜索任务
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,607评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,047评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,496评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,405评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,400评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,479评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,883评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,535评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,743评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,544评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,612评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,309评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,881评论 3 306
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,891评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,136评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,783评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,316评论 2 342

推荐阅读更多精彩内容