android wifi(WAP/PSK加密)藍牙設備的連接

(正在上班,待續)

WIFI配置權限

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

藍牙連接的配置權限

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

<uses-permission android:name="android.permission.BLUETOOTH"/>

WIFI連接

其實wifi的連接參數可以在文件裏面找到(需要手機root),

進入cmd命令提示符,adb shell進入 data/misc/wifi,查看wpa_supplicant.conf這個文件,使用cat  wpa_supplicant.conf這個指令,我們可以看到之前連接的一些信息



一:藍牙連接聊天

package com.liu.blutoolth;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
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.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

@SuppressLint("HandlerLeak")
public class MainActivity extends Activity implements OnClickListener {
	private Button searchBtn; // 搜索按鈕
	private TextView showList; // 藍牙數據
	private BluetoothAdapter ma; // 藍牙
	private IntentFilter mFilter;
	private Button serverBtn; // 作爲服務器
	private Button clientBtn; // 作爲客戶端
	private BluetoothServerSocket sServerSocket = null;
	private static BluetoothDevice mDevice; // 客戶端要連接的設備
	private ServerThread server; // 服務端線程
	private ConnectServer connect; // 客戶端線程
	private static UUID uuid = null; // 雙方的UUID
	private EditText uuidText; // UUID(後四位)
	private BluetoothSocket clientSocket; // 客戶端連接端口
	private BluetoothSocket serverSocket; // 服務端連接端口
	private EditText sendText;
	private Button send;
	private Handler hand;
	private boolean isServer = true;
	private OutputStream outClient;
	private InputStream inClient;
	private final BroadcastReceiver br = new BroadcastReceiver() {

		@SuppressLint("NewApi")
		@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 ("C230t".trim().equals(device.getName())) {	//這裏的"C230t"是你想要連接的藍牙設備的名稱,需要手動修改
					mDevice = device; // 獲取對方設備
					ma.cancelDiscovery();
				}

				StringBuilder sb = new StringBuilder();
				sb.append("name:" + device.getName() + " address:"
						+ device.getAddress() + "\n");
				showList.append(sb);
				
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);
		init();
	}

	private void init() {
		searchBtn = (Button) findViewById(R.id.search);
		showList = (TextView) findViewById(R.id.showlist);
		serverBtn = (Button) findViewById(R.id.server);
		clientBtn = (Button) findViewById(R.id.client);
		uuidText = (EditText) findViewById(R.id.uuid);
		sendText = (EditText) findViewById(R.id.sent_text);
		send = (Button) findViewById(R.id.send);
		serverBtn.setOnClickListener(this);
		clientBtn.setOnClickListener(this);
		mFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		registerReceiver(br, mFilter);
		hand = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				StringBuilder sb = new StringBuilder();
				sb.append((String) msg.obj + "\n");
				showList.append(sb);
				if (((String) msg.obj).equalsIgnoreCase("wifi")) {
					// Intent intent = new Intent();
					/*
					 * intent.setAction("com.liu.wifi.mainactivity");
					 * 
					 * startActivity(intent);
					 */
					LayoutInflater inflate = getLayoutInflater();
					View view = inflate.inflate(R.layout.wifi_dialog, null);
					Builder wifiDialog = new AlertDialog.Builder(
							MainActivity.this);
					wifiDialog.setTitle("title");
					wifiDialog.setView(view);
					wifiDialog.setPositiveButton("ok", null);
					wifiDialog.setNegativeButton("cancel", null);
					wifiDialog.show();

				}

			}
		};
		send.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (isServer) {
					ServerSendMessage();
				} else {
					ClientSendMessage();
				}
			}
		});
		showList.setText("DEVICE");

		ma = BluetoothAdapter.getDefaultAdapter();
		searchBtn.setOnClickListener(new OnClickListener() { // 搜索按鈕

					@Override
					public void onClick(View v) {
						ma.cancelDiscovery();
						ma.startDiscovery();

						Intent canFind = new Intent(
								BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
						canFind.putExtra(
								BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,
								300);
						startActivity(canFind);
					}
				});

		if (!ma.isEnabled()) {
			Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(intent, 1);
		
		}
	}

	private OutputStream outServer;

	private void ServerSendMessage() {
		try {
			if (!sendText.getText().toString().trim().equals("")) {
				outServer
						.write(sendText.getText().toString().trim().getBytes());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	protected void ClientSendMessage() {
		try {
			if (!sendText.getText().toString().trim().equals("")) {
				outClient
						.write(sendText.getText().toString().trim().getBytes());
				
			}
		} catch (IOException e) {
			e.printStackTrace();
			try {
				outClient.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.server:
			isServer = true;
			clientBtn.setVisibility(View.INVISIBLE);
			uuid = UUID.fromString("00035201-0000-1000-8000-00805F92"
					+ uuidText.getText().toString().trim());
			startServer();
			break;
		case R.id.client:
			isServer = false;
			serverBtn.setVisibility(View.INVISIBLE);
			uuid = UUID.fromString("00035201-0000-1000-8000-00805F92"
					+ uuidText.getText().toString().trim());
			startConnect();
			break;
		default:
			break;
		}
	}

	private void startConnect() {
		if (uuid == null) {
			
		} else {
			if (MainActivity.mDevice != null) {
				connect = new ConnectServer(mDevice, uuid);
				connect.start();
				
			}
		}
	}

	private void startServer() {
		if (server == null) {
			server = new ServerThread();
			server.start();
		}
	}

	private InputStream inServer; // 服務器接收

	// 服務端等待線程
	private class ServerThread extends Thread {
		public ServerThread() {
			try {
				sServerSocket = ma.listenUsingRfcommWithServiceRecord("bt",
						uuid);		//這裏的 "bt"是本地設備名,可修改
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void run() {
			ma.cancelDiscovery();
			while (true) {
				try {
					serverSocket = sServerSocket.accept();
					outServer = serverSocket.getOutputStream();
					inServer = serverSocket.getInputStream();
					if (serverSocket != null) {
						sServerSocket.close();
						break;
					}
				} catch (IOException e) {
					e.printStackTrace();
					try {
						if (sServerSocket != null) {
							sServerSocket.close();
						}
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			}
		}
	}

	// 客戶端連接線程

	private class ConnectServer extends Thread {

		public ConnectServer(BluetoothDevice device, UUID uuid) {
			
			try {
				clientSocket = device.createRfcommSocketToServiceRecord(uuid);

			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void run() {
			ma.cancelDiscovery();
			try {
				clientSocket.connect();
				inClient = clientSocket.getInputStream();
				outClient = clientSocket.getOutputStream();
				new handClientThread().start();
			} catch (IOException e) {
				e.printStackTrace();
				try {
					clientSocket.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(br);
	}

	// 處理客戶端發來的數據
	private class handClientThread extends Thread {

		@Override
		public void run() {

			byte[] buffer = new byte[1024];
			int size = 0;
			while (true) {
				try {
					if (isServer) {
	
						size = inServer.read(buffer);
						String str = new String(buffer, 0, size, "UTF-8");
						
						Message msg = new Message();
						msg.obj = str;
						hand.sendMessage(msg);
					} else {
						size = inClient.read(buffer);
						String str = new String(buffer, 0, size, "UTF-8");
						
						Message msg = new Message();
						msg.obj = str;
						hand.sendMessage(msg);
					}

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					break;
				}

			}

		}

	}
}


activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/search"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="@string/search" />

    <TextView
        android:id="@+id/showlist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/uuid" />

    <Button
        android:id="@+id/server"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/search"
        android:text="@string/server" />

    <Button
        android:id="@+id/client"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/search"
        android:text="@string/client" />

    <EditText
        android:id="@+id/uuid"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="22dp"
        android:layout_below="@id/server"
        android:hint="@string/uuid"
        android:ems="10" >

        <requestFocus />
        
    </EditText>

    <EditText
        android:id="@+id/sent_text"
        android:hint="@string/sent_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignLeft="@+id/send" />

    <Button
        android:id="@+id/send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_marginLeft="29dp"
        android:text="@string/send" />

</RelativeLayout>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章