標題:
SmartHat(Android)
[打印本頁]
作者:
ray
時間:
2018-9-15 12:09
標題:
SmartHat(Android)
package ray.test.smarthat;
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.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
//private Button openBT,findBT,connectBT,disconnectBT;
private TextView status;
private BluetoothDevice myDevice;
private BluetoothSocket mySocket;
private OutputStream myOutputStream;
private InputStream myInputStream;
private BluetoothAdapter myBT = BluetoothAdapter.getDefaultAdapter();
ToneGenerator toneG = new ToneGenerator(AudioManager.STREAM_ALARM, 100);
Handler mHandler = new Handler() {
@Override public void handleMessage(Message msg) {
if(msg.what > 0)
{
if(status != null)
status.setText("Got from BT:"+msg.what);
}
if(msg.what == 49)
toneG.startTone(ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD, 200);
if(msg.what == 48)
toneG.stopTone();
super.handleMessage(msg);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
status = (TextView)this.findViewById(R.id.status);
}
public void openBTClick(View v)
{
if(myBT == null)
{
status.setText("手機無藍芽設備");
finish();
return;
}
if(!myBT.enable())
{
Intent enable = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enable, 0);
}
Intent scanable = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(scanable, 0x2);
status.setText("藍芽開啟成功");
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
status.setText(status.getText()+"\n"+device.getName());
}
}
};
public void findBTClick(View v)
{
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
// 注册广播接收器,接收并处理搜索结果
registerReceiver(receiver, intentFilter);
// 寻找蓝牙设备,android会将查找到的设备以广播形式发出去
myBT.startDiscovery();
}
public void connectBTClick(View v)
{
Set<BluetoothDevice> pairedDevices = myBT.getBondedDevices();
if(pairedDevices.size() > 0)
{
String s = "";
for(BluetoothDevice device:pairedDevices)
{
if(device.getName().equals("RAY_Bluetooth"))
{
myDevice = device;
try{
openBT();
}catch(Exception e){}
s = "RAY_BT Connected!";
break;
}
//s += device.getName()+"\t"+device.getAddress()+"\n";
}
status.setText(s);
}
}
public void disconnectBTClick(View v)
{}
void openBT() throws IOException
{
UUID uuid=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
mySocket=myDevice.createRfcommSocketToServiceRecord(uuid);
mySocket.connect();
//myOutputStream=mySocket.getOutputStream();
//myInputStream=mySocket.getInputStream();
new ConnectedThread(mySocket).start();
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(buffer[0])
.sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main Activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main Activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
複製代碼
歡迎光臨 種子論壇 | 高雄市資訊培育協會學員討論區 (http://istak.org.tw/seed/)
Powered by Discuz! 7.2