bluetooth android

205
26 ноября 2016, 19:19

Приложение вылетает если блюзуз на устройстве не включен

D/bluetooth:  onResume - попытка соединения
E/BluetoothDevice: Bluetooth is not enabled
D/bluetooth:  ....соединяемся...
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.jeka.toolcarcontrol, PID: 21370
                  java.lang.RuntimeException: Unable to resume activity {com.example.jeka.toolcarcontrol/com.example.jeka.toolcarcontrol.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.bluetooth.BluetoothSocket.connect()' on a null object reference
                      at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4221)
                      at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4323)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3426)
                      at android.app.ActivityThread.access$1100(ActivityThread.java:229)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:148)
                      at android.app.ActivityThread.main(ActivityThread.java:7325)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.bluetooth.BluetoothSocket.connect()' on a null object reference
                      at com.example.jeka.toolcarcontrol.MainActivity.onResume(MainActivity.java:110)
                      at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1287)
                      at android.app.Activity.performResume(Activity.java:7015)
                      at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4210)
                      at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4323) 
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3426) 
                      at android.app.ActivityThread.access$1100(ActivityThread.java:229) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821) 
                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                      at android.os.Looper.loop(Looper.java:148) 
                      at android.app.ActivityThread.main(ActivityThread.java:7325) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
I/Process: Sending signal. PID: 21370 SIG: 9
Application terminated.

Вот код приложения

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
public class MainActivity extends Activity {
    private static final String Tag = "bluetooth";
    ImageButton img_button_up, img_button_down;
    TextView parameter1;
    Handler handler;
    private static final int REQUEST_ENABLE_BT = 1;
    BluetoothAdapter bluetoothAdapter;
    BluetoothSocket bluetoothSocket;
    OutputStream outputStream;
    private StringBuilder stringBuilder = new StringBuilder();
    private ConectionTread conectionTread;
    private static final UUID my_uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private static final String module_adress = "20:13:01:29:12:61";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_xml_land);
        img_button_up = (ImageButton) findViewById(R.id.img_but_up);
        img_button_down = (ImageButton) findViewById(R.id.img_but_down);
        parameter1 = (TextView) findViewById(R.id.parm1);
        handler = new Handler(){
            public void handleMessage(android.os.Message msg) {
            switch (msg.what){
                case 1:
                    byte[] readBuffer = (byte[]) msg.obj;
                    String strIncom = new String(readBuffer, 0, msg.arg1);
                    int end_of__line_indx = stringBuilder.indexOf(";"); //not working, return -1
                    Log.d(Tag, strIncom);
                    Log.d(Tag, String.valueOf(end_of__line_indx));
                    if (end_of__line_indx > 0){
                        String strBuild_print = stringBuilder.substring(0, end_of__line_indx); //get text, from 0 index to last index
                        stringBuilder.delete(0, stringBuilder.length());
                        parameter1.setText("param 1: " + strBuild_print);
                        Log.d(Tag, strIncom);
                    }
                }
             }
        };
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        chackBluetoothState();
        img_button_up.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                conectionTread.write("1");  // Send 1 to module
            }
        });
        img_button_down.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                conectionTread.write("0");
            }
        });
    }
        @Override
        public void onStart(){
            super.onStart();
            if (!bluetoothAdapter.isEnabled()) {
                Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            }
        }
        @Override
        public void onResume(){
            super.onResume();
                Log.d(Tag, " onResume - попытка соединения");
                BluetoothDevice device = bluetoothAdapter.getRemoteDevice(module_adress);
                try {
                    bluetoothSocket = device.createRfcommSocketToServiceRecord(my_uuid);
                } catch (IOException e) {
                    errorExit("Fatal Error", "Ошибка в onResume, проблема создания сокета " + e.getMessage());
                }
                Log.d(Tag, " ....соединяемся...");
                try {
                    bluetoothSocket.connect();
                    Toast.makeText(this,"Соединение установлено", Toast.LENGTH_LONG).show();
                    Log.d(Tag, "...Соединение установлено и готово к передаче данных...");
                } catch (IOException e) {
                    try {
                        bluetoothSocket.close();
                    } catch (IOException e1) {
                        Log.d(Tag, "..Ошибка закрытия порта...");
                    }
                    Toast.makeText(this,"Соединение не установлено", Toast.LENGTH_LONG).show();
                    Log.d(Tag, "...Соединение не установлено...");
                }
                Log.d(Tag, "..Создание Сокета..");
                try {
                    outputStream = bluetoothSocket.getOutputStream();
                } catch (IOException e) {
                    errorExit("Fatal Error", " Ошибка в onResume, не удалось создать выходной поток " + e.getMessage());
                }
                conectionTread = new ConectionTread(bluetoothSocket);
                conectionTread.start();
        }
    @Override
    public void onPause(){
        super.onPause();
        Log.d(Tag, "...InPause..");
        if (outputStream != null) {
            try {
                outputStream.flush();
            } catch (IOException e) {
                errorExit("Fatal Error", "ошибка в onPause(), не удалось очистить выходной поток " + e.getMessage());
            }
        }
        try {
            bluetoothSocket.close();
        } catch (IOException e1) {
            errorExit("Fatal Error", " ошибка в onPause, не удалось закрыть сокет" + e1.getMessage());
        }
    }
    private void chackBluetoothState() {
        if (bluetoothAdapter == null){
            errorExit("Fatal Error", "Bluetooth не поддерживается");
            finish();
            }
        }
    private void errorExit(String title, String massage) {
        Toast.makeText(getBaseContext(), title + " - " + massage, Toast.LENGTH_LONG).show();
        finish();
    }
    class ConectionTread extends Thread{
        private final BluetoothSocket mmSocket;
        private final InputStream mmInputStream;
        private final OutputStream mmOutStream;
        public ConectionTread(BluetoothSocket socket){
            mmSocket = socket;
            InputStream streamIn = null;
            OutputStream streamOut = null;
            try {
                streamIn = socket.getInputStream();
                streamOut = socket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mmInputStream = streamIn;
            mmOutStream = streamOut;
        }
        public void run(){
            byte[] buffer = new byte[256];
            int bytes;
            while (true){
                try {
                    //Read InputStream
                    if (mmInputStream != null) {
                        bytes = mmInputStream.read(buffer); // get byteArray in "buffer"
                        handler.obtainMessage(1, bytes, -1, buffer).sendToTarget(); // send message to Handler
                    }
                    } catch (IOException e) {
                    e.printStackTrace();
                    break;
                }
            }
        }
        public void write(String message){
            Log.d(Tag, "...Данные для отправки: " + message );
            byte[] msgBuffer = message.getBytes();
            try {
                if(mmOutStream != null)
                mmOutStream.write(msgBuffer);
            } catch (IOException e) {
                e.printStackTrace();
                Log.d(Tag, "...Ошибка отправки данных: " + e.getMessage() + "...");
            }
        }
        public void cancel(){
            try {
                mmSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
Answer 1

А в чем проблема-то? Вы не понимаете, почему программа вылетает?

Так в стек-трейсе же ясно написано:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.bluetooth.BluetoothSocket.connect()' on a null object reference

То есть у Вас bluetoothSocket == null.

UPD. Вы можете проверить, включен ли bluetooth таким образом:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
    // Device does not support Bluetooth
} else {
    if (!mBluetoothAdapter.isEnabled()) {
        // Bluetooth is not enable :)
    }
}

Далее, если bluetooth выключен, то Вы можете попросить пользователя включить его, если же устройство не поддерживает bluetooth, то показать соответствующее уведомление.

UPD 2. В методе onStart() Вы просите пользователя включить bluetooth запуская startActivityForResult(enableIntent, REQUEST_ENABLE_BT);, но дело в том, что метод onResume() (в котором вы пытаетесь коннектиться) срабатывает раньше того, как пользователь включит bluetooth (если вообще включит). Вам необходимо в методе onActivityResult(...) получать результат, и, если пользователь включил bluetooth, то производить коннект.

READ ALSO
Поиск в приложении: Searchable Activity, Searchable Dialog

Поиск в приложении: Searchable Activity, Searchable Dialog

Хочу сделать поиск в определенной активити в приложении, немного запуталась в тьюториалахХочу добавить в MainActivity, стандартный поиск при нажатии...

270
Расположить кнопку, что бы она была между двумя RelativeLayoout

Расположить кнопку, что бы она была между двумя RelativeLayoout

Нужно расположить кнопку, что бы она была, как на рисунке:

270
Разные адаптеры listview

Разные адаптеры listview

Имеется listview с группами каналовПо нажатию на которую в этом же listview выводится список каналов

238