標題:
Android
[打印本頁]
作者:
ray
時間:
2018-9-15 11:49
標題:
Android
package ray.test.smarthat;
import android.app.Activity;
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.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
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.util.Set;
import java.util.UUID;
public class MainActivity extends Activity {
private Button button1,button2,button3,button4,button5;
private TextView textView1 = null;
private BluetoothDevice myDevice;
private BluetoothSocket mySocket;
private OutputStream myOutputStream;
private InputStream myInputStream;
private String onStr = "a\n";
private String offStr = "b\n";
ToneGenerator toneG = new ToneGenerator(AudioManager.STREAM_ALARM, 100);
Handler mHandler = new Handler() {
@Override public void handleMessage(Message msg) {
if(msg.what > 0)
{
if(textView1 != null)
textView1.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);
}
};
BluetoothAdapter myBt=BluetoothAdapter.getDefaultAdapter();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button)this.findViewById(R.id.button1);
button2 = (Button)this.findViewById(R.id.button2);
button3 = (Button)this.findViewById(R.id.button3);
button4 = (Button)this.findViewById(R.id.button4);
button5 = (Button)this.findViewById(R.id.button5);
button5.setText("ON");
textView1 = (TextView)this.findViewById(R.id.textView1);
button1.setOnClickListener(button1_click);
button2.setOnClickListener(button2_click);
button3.setOnClickListener(button3_click);
button4.setOnClickListener(button4_click);
button5.setOnClickListener(button5_click);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.ex07, menu);
return true;
}
//開啟藍芽
Button.OnClickListener button1_click = new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(myBt == null)
{
textView1.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);
textView1.setText("藍芽開啟成功");
}};
//配對過的藍芽
Button.OnClickListener button2_click = new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
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";
}
textView1.setText(s);
}
}};
Button.OnClickListener button4_click = new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
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();
}};
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);
textView1.setText(textView1.getText()+"\n"+device.getName());
}
}
};
//關閉藍芽
Button.OnClickListener button3_click = new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
myBt.disable();
}};
//LED開關
Button.OnClickListener button5_click = new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
if(button5.getText().equals("ON"))
{
button5.setText("OFF");
//myOutputStream.write(onStr.getBytes());
}
else {
button5.setText("ON");
//myOutputStream.write(offStr.getBytes());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}};
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();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
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) { }
}
}
}
複製代碼
作者:
ray
時間:
2018-10-3 16:47
package ray.test.smarthat;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.media.AudioManager;
import android.media.ToneGenerator;
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.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
//private Button openBT,findBT,connectBT,disconnectBT;
private TextView status;
private TextView deviceName;
private BluetoothDevice myDevice;
private String deviceStatus = "";
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) {
switch(msg.what)
{
case 49:
case -2:
toneG.startTone(ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD, 200);
status.setText("你是不是低頭了呢!");
deviceStatus = "1";
break;
case 48:
case -1:
toneG.stopTone();
status.setText("你的姿勢很正確哦!");
deviceStatus = "0";
}
logToServer();
super.handleMessage(msg);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
status = (TextView)this.findViewById(R.id.status);
deviceName = (TextView)this.findViewById(R.id.deviceName);
}
/*
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();
Log.d("debug","BTConnect paired size:"+pairedDevices.size());
if(pairedDevices.size() > 0)
{
String s = "找不到任何正確連結的美姿皇冠";
for(BluetoothDevice device:pairedDevices)
{
boolean success = false;
Log.d("debug","BTConnect paired name:"+device.getName());
if(device.getName().substring(0,8).equals("SmartCap"))
{
myDevice = device;
deviceName.setText(device.getName());
try{
openBT();
success = true;
s = "配對到的美姿皇冠:"+deviceName.getText();
Log.d("debug","BTConnect paired success:"+device.getName());
}catch(Exception e){
s = "藍牙錯誤,請重開美姿皇冠及設定手機的藍牙連接";
Log.d("debug","BTConnect paired fail:"+device.getName());
}
}
if(success)
break;
}
status.setText(s);
}
}
public void disconnectBTClick(View v)
{
closeBT();
}
void closeBT()
{
try {
mySocket.close();
mySocket = null;
myDevice = null;
status.setText("");
deviceName.setText("");
}catch(Exception e)
{
status.setText("關閉失敗!");
}
}
void openBT() throws Exception
{
UUID uuid=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
Log.d("debug","BTConnect uuid ok");
Log.d("debug","BTConnect myDevice:"+myDevice.getName());
mySocket=myDevice.createRfcommSocketToServiceRecord(uuid);
Log.d("debug","BTConnect create socket ok");
Log.d("debug","BTConnect connect:"+mySocket.isConnected());
mySocket.connect();
Log.d("debug","BTConnect connect ok");
//myOutputStream=mySocket.getOutputStream();
//myInputStream=mySocket.getInputStream();
new ConnectedThread(mySocket).start();
Log.d("debug","BTConnect thread start ok");
}
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) {
status.setText("藍芽通訊失敗");
}
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
Log.d("debug","BTThread run:"+mySocket.toString());
while (mySocket != null) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
Log.d("debug","BTThread:"+buffer[0]);
mHandler.obtainMessage(buffer[0])
.sendToTarget();
Thread.sleep(200);
} catch (Exception e) {
Log.d("error","BTThread:"+e.toString());
}
}
Log.d("debug","BTThread end");
}
/* 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) { }
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case R.id.settings:
startActivity(new Intent(this,PrefsActivity.class));
return true;
case R.id.exit:
closeBT();
finish();
}
return false;
}
void logToServer(){
new Thread()
{
public void run()
{
try
{
URL url = new URL("http://"+PrefsActivity.getServer(MainActivity.this)+"/smartcap/log.php?device="+deviceName+"&status="+deviceStatus);
url.openStream();
}
catch(Exception e)
{
}
}
}.start();
}
}
複製代碼
作者:
ray
時間:
2018-10-3 16:47
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
android:orientation="vertical">
<!--
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="openBT"
android:onClick="openBTClick"
android:id="@+id/openBT" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="findBT"
android:onClick="findBTClick"
android:id="@+id/findBT" />
-->
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="連接美姿皇冠"
android:onClick="connectBTClick"
android:id="@+id/connectBT" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="斷開美姿皇冠"
android:onClick="disconnectBTClick"
android:id="@+id/disconnecBT" />
<TextView android:id="@+id/deviceName" android:text="" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView android:id="@+id/status" android:text="" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
複製代碼
歡迎光臨 種子論壇 | 高雄市資訊培育協會學員討論區 (http://istak.org.tw/seed/)
Powered by Discuz! 7.2