Skip to content

Instantly share code, notes, and snippets.

@aaayushsingh
Created August 21, 2017 05:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaayushsingh/baf15cc0c0d04953885668920d7ea189 to your computer and use it in GitHub Desktop.
Save aaayushsingh/baf15cc0c0d04953885668920d7ea189 to your computer and use it in GitHub Desktop.
new, checks permissions
package com.sunflyelec.smartearphone.module.bluetooth.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.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.sunflyelec.smartearphone.R;
import com.sunflyelec.smartearphone.common.util.handler.OnCancelListener;
import com.sunflyelec.smartearphone.common.util.handler.OnSuccessListener;
import com.sunflyelec.smartearphone.common.util.log.Logger;
import com.sunflyelec.smartearphone.config.AppConfig;
import com.sunflyelec.smartearphone.datacenter.BluetoothHelper;
import com.sunflyelec.smartearphone.datacenter.SettingCache;
import com.sunflyelec.smartearphone.module.BaseActivity;
import com.sunflyelec.smartearphone.module.MainPageActivity;
import com.sunflyelec.smartearphone.module.bluetooth.adapters.FindBluetoothDeviceAdapter;
import com.sunflyelec.smartearphone.module.bluetooth.biz.BluetoothDeviceBiz;
import com.sunflyelec.smartearphone.module.bluetooth.services.BluetoothLeService;
import com.sunflyelec.smartearphone.module.login.activity.LoginActivity;
import com.sunflyelec.smartearphone.module.login.activity.permss;
import java.lang.reflect.Constructor;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 蓝牙搜索
*
* Created by Administrator on 2016/3/24.
*/
public class BluetoothLEFindActivity extends BaseActivity implements View.OnClickListener{
public static final String SEARCH_RIGHT_NOW = "search_right_now";
public static final String IS_SKIP_LOGIN = "IS_SKIP_LOGIN";
// Debugging
private static final String TAG = "BluetoothSPP";
private static final boolean D = true;
private TextView mBluetoothSkipTv;
private ListView mDeviceListLv;
private TextView mBluetoothResearchTv;
private TextView mMainTitleTv;
private TextView mMainTipOneTv;
private TextView mMainTipTwoTv;
private int allowreconnecttimes = 3;
private int reconnecttimes = 0;
private boolean mScanning;
// 10秒后停止查找搜索.
private static final long SCAN_PERIOD = 10000;
// public static BluetoothDevice mCurrentBluetoothDevice;
private SimpleDateFormat sdf;
private BluetoothDevice mConnectedBluetoothDevice;
// Member fields
private BluetoothAdapter mBtAdapter;
private android.bluetooth.le.BluetoothLeScanner mBleScanner;
private FindBluetoothDeviceAdapter mFindBluetoothDeviceAdapter;
private List<BluetoothDevice> mFoundDevices;
private Set<BluetoothDevice> mPairedDevices;
private Map<String,BluetoothDevice> mBluetoothFilter;
public static List<String> mIgnoreDevice = new ArrayList<String>();
private boolean isDestroy;
private String address;//当前连接蓝牙地址
private boolean isSkipLogin;
private Handler freshHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
mFindBluetoothDeviceAdapter.notifyDataSetChanged();
}
};
// The BroadcastReceiver that listens for discovered devices and
// changes the title when discovery is finished
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
switch (action){
case BluetoothLeService.ACTION_GATT_CONNECTED://onConnectionStateChange BluetoothProfile.STATE_CONNECTED
Logger.debug("GATT已连接", "");
//缓存最近连接的蓝牙设备地址
BluetoothHelper.cacheLastBluetoothDeviceAddress(address);
BluetoothDeviceBiz.getInstance().setmDEVICE_VERSION("");
SettingCache.openAutoConnect();
break ;
case BluetoothLeService.ACTION_GATT_DISCONNECTED://onConnectionStateChange BluetoothProfile.STATE_DISCONNECTED
Logger.debug("GATT已取消连接","");
break ;
case BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED://onServicesDiscovered
Logger.debug("GATT服务已发现", "");
BluetoothDeviceBiz.getInstance().getBluetoothLeService().initBluetoothGattCharacteristic();
BluetoothDeviceBiz.getInstance().startGetMACDEV();
startActivity(getNextIntent());
finish();
/* connecting(new OnSuccessListener() {
@Override
public void success() {
startActivity(getNextIntent());
finish();
}
});*/
break ;
}
}
};
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// mLeDeviceListAdapter.addDevice(device);
// mLeDeviceListAdapter.notifyDataSetChanged();
Log.i("BroadcastReceiver","搜索到蓝牙设备:"+device.getName()+":"+device.getAddress());
if(!"Cyclist-HR".equals(device.getName())){
return;
}
if (!device.getAddress().equals(BluetoothHelper.getLastBluetoothDeviceAddress())) {
if (!mBluetoothFilter.keySet().contains(device.getAddress())&&!mIgnoreDevice.contains(device.getAddress())&&!TextUtils.isEmpty(device.getName())) {
mBluetoothFilter.put(device.getAddress(), device);
mFoundDevices.add(device);
mFindBluetoothDeviceAdapter.notifyDataSetChanged();
}
}else{
if(SettingCache.isAutoConnect()&&!BluetoothDeviceBiz.getInstance().isBluetoothConnected()&&!TextUtils.isEmpty(BluetoothHelper.getLastBluetoothDeviceAddress())){
address = BluetoothHelper.getLastBluetoothDeviceAddress();
BluetoothDeviceBiz.getInstance().getBluetoothLeService().autoConnect(address);
}
}
}
});
}
};
/**
* 扫描BLE设备
* @param enable
*/
private void scanLeDevice(final boolean enable) {
if (enable) {
// Stops scanning after a pre-defined scan period.
freshHandler.postDelayed(new Runnable() {
@Override
public void run() {
mScanning = false;
mBtAdapter.stopLeScan(mLeScanCallback);
setProgressBarIndeterminateVisibility(false);
mBluetoothResearchTv.setVisibility(View.VISIBLE);
mFindBluetoothDeviceAdapter.notifyDataSetChanged();
Log.i("BroadcastReceiver", "搜索蓝牙结束");
// mBleScanner.stopScan(mLeScanCallback2);
// invalidateOptionsMenu();
}
}, SCAN_PERIOD);
mScanning = true;
// mBleScanner.startScan(mLeScanCallback2);
mBtAdapter.startLeScan(mLeScanCallback);
} else {
mScanning = false;
// mBleScanner.stopScan(mLeScanCallback2);
mBtAdapter.stopLeScan(mLeScanCallback);
setProgressBarIndeterminateVisibility(false);
mBluetoothResearchTv.setVisibility(View.VISIBLE);
mFindBluetoothDeviceAdapter.notifyDataSetChanged();
Log.i("BroadcastReceiver", "搜索蓝牙结束");
}
// invalidateOptionsMenu();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth_find);
// 检查当前手机是否支持ble 蓝牙,如果不支持退出程序
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.nosuportble_erorr, Toast.LENGTH_SHORT).show();
finish();
}
BluetoothDeviceBiz.getInstance().initBluetoothService(this);
// mBtAdapter = BluetoothAdapter.getDefaultAdapter();
// mBtAdapter = ((BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter();
// mBleScanner = mBtAdapter.getBluetoothLeScanner();
isSkipLogin = getIntent().getBooleanExtra(IS_SKIP_LOGIN,false);
mBluetoothSkipTv = (TextView)findViewById(R.id.bluetooth_skip_tv);
mBluetoothSkipTv.setOnClickListener(this);
mDeviceListLv = (ListView)findViewById(R.id.device_list_lv);
//初始化蓝牙适配器
mFoundDevices = new ArrayList<BluetoothDevice>();
mFindBluetoothDeviceAdapter = new FindBluetoothDeviceAdapter(this,mFoundDevices,this);
mDeviceListLv.setAdapter(mFindBluetoothDeviceAdapter);
mBluetoothResearchTv = (TextView)findViewById(R.id.bluetooth_research_tv);
mBluetoothResearchTv.setOnClickListener(this);
mMainTitleTv = (TextView)findViewById(R.id.main_title_tv);
mMainTitleTv.setText(getTitleFromDate());
mMainTipOneTv = (TextView)findViewById(R.id.main_tip_one_tv);
mMainTipTwoTv = (TextView)findViewById(R.id.main_tip_two_tv);
//Toast.makeText(this,"kuch hua?", Toast.LENGTH_SHORT).show();
//checkLocationPermission();
mBluetoothFilter = new HashMap<>();
mDeviceListLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Cancel discovery because it's costly and we're about to connect
if (mScanning)
scanLeDevice(false);
if (mFoundDevices.get(position).getBondState() != BluetoothDevice.BOND_BONDED || !BluetoothDeviceBiz.getInstance().isBluetoothConnected()) {
// BluetoothDeviceBiz.getInstance().getBluetoothLeService().disconnect();
BluetoothDevice device = mFoundDevices.get(position);
address = mFoundDevices.get(position).getAddress();
BluetoothDeviceBiz.getInstance().getBluetoothLeService().autoConnect(address);
} else {
startActivity(getNextIntent());
finish();
}
}
});
// if(BluetoothDeviceBiz.getInstance().getmBluetoothSPP()==null){
// initBluetoothSPP();
// }
String data = getIntent().getStringExtra(SEARCH_RIGHT_NOW);
//注册广播监听
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
filter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
filter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
// filter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
this.registerReceiver(mReceiver, filter);
if("Y".equals(data)){
autoFindDevice();
}else {
// getConnectBluetoothDevice();
new Handler().postDelayed(new Runnable() {
public void run() {
//execute the task
if (!BluetoothLEFindActivity.this.isDestroyed()) {
autoFindDevice();
}
}
}, 3000);
}
new Thread(new Runnable() {
@Override
public void run() {
while (!isDestroy){
freshHandler.sendEmptyMessage(0);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
/**
* 获取下一个Intent
* 未登录显示登录界面 已登录直接进入主界面
* @return
*/
private Intent getNextIntent(){
Intent mainPageIntent = new Intent();
if((AppConfig.LOGIN_USER!=null&&AppConfig.LOGIN_USER.isLogin())||isSkipLogin) {
mainPageIntent.setClass(BluetoothLEFindActivity.this, MainPageActivity.class);
}else{
mainPageIntent.setClass(BluetoothLEFindActivity.this, LoginActivity.class);
}
return mainPageIntent;
}
private String getTitleFromDate(){
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
if(hour>=3&&hour<12){
return getString(R.string.bluetoothfind_title_morning);
}else if(hour>=12&&hour<18){
return getString(R.string.bluetoothfind_title_afternoon);
}else{
return getString(R.string.bluetoothfind_title_evening);
}
}
/* private void initBluetoothSPP(){
BluetoothDeviceBiz.getInstance().setmBluetoothSPP(new BluetoothSPP(EarphoneApplication.getContent()));
BluetoothDeviceBiz.getInstance().getmBluetoothSPP().setBluetoothConnectionListener(new BluetoothSPP.BluetoothConnectionListener() {
@Override
public void onDeviceConnected(String name, String address) {
//延迟2s执行
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
connecting(null);
}
}, 2000);
//缓存最近连接的蓝牙设备地址
BluetoothHelper.cacheLastBluetoothDeviceAddress(address);
startActivity(getNextIntent());
finish();
*//*try {
ParcelUuid[] uuids = mFoundDevices.get(position).getUuids();
for (ParcelUuid pu : uuids) {
Log.i("uuid:", pu.getUuid().toString());
}
}catch (Exception e){}*//*
}
@Override
public void onDeviceDisconnected() {
mFindBluetoothDeviceAdapter.notifyDataSetChanged();
}
@Override
public void onDeviceConnectionFailed() {
// BluetoothDeviceBiz.getInstance().getmBluetoothSPP().mCurrentDevice = mConnectedBluetoothDevice;
CustomToast.showShortToast(BluetoothLEFindActivity.this, getString(R.string.connect_failed));
}
});
}*/
private void connecting(final OnSuccessListener onSuccessListener){
reconnecttimes++;
//
// BluetoothDeviceBiz.getInstance().getmBluetoothSPP().connectA2dp();
// BluetoothDeviceBiz.getInstance().getmBluetoothSPP().connectHeadset();
//查询设备信息
if(TextUtils.isEmpty(BluetoothDeviceBiz.getInstance().getmBLE_MAC()))
BluetoothDeviceBiz.getInstance().queryBluetoothMAC();
if(TextUtils.isEmpty(BluetoothDeviceBiz.getInstance().getmDEVICE_VERSION()))
BluetoothDeviceBiz.getInstance().queryDeviceVersion();
/*new Handler().postDelayed(new Runnable() {
@Override
public void run() {
BluetoothDeviceBiz.getInstance().queryDeviceVersion();
}
}, 500);*/
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (TextUtils.isEmpty(BluetoothDeviceBiz.getInstance().getmDEVICE_VERSION())||TextUtils.isEmpty(BluetoothDeviceBiz.getInstance().getmBLE_MAC())) {
if (reconnecttimes > allowreconnecttimes) {
ShowShortToast(getString(R.string.blooth_connect_error));
reconnecttimes = 0;
BluetoothDeviceBiz.getInstance().disconnect();
return;
}
connecting(onSuccessListener);
} else {
//启动心跳
BluetoothDeviceBiz.getInstance().startKeepHeartbeat();
BluetoothDeviceBiz.getInstance().resetHardDeviceStatus();
reconnecttimes = 0;
onSuccessListener.success();
}
}
}, 1000);
}
private void autoFindDevice(){
//变更显示
mMainTitleTv.setText(R.string.bluetooth_searching);
mMainTipOneTv.setText(R.string.bluetooth_search_one_tip);
mMainTipTwoTv.setText(R.string.bluetooth_search_two_tip);
// Get the local Bluetooth adapter
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
if(!mBtAdapter.isEnabled()){
mBtAdapter.enable();
}
// Register for broadcasts when a device is discovered
// 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);
Log.i("autoFindDevice","自动搜寻蓝牙设备");
doDiscovery();
}
/**
* 查找设置
*/
private void doDiscovery(){
Log.i("doDiscovery","开始搜索蓝牙设备");
mBluetoothResearchTv.setVisibility(View.GONE);
// Get a set of currently paired devices
//mPairedDevices = mBtAdapter.getBondedDevices();
// Remove all element from the list
mFoundDevices.clear();
mBluetoothFilter.clear();
if(mIgnoreDevice.size()>0){
for(String address : mIgnoreDevice){
System.out.println("忽略的设备:"+address);
mBluetoothFilter.put(address, null);
}
}
String lastAddress = BluetoothHelper.getLastBluetoothDeviceAddress();
if(!TextUtils.isEmpty(lastAddress)){
Class clazz = null;
BluetoothDevice last = null;
try {
//反射生成蓝牙设备状态
clazz = Class.forName(BluetoothDevice.class.getName());
Constructor c = clazz.getDeclaredConstructor(String.class);
c.setAccessible(true);
last = (BluetoothDevice)c.newInstance(lastAddress);
} catch (Exception e) {
e.printStackTrace();
}
if(!mIgnoreDevice.contains(lastAddress)){
mBluetoothFilter.put(lastAddress, null);
mFoundDevices.add(last);
}
mFindBluetoothDeviceAdapter.notifyDataSetChanged();
}
// If there are paired devices, add each one to the ArrayAdapter
// if (mPairedDevices.size() > 0) {
// for (BluetoothDevice device : mPairedDevices) {
// if(!mBluetoothFilter.keySet().contains(device.getAddress())) {
// mBluetoothFilter.put(device.getAddress(),device);
// mFoundDevices.add(device);
// mFindBluetoothDeviceAdapter.notifyDataSetChanged();
// }
// }
// }
// Turn on sub-title for new devices
// findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
// If we're already discovering, stop it
if (mScanning) {
scanLeDevice(false);
}
// Request discover from BluetoothAdapter
scanLeDevice(true);
}
public void onDestroy() {
super.onDestroy();
//mBluetoothSPP.stopService();
isDestroy = true;
// Register for broadcasts when a device is discovered
try {
this.unregisterReceiver(mReceiver);
}catch (Exception e){}
}
/* public void onStart() {
super.onStart();
if(!BluetoothDeviceBiz.getInstance().getmBluetoothSPP().isBluetoothEnabled()) {
BluetoothDeviceBiz.getInstance().getmBluetoothSPP().enable();
} else {
if(!BluetoothDeviceBiz.getInstance().getmBluetoothSPP().isServiceAvailable()) {
BluetoothDeviceBiz.getInstance().getmBluetoothSPP().setupService();
BluetoothDeviceBiz.getInstance().getmBluetoothSPP().startService(BluetoothState.DEVICE_ANDROID);
setup();
}
}
}*/
public void setup() {
/* Button btnSend = (Button)findViewById(R.id.send_btn);
btnSend.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
bt.send("Text", true);
}
});*/
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.bluetooth_skip_tv:
startActivity(getNextIntent());
finish();
break;
case R.id.bluetooth_research_tv:
doDiscovery();
break;
}
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
android.Manifest.permission. ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle("Permissions not granted!")
.setMessage("This app needs to access location to detect device, Please grant permission.")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(BluetoothLEFindActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.CAMERA,
Manifest.permission.RECORD_AUDIO,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.CALL_PHONE
},
MY_PERMISSIONS_REQUEST_LOCATION);
// ActivityCompat.requestPermissions(MainActivity.this,
// new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
// MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.CAMERA,
Manifest.permission.RECORD_AUDIO,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.CALL_PHONE
},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission. ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Request location updates:
//Toast.makeText(this,"granted",Toast.LENGTH_SHORT).show();
}
} else {
new AlertDialog.Builder(this)
.setTitle("Permissions not granted!")
.setMessage("This app needs to access location to detect device, Please grant permission.")
.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
// ActivityCompat.requestPermissions(BluetoothLEFindActivity.this,
// new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.READ_EXTERNAL_STORAGE},
// MY_PERMISSIONS_REQUEST_LOCATION);
checkLocationPermission();
// ActivityCompat.requestPermissions(MainActivity.this,
// new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
// MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.setNegativeButton("Deny, Quit!", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialogInterface, int i){
finish();
}
}).setOnCancelListener(new DialogInterface.OnCancelListener(){
@Override
public void onCancel(DialogInterface dialogInterface){
finish();
}
})
.create()
.show();
// permission denied, boo! Disable the
// functionality that depends on this permission.
//Toast.makeText(this,"not granted",Toast.LENGTH_SHORT).show();
}
return;
}
}
}
@Override
protected void onResume() {
super.onResume();
if (checkLocationPermission()) {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission. ACCESS_FINE_LOCATION )
== PackageManager.PERMISSION_GRANTED
&&
ContextCompat.checkSelfPermission(this,
android.Manifest.permission. READ_EXTERNAL_STORAGE )
== PackageManager.PERMISSION_GRANTED) {
//Request location updates:
//Toast.makeText(this,"on resume, granted",Toast.LENGTH_SHORT).show();
}
}
}
/**
* 获取已连接的设备
*/
/* public void getConnectBluetoothDevice(){
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter==null){
return ;
}
int a2dp = mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.A2DP);
int headset = mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET);
int health = mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEALTH);
int flag = -1;
if (a2dp == BluetoothProfile.STATE_CONNECTED) {
flag = a2dp;
} else if (headset == BluetoothProfile.STATE_CONNECTED) {
flag = headset;
} else if (health == BluetoothProfile.STATE_CONNECTED) {
flag = health;
}
if (flag != -1) {
mBluetoothAdapter.getProfileProxy(this, new BluetoothProfile.ServiceListener() {
@Override
public void onServiceDisconnected(int profile) {
// TODO Auto-generated method stub
}
@Override
public void onServiceConnected(int profile, BluetoothProfile proxy) {
// TODO Auto-generated method stub
List<BluetoothDevice> mDevices = proxy.getConnectedDevices();
if (mDevices != null && mDevices.size() > 0) {
for (BluetoothDevice device : mDevices) {
Log.i("W","device name:"+ device.getName());
//
mConnectedBluetoothDevice = device;
try {
if(BluetoothDeviceBiz.getInstance().getmBluetoothSPP().mCurrentDevice==null||!BluetoothDeviceBiz.getInstance().getmBluetoothSPP().mCurrentDevice.getAddress().equals(mConnectedBluetoothDevice.getAddress())) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
device.setPairingConfirmation(true);
}
BluetoothDeviceBiz.getInstance().getmBluetoothSPP().connect(mConnectedBluetoothDevice.getAddress());
//延迟2s执行
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
connecting(new OnSuccessListener() {
@Override
public void success() {
startActivity(getNextIntent());
finish();
}
});
}
}, 2000);
}
} catch (Exception e) {
e.printStackTrace();
}
break;
}
} else {
mConnectedBluetoothDevice = null;
BluetoothDeviceBiz.getInstance().getmBluetoothSPP().mCurrentDevice = null;
Log.i("W","mDevices is null");
}
}
}, flag);
}
}*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment