蓝牙功能:
打开,关闭搜索,下载
package com.example.bluetooth;
import android.Manifest;
import android.app.Notification;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
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.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.example.bluetooth.adapter.LIstViewAdapter;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Button mOpen;
private Button mClose;
private Button mFind;
private BluetoothManager manager;
private MyReceiver myReceiver;
private BluetoothAdapter adapter;
private LIstViewAdapter lIstViewAdapter;
private ListView mListView;
private List<BluetoothDevice> list=new ArrayList<>();
private BluetoothDevice extra;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mOpen = findViewById(R.id.open);
mClose = findViewById(R.id.close);
mFind = findViewById(R.id.find);
mListView = findViewById(R.id.listView);
init();
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
BluetoothDevice w = list.get(position);
w.createBond();
}
});
}
private void init() {
String[] strings=new String[]{Manifest.permission.BLUETOOTH,Manifest.permission.BLUETOOTH_ADMIN,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE};
if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.M){
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
requestPermissions(strings,100);
}
}
initMyBlueThooth();
myReceiver=new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);//注册搜索蓝牙的广播
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(myReceiver,intentFilter);
}
public void initMyBlueThooth(){
manager=(BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
adapter=manager.getAdapter();//获得自己蓝牙
}
public void click(View view) {
switch (view.getId()){
case R.id.open:
open();
break;
case R.id.close:
close();
break;
case R.id.find:
find();
break;
}
}
private void find() {
adapter.startDiscovery();//扫描蓝牙
}
private void close() {
adapter.disable();//关闭蓝牙
}
//打开蓝牙
private void open() {
Intent intent = new Intent();
intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);//开启蓝
intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//允许蓝牙被搜索
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,200);//设置允许被搜索时间200s内可以被搜索到
startActivityForResult(intent,100);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(myReceiver);
}
class MyReceiver extends BroadcastReceiver {
private static final String TAG = "MyReceiver";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals(BluetoothDevice.ACTION_FOUND)){
BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
list.add(device);
Log.i(TAG, "onReceive: "+list.toString());
}else if(action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){
lIstViewAdapter=new LIstViewAdapter(context,list);
mListView.setAdapter(lIstViewAdapter);
Log.i(TAG, "onReceive: "+list.toString());
}else if(action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)){
extra= intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
int state=extra.getBondState();
if(state==BluetoothDevice.BOND_BONDED){
new ClientThread().start();
}
}
}
}
class ClientThread extends Thread{
@Override
public void run() {
super.run();
UUID uuid=UUID.fromString("00001106-0000-1000-8000-00805F9B34FB");
try {
BluetoothSocket socket=extra.createRfcommSocketToServiceRecord(uuid);
socket.connect();//建立连接
BufferedOutputStream os=new BufferedOutputStream(socket.getOutputStream());
FileInputStream is=new FileInputStream("/mnt/sdcard/http.txt");
int len=0;
byte[] b=new byte[1024];
while((len=is.read(b)) != -1){
os.write(b,0,len);
Log.i(TAG, "run: "+os);
}
os.flush();
os.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// public void receveFromServer(BluetoothSocket socket){
// try {
// InputStream is = socket.getInputStream();
// int len=0;
// byte[] b=new byte[1024];
// FileOutputStream os=new FileOutputStream(Environment.getExternalStorageDirectory()+"/aaa.txt");
// while((is.read(b)) != -1){
// os.write(b,0,len);
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
}
}
<?xml version="1.0" encoding="utf-8"?>
<Button
android:id="@+id/find"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="click"
android:text="搜索蓝牙"/>
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
</ListView>
package com.example.bluetooth.adapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.bluetooth.R;
import java.util.List;
public class LIstViewAdapter extends BaseAdapter {
private Context context;
private List<BluetoothDevice> list;
private LayoutInflater inflater;
public LIstViewAdapter(Context context, List<BluetoothDevice> list) {
this.context = context;
this.list = list;
inflater=LayoutInflater.from(context);
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null){
holder=new ViewHolder();
convertView=inflater.inflate(R.layout.listview_item,null);
holder.textView=convertView.findViewById(R.id.textView);
convertView.setTag(holder);
}else{
holder=(ViewHolder)convertView.getTag();
}
holder.textView.setText(list.get(position).getName());
return convertView;
}
static class ViewHolder{
private TextView textView;
}
}