服務端:java
import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; 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.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private BluetoothAdapter btAdapter; private String btAdress; private InputStream input; private OutputStream output; private Handler handler; final String uuid = "af3ad9b2-0ea6-4a90-be06-a1c86bc7e28b"; private TextView getInformationText; private Button one; private Button two; private Button three; private Button four; private Button five; private Button six; private int position; private Map<Integer, Button> map; public static boolean isRunning = true; private BroadcastReceiver receiver; private IntentFilter filter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); position = 1; //初始化 one = (Button) findViewById(R.id.one); two = (Button) findViewById(R.id.two); three = (Button) findViewById(R.id.three); four = (Button) findViewById(R.id.four); five = (Button) findViewById(R.id.five); six = (Button) findViewById(R.id.six); two.setEnabled(false); three.setEnabled(false); four.setEnabled(false); five.setEnabled(false); six.setEnabled(false); one.setOnClickListener(this); two.setOnClickListener(this); three.setOnClickListener(this); four.setOnClickListener(this); five.setOnClickListener(this); six.setOnClickListener(this); //初始化標識 map = new HashMap<>(); map.put(1, one); map.put(2, two); map.put(3, three); map.put(4, four); map.put(5, five); map.put(6, six); //註冊廣播 receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)) { Log.i("information", "hello i am a dialog~~~~~"); Intent btIntent = new Intent(BluetoothDevice.ACTION_BOND_STATE_CHANGED); intent.putExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_BONDED); sendBroadcast(btIntent); } } }; filter = new IntentFilter(); filter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST); registerReceiver(receiver, filter); //class: getInformationText = (TextView) findViewById(R.id.tv); getInformationText.append("\n"); btAdapter = BluetoothAdapter.getDefaultAdapter(); //打開藍牙 if (btAdapter.enable()) { Toast.makeText(this, "藍牙已成功打開", Toast.LENGTH_LONG).show(); btAdress = btAdapter.getAddress(); Log.i("information", UUID.randomUUID().toString()); //讓本身的藍牙設備永遠地能夠被搜索到 Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0); startActivity(intent); new btGetConnectionThread(btAdapter).start(); } else { Toast.makeText(this, "請打開藍牙!", Toast.LENGTH_LONG).show(); } //初始化handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); final String information = ((String) msg.obj); Log.i("information", information + "-----------" + isRunning); if (isRunning) { get_And_Do(information); } else { //發送信息到下一個界面 sendBroadcast(new Intent("send_to_me").putExtra("the_order", information)); } //getInformationText.append(" Zzm: " + information + "\n"); } }; } public void click(View view) { Toast.makeText(this, "已開啓鏈接!", Toast.LENGTH_LONG).show(); new btGetConnectionThread(btAdapter).start(); } //等待請求的鏈接 private class btGetConnectionThread extends Thread { private BluetoothServerSocket btServerSocket; private BluetoothSocket btSocket; public btGetConnectionThread(BluetoothAdapter btAdapter) { try { btServerSocket = btAdapter.listenUsingRfcommWithServiceRecord(UUID.randomUUID().toString(), UUID.fromString(uuid)); if (btServerSocket == null) { Toast.makeText(MainActivity.this, "藍牙創建鏈接失敗!", Toast.LENGTH_LONG).show(); return; } else { Toast.makeText(MainActivity.this, "藍牙正在等待鏈接!", Toast.LENGTH_LONG).show(); } } catch (IOException e) { Log.i("information", e.toString()); } } @Override public void run() { super.run(); //等待客戶端來的鏈接 try { btSocket = btServerSocket.accept(); } catch (IOException e) { // Toast.makeText(MainActivity.this,"藍牙鏈接,接收失敗!",Toast.LENGTH_LONG).show(); new btGetConnectionThread(btAdapter).start(); return; } if (btSocket != null) { try { // Toast.makeText(MainActivity.this,"藍牙鏈接成功!",Toast.LENGTH_LONG).show(); btServerSocket.close(); try { input = btSocket.getInputStream(); output = btSocket.getOutputStream(); new GetInformationThread().start(); } catch (IOException e) { Log.i("information", "獲取流失敗!"); } //鏈接成功後要作的事情 } catch (IOException e) { Log.i("information", e.toString()); // Toast.makeText(MainActivity.this,"藍牙鏈接關閉失敗!正在從新等待鏈接!",Toast.LENGTH_LONG).show(); new btGetConnectionThread(btAdapter).start(); return; } } else { Log.i("information", "獲取,socket失敗!"); // Toast.makeText(MainActivity.this,"藍牙鏈接失敗,正在從新等待鏈接!",Toast.LENGTH_LONG).show(); new btGetConnectionThread(btAdapter).start(); //Looper.loop(); return; } } } //鏈接後接收信息的線程 private class GetInformationThread extends Thread { @Override public void run() { super.run(); boolean is = true; while (is) { byte[] bytes = new byte[1024]; int length = 0; String getInformation = null; if (input != null || output != null) { try { length = input.read(bytes); getInformation = new String(bytes, 0, length, "utf-8"); //處理信息 Message message = new Message(); message.obj = getInformation; handler.sendMessage(message); } catch (IOException e) { Log.i("information", e.toString()); } } } } } //寫的監聽事件 @Override public void onClick(View v) { switch (v.getId()) { case R.id.one: //方法:下面同上 one(); break; case R.id.two: two(); break; case R.id.three: three(); break; case R.id.four: four(); break; case R.id.five: five(); break; case R.id.six: six(); break; } } //各個控制的方法 private void one() { isRunning = false; startActivity(new Intent(this, One.class)); } private void two() { startActivity(new Intent(this, Two.class)); isRunning = false; } private void three() { startActivity(new Intent(this, Three.class)); isRunning = false; } private void four() { startActivity(new Intent(this, Four.class)); isRunning = false; } private void five() { startActivity(new Intent(this, Five.class)); isRunning = false; } private void six() { startActivity(new Intent(this, Six.class)); isRunning = false; } //獲得控制端的信息再作出相應的反應 private void get_And_Do(String information) { switch (information) { case "left": if (position != 1 && position != 4) { map.get(position).setEnabled(false); map.get(position - 1).setEnabled(true); position -= 1; } break; case "front": if (position != 1 && position != 2 && position != 3) { map.get(position).setEnabled(false); map.get(position - 3).setEnabled(true); position -= 3; } break; case "down": if (position != 4 && position != 5 && position != 6) { map.get(position).setEnabled(false); map.get(position + 3).setEnabled(true); position += 3; } break; case "right": if (position != 6 && position != 3) { map.get(position).setEnabled(false); map.get(position + 1).setEnabled(true); position += 1; } break; case "sure": map.get(position).callOnClick(); break; } } }
客戶端:android
import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.UUID; public class Android_below_four_zero extends AppCompatActivity { private TextView textView1; private TextView textView2; private BluetoothAdapter btAdapter; final int STARTBLUETOOTH = 1994; final int SCANBLUETOOTH = 2010; private BluetoothSocket btSocket; private Handler handler1; private InputStream input; private OutputStream output; private BroadcastReceiver btResult; private BluetoothDevice btDevice; //UUID final String uuid = "af3ad9b2-0ea6-4a90-be06-a1c86bc7e28b"; private EditText sendInformation; private Button sending; private Button front; private Button down; private Button left; private Button right; private Button sure; private Button back; private ControlOrder order; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //initialView textView1 = (TextView) findViewById(R.id.Bt1); textView2 = (TextView) findViewById(R.id.Bt2); front = (Button) findViewById(R.id.front); down = (Button) findViewById(R.id.down); left = (Button) findViewById(R.id.left); right = (Button) findViewById(R.id.right); sure = (Button) findViewById(R.id.sure); back = (Button) findViewById(R.id.back); sendInformation = ((EditText) findViewById(R.id.send)); sending = ((Button) findViewById(R.id.sending)); //獲取藍牙設備管理對象 btAdapter = BluetoothAdapter.getDefaultAdapter(); //判斷藍牙是否打開,若是沒有就會提醒打開 if (btAdapter.isEnabled()) { Toast.makeText(this, "藍牙已成功打開", Toast.LENGTH_SHORT).show(); textView1.setText("本地藍牙的名字:" + btAdapter.getName()); //掃描設備 bluetoothScaning(btAdapter); } else { startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), STARTBLUETOOTH); } //發現設備的廣播 btResult = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.i("information", "---------" + action); if (BluetoothDevice.ACTION_FOUND.equals(action)) { btDevice =intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (null == btDevice) { Toast.makeText(context, "未發現設備", Toast.LENGTH_SHORT).show(); } else { textView2.setText("掃描到的藍牙的名字:" + btDevice.getName()); } } if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { Toast.makeText(context, "搜索藍牙完成", Toast.LENGTH_SHORT).show(); } if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) { int state = btDevice.getBondState(); if (state == BluetoothDevice.BOND_BONDED) Toast.makeText(context, "完成配對", Toast.LENGTH_SHORT).show(); if (state == BluetoothDevice.BOND_BONDING) Log.i("information","正在配對"); if (state == BluetoothDevice.BOND_NONE) Log.i("information","配對取消"); } if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)) { Toast.makeText(context, "正在請求配對!", Toast.LENGTH_SHORT).show(); //BluetoothaAutoConnectUtils.setPassWord(btDevice.getClass(),btDevice,"0000"); } } }; //註冊廣播 IntentFilter filter = new IntentFilter(); filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); filter.addAction(BluetoothDevice.ACTION_FOUND); filter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST); registerReceiver(btResult, filter); } //打開藍牙後返回的數據 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == STARTBLUETOOTH && resultCode == RESULT_OK) { Toast.makeText(this, "藍牙已成功打開", Toast.LENGTH_SHORT).show(); textView1.setText("本地藍牙的名字:" + btAdapter.getName()); bluetoothScaning(btAdapter); } else if (requestCode == SCANBLUETOOTH && resultCode == RESULT_OK) { ///// ////// } else { Toast.makeText(this, "藍牙操做失敗", Toast.LENGTH_LONG).show(); Toast.makeText(this, "" + requestCode + " " + resultCode, Toast.LENGTH_LONG).show(); } // } //藍牙掃描的方法 private void bluetoothScaning(BluetoothAdapter btAdapter) { if (btAdapter.getScanMode() == BluetoothAdapter.SCAN_MODE_NONE) { //若是沒在掃描則開啓掃描 Intent btIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); //設置掃描時間 btIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 6000); startActivityForResult(btIntent, SCANBLUETOOTH); // Log.i("information","hello"); } else { //若是在掃描,或則已經獲取告終果,開啓從新掃描 if (!btAdapter.isDiscovering()) { btAdapter.startDiscovery(); } else { //中止掃描從新掃描 btAdapter.cancelDiscovery(); btAdapter.startDiscovery(); } } } //解除註冊的廣播 @Override protected void onDestroy() { unregisterReceiver(btResult); btAdapter.disable(); super.onDestroy(); } //從新鏈接 public void click(View view) { bluetoothScaning(btAdapter); } //執行鏈接 public void click_1(View view) { new BtConnectThread(btDevice).start(); // BluetoothaAutoConnectUtils.createConnection(btDevice.getClass(),btDevice); } //創建請求鏈接藍牙的線程 private class BtConnectThread extends Thread { public BtConnectThread(BluetoothDevice btDevice) { //獲取通訊Socket if (null != btDevice) { try { btSocket = btDevice.createInsecureRfcommSocketToServiceRecord(UUID.fromString(uuid)); } catch (IOException e) { Toast.makeText(Android_below_four_zero.this, "藍牙創建鏈接失敗", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(Android_below_four_zero.this, "藍牙未搜索到設備", Toast.LENGTH_SHORT).show(); } } @Override public void run() { super.run(); Looper.prepare(); if (btSocket != null) { try { btAdapter.cancelDiscovery(); //鏈接 btSocket.connect(); if (!btSocket.isConnected()) { Toast.makeText(Android_below_four_zero.this, "藍牙鏈接失敗,請重試", Toast.LENGTH_SHORT).show(); } else { if (!btDevice.getName().equals("null")) { Toast.makeText(Android_below_four_zero.this, "與 " + btDevice.getName() + " 藍牙設備鏈接成功", Toast.LENGTH_SHORT).show(); try { input = btSocket.getInputStream(); output = btSocket.getOutputStream(); if (null != output) { Log.i("information", "---------------------11"); control(); } if (null != input) { Log.i("information", "---------------------22"); } } catch (IOException e) { Log.i("information", "獲取流失敗!"); } Looper.loop(); } else { Toast.makeText(Android_below_four_zero.this, "藍牙鏈接成功", Toast.LENGTH_SHORT).show(); try { input = btSocket.getInputStream(); output = btSocket.getOutputStream(); control(); } catch (IOException e) { Log.i("information", "獲取流失敗!"); } Looper.loop(); } //鏈接成功時候的操做 } } catch (Exception e) { Toast.makeText(Android_below_four_zero.this, "藍牙鏈接超時,請重試", Toast.LENGTH_SHORT).show(); Log.i("information", e.toString()); Looper.loop(); } } } } //連接後的處理線程 private class BtConnect extends Thread { @Override public void run() { super.run(); } } //連接後發送信息 public void click_2(View view) { if (null == output || null == input) { Toast.makeText(Android_below_four_zero.this, "藍牙鏈接異常!不能發信息", Toast.LENGTH_SHORT).show(); } else { String information = sendInformation.getText().toString(); if (TextUtils.isEmpty(information)) { Toast.makeText(Android_below_four_zero.this, "不能發送空信息!", Toast.LENGTH_LONG).show(); } else { //發送信息 byte[] bytes = new byte[0]; try { bytes = information.getBytes("utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } try { output.write(bytes); Log.i("information", information); Toast.makeText(Android_below_four_zero.this, "發送信息成功!", Toast.LENGTH_LONG).show(); } catch (IOException e) { Toast.makeText(Android_below_four_zero.this, "發送信息失敗!", Toast.LENGTH_LONG).show(); } } } sendInformation.setText(""); } //初始化監聽器以及監聽 private void control() { order = new ControlOrder(this, output, R.id.front, R.id.down, R.id.left, R.id.right, R.id.sure, R.id.back); //設置指令監聽 front.setOnClickListener(order); down.setOnClickListener(order); left.setOnClickListener(order); right.setOnClickListener(order); sure.setOnClickListener(order); back.setOnClickListener(order); } }