//main_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/player"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="1号玩家"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick_Search"
android:text="搜索" />
<ListView
android:id="@+id/lvDevices"
android:layout_width="wrap_content"
android:layout_height="200dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.juliciy.bluetoothproject_18715_2.MySurfaceView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</LinearLayout>
// mySurfaceView 类;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.io.IOException;
/**
* Created by juliciy on 2018/7/15 0015.
*/
public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback,Runnable {
static int my_x = 40,my_y = 40;
static int you_x = 200,you_y = 200;
private SurfaceHolder sfh;
private Paint paint;
private Thread th;
private boolean flag;
private Canvas canvas;
private int screenW, screenH;
public MySurfaceView(Context context){
super(context);
sfh = this.getHolder();
sfh.addCallback(this);
paint = new Paint();
paint.setColor(Color.WHITE);
setFocusable(true);
}
public MySurfaceView(Context context, AttributeSet attrs) {
// attrs为自定义属性,在xml配置,可以通过此参数来获取
super(context, attrs);
sfh = this.getHolder();
sfh.addCallback(this);
paint = new Paint();
paint.setColor(Color.WHITE);
setFocusable(true);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
screenW = this.getWidth();
screenH = this.getHeight();
flag = true;
th = new Thread(this);
th.start();
}
public void myDraw(){
try{
canvas = sfh.lockCanvas();
if(canvas != null){
canvas.drawRGB(0,0,0);
canvas.drawCircle(my_x,my_y,40,paint);
canvas.save();
paint.setColor(Color.RED);
canvas.drawCircle(you_x,you_y,40,paint);
paint.setColor(Color.WHITE);
canvas.restore();
}
}catch (Exception e){
}finally {
if(canvas != null){
sfh.unlockCanvasAndPost(canvas);
}
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if(MainActivity.player == 1){
my_x = (int) event.getX();
my_y = (int) event.getY();
}else if(MainActivity.player == 2){
you_x = (int) event.getX();
you_y = (int) event.getY();
}
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return super.onKeyDown(keyCode, event);
}
public void logic(){
if(MainActivity.playerData != null){
String str = MainActivity.playerData;
String a[] = str.split(":");
int x = Integer.parseInt(a[0]);
int y = Integer.parseInt(a[1]);
if(MainActivity.player == 1){
you_x = x;
you_y = y;
}else if(MainActivity.player == 2 ){
my_x = x;
my_y = y;
}
}
if(MainActivity.os != null){
int a[] = new int[2];
String text = "";
if (MainActivity.player == 1){
text = text + my_x + ":" + my_y;
a[0] = my_x;
a[1] = my_y;
}else if (MainActivity.player == 2){
text = text + you_x + ":" + you_y;
a[0] = you_x;
a[1] = you_y;
}
try{
MainActivity.os.write(text.getBytes("UTF-8"));
}catch (IOException e){
e.printStackTrace();
}
}
}
@Override
public void run() {
while(flag){
long start = System.currentTimeMillis();
myDraw();
logic();
long end = System.currentTimeMillis();
try{
if(end - start < 100){
Thread.sleep(100 - (end - start));
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
flag = false;
}
}
//main主类
package com.example.juliciy.bluetoothproject_18715_2;
import android.app.Activity;
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.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity implements OnItemClickListener {
private BluetoothAdapter mBluetoothAdapter;
private List<String > bluetoothDevices = new ArrayList<>();
private ListView lvDevices;
private ArrayAdapter<String> arrayAdapter;
private final UUID MY_UUID = UUID
.fromString("db764ac8-4b08-7f25-aafe-59d03c27bae3");
private final String NAME = "Bluetooth_socket";
private BluetoothDevice selectDevice;
private BluetoothSocket clientSocket;
static public OutputStream os;
private AcceptThread thread;
static public int player = 1;
static String playerData = null;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.player);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(player == 1){
player = 2;
button.setText("二号玩家");
}else{
player = 1;
button.setText("一号玩家");
}
}
});
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
lvDevices = (ListView) findViewById(R.id.lvDevices);
arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,
bluetoothDevices);
lvDevices.setAdapter(arrayAdapter);
lvDevices.setOnItemClickListener(this);
Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
if(devices.size() > 0){
for (BluetoothDevice bluetoothDevice : devices){
bluetoothDevices.add(bluetoothDevice.getName() + ":" +
bluetoothDevice.getAddress()+"\n");
}
}
IntentFilter filter = new IntentFilter(
BluetoothAdapter.ACTION_DISCOVERY_FINISHED
);
registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);
thread = new AcceptThread();
thread.start();
}
public void onClick_Search(View view){
setTitle("正在扫描");
if(mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
}
mBluetoothAdapter.startDiscovery();
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
@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);
if(device.getBondState() != BluetoothDevice.BOND_BONDED){
bluetoothDevices.add(device.getName() + ":" + device.getAddress() + "\n");
arrayAdapter.notifyDataSetChanged();
}
}else if(action
.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){
setTitle("搜索完成");
}
}
};
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String s = arrayAdapter.getItem(position);
String address = s.substring(s.indexOf(":") + 1).trim();
if(mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
}
if(selectDevice == null){
selectDevice = mBluetoothAdapter.getRemoteDevice(address);
}
try {
if (clientSocket == null) {
clientSocket = selectDevice
.createInsecureRfcommSocketToServiceRecord(MY_UUID);
clientSocket.connect();
os = clientSocket.getOutputStream();
}
if(os != null){
String text = "abc";
os.write(text.getBytes("UTF-8"));
}
Toast.makeText(this, "发送信息成功,请查收", 0).show();
}catch (IOException e){
e.printStackTrace();
Toast.makeText(this, "发送信息失败", 0).show();
}
}
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// Toast.makeText(MainActivity.this, (String ) msg.obj, Toast.LENGTH_SHORT).show();
if (player == 2){
// MySurfaceView.my_x += 10;
playerData = (String) msg.obj;
button.setText("二号玩家(" + (String)msg.obj + ")");
}else if (player == 1){
// MySurfaceView.you_x += 10;
playerData = (String) msg.obj;
button.setText("一号玩家(" + (String)msg.obj + ")");
}
}
};
private class AcceptThread extends Thread{
private BluetoothServerSocket serverSocket;
private BluetoothSocket socket;
private InputStream is;
private OutputStream os;
public AcceptThread(){
try{
serverSocket = mBluetoothAdapter
.listenUsingInsecureRfcommWithServiceRecord(NAME, MY_UUID);
}catch (Exception e){
}
}
public void run(){
try{
socket = serverSocket.accept();
is = socket.getInputStream();
os= socket.getOutputStream();
while(true){
byte[] buffer = new byte[128];
int count = is.read(buffer);
Message msg = new Message();
msg.obj = new String(buffer, 0, count, "UTF-8");
handler.sendMessage(msg);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}