Итак, допилил прогу под ВТ для андройда.
манифест
PHP код:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.oho.bt" >
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar" >
<receiver android:name=".MyReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.SCREEN_ON"/>
<action android:name="android.intent.action.SCREEN_OFF"/>
</intent-filter>
</receiver>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Ява
PHP код:
package com.example.oho.bt;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.os.Handler;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btnOn, btnOff;
TextView txtArduino;
Handler h;
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter btAdapter = null;
private ConnectedThread mConnectedThread;
private StringBuilder sb = new StringBuilder();
final int RECIEVE_MESSAGE = 1; // Статус для Handler
Integer btconnectingst = 0; //Проверяем активно ли соединение
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOn = (Button) findViewById(R.id.btnOn);
btnOff = (Button) findViewById(R.id.btnOff);
txtArduino = (TextView) findViewById(R.id.txtArduino);
btAdapter = BluetoothAdapter.getDefaultAdapter();
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_ON));
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_OFF));
btnOn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (btconnectingst.equals(1)) {
mConnectedThread.write("1"); // Отправляем через Bluetooth цифру 1
}
}
});
btnOff.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (btconnectingst.equals(1)) {
mConnectedThread.write("0"); // Отправляем через Bluetooth цифру 0
}
}
});
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE: // если приняли сообщение в Handler
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1);
sb.append(strIncom); // формируем строку
int endOfLineIndex = sb.indexOf("\r\n"); // определяем символы конца строки
if (endOfLineIndex > 0) { // если встречаем конец строки,
String sbprint = sb.substring(0, endOfLineIndex); // то извлекаем строку
sb.delete(0, sb.length()); // и очищаем sb
txtArduino.setText(sbprint); // обновляем TextView
btnOff.setEnabled(true);
btnOn.setEnabled(true);
}
break;
}
}
};
}
BroadcastReceiver mybroadcast = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
checkBTState();
}
else if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
if (btconnectingst.equals(1)){
btconnectingst = 0;
mConnectedThread.cancel();
}
}
}
};
private void errorExit(String title, String message){
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
}
private void checkBTState() {
if(btAdapter==null) {
} else {
if (btAdapter.isEnabled()) {
ConnectBT();
btconnectingst = 1;
} else {
Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_ENABLE_BT){
if (resultCode == RESULT_OK){
ConnectBT();
btconnectingst = 1;
}
if(resultCode == RESULT_CANCELED){
finish();
}
}
}
@Override
public void onResume() {
super.onResume();
checkBTState();
}
@Override
public void onPause() {
//тут возникает проблема если ВТ выключен!
//Видимо из за того, что пытамся закрыть несуществующий сокет.
//Нужно записывать в переменную статус адаптера!
super.onPause();
if (btconnectingst.equals(1)) {
btconnectingst = 0;
mConnectedThread.cancel();
}
}
public void ConnectBT() {
btAdapter.cancelDiscovery();
for (BluetoothDevice device : btAdapter.getBondedDevices()) {
try {
try {
Method m = device.getClass().getMethod("createRfcommSocket",new Class[] { int.class });
try {
BluetoothSocket btSocket = (BluetoothSocket) m.invoke(device,Integer.valueOf(1));
btSocket.connect();
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
break;
} catch (IOException e) {}
}
catch (IllegalArgumentException e) {}
catch (IllegalAccessException e) {}
catch (InvocationTargetException e) {}
} catch (SecurityException e) {}
catch (NoSuchMethodException e) {}
}
}
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[256]; // 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); // Получаем кол-во байт и само собщение в байтовый массив "buffer"
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Отправляем в очередь сообщений Handler
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String message) {
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
xml
PHP код:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" 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"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/activity_main" tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text From Arduino"
android:id="@+id/txtArduino"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_above="@+id/btnOn"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:id="@+id/btnOn"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="37dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:id="@+id/btnOff"
android:layout_alignBottom="@+id/btnOn"
android:layout_toRightOf="@+id/btnOn"
android:layout_toEndOf="@+id/btnOn" />
</RelativeLayout>