Тема: CITROEN-ARDUINO
Показать сообщение отдельно
Старый 23.12.2015, 21:30   #116
T_r_D
Старший Пользователь
 
Регистрация: 03.07.2015
Регион: 77, 97, 99, 177
Сообщений: 372
T_r_D is a jewel in the roughT_r_D is a jewel in the roughT_r_D is a jewel in the rough
По умолчанию

Итак, допилил прогу под ВТ для андройда.
манифест
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 btnOnbtnOff;
    
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 = (ButtonfindViewById(R.id.btnOn);
        
btnOff = (ButtonfindViewById(R.id.btnOff);

        
txtArduino = (TextViewfindViewById(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
                
}
            }
        });

        
= 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(readBuf0msg.arg1);
                        
sb.append(strIncom);                                                // формируем строку
                        
int endOfLineIndex sb.indexOf("\r\n");                            // определяем символы конца строки
                        
if (endOfLineIndex 0) {                                            // если встречаем конец строки,
                            
String sbprint sb.substring(0endOfLineIndex);               // то извлекаем строку
                            
sb.delete(0sb.length());                                      // и очищаем sb
                            
txtArduino.setText(sbprint);                                   // обновляем TextView
                            
btnOff.setEnabled(true);
                            
btnOn.setEnabled(true);
                        }
                        break;
                }
            }
        };
 }

    
BroadcastReceiver mybroadcast = new BroadcastReceiver() {
        @
Override
        
public void onReceive(Context contextIntent 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 titleString message){
        
Toast.makeText(getBaseContext(), title " - " messageToast.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(enableBtIntentREQUEST_ENABLE_BT);
            }
        }
    }

    @
Override
    
protected void onActivityResult(int requestCodeint resultCodeIntent 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_MESSAGEbytes, -1buffer).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>
T_r_D вне форума   Ответить с цитированием