Страница 1 из 1

Bluetooth Проблемы с отладчиком!

Добавлено: 10 май 2014, 03:57
Dmitry91
Всем доброго вечера!

Помогите, пожалуйста, решить проблему. Хочу написать простую программу для Android c включением/выключением светодиода. Пример программы активации Bluetooth взял с сайта http://wiki.amperka.ru/%D0%B1%D0%B5%D1% ... -bluetooth
При компиляции ошибок нет, однако в отладчике приложение запускаться ну никак не хочет.
  • MainActivity.java

Код: Выделить всё

package com.example.project_bt_allumerled;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.app.Activity;
import android.app.Fragment;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
    }


    @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) {
        // 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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
    	
    	TextView textResultat;
    	Button btnAllumerLED;
    	Button btnEteindreLED;
    	LinearLayout ecran;
    	private OnClickListener oclBtn;
    	
    	//Сокет, с помощью которого мы будем отправлять данные
    	BluetoothSocket clientSocket;

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            
            //найдем View элементы
            textResultat = (TextView) rootView.findViewById(R.id.textResultat);
            btnAllumerLED = (Button) rootView.findViewById(R.id.allumerLED);
            btnEteindreLED = (Button) rootView.findViewById(R.id.eteindreLED);            
        	
            //Включаем bluetooth. Если он уже включен, то ничего не произойдет
            String enableBT = BluetoothAdapter.ACTION_REQUEST_ENABLE;
            startActivityForResult(new Intent(enableBT), 0);
     
            //Мы хотим использовать тот bluetooth-адаптер, который задается по умолчанию
            BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

            //Пытаемся проделать эти действия
            try{
                //Устройство с данным адресом - наш Bluetooth Bee
                //Адрес опредеяется следующим образом: установите соединение
                //между ПК и модулем (пин: 1234), а затем посмотрите в настройках
                //соединения адрес модуля. Скорее всего он будет аналогичным.
                BluetoothDevice device = bluetooth.getRemoteDevice("20:14:04:14:29:72"); 
     
                //Инициируем соединение с устройством
                Method m = device.getClass().getMethod(
                        "createRfcommSocket", new Class[] {int.class});
     
                clientSocket = (BluetoothSocket) m.invoke(device, 1);
                clientSocket.connect();
     
                //В случае появления любых ошибок, выводим в лог сообщение
            } catch (IOException e) {
                Log.d("BLUETOOTH", e.getMessage());
            } catch (SecurityException e) {
                Log.d("BLUETOOTH", e.getMessage());
            } catch (NoSuchMethodException e) {
                Log.d("BLUETOOTH", e.getMessage());
            } catch (IllegalArgumentException e) {
                Log.d("BLUETOOTH", e.getMessage());
            } catch (IllegalAccessException e) {
                Log.d("BLUETOOTH", e.getMessage());
            } catch (InvocationTargetException e) {
                Log.d("BLUETOOTH", e.getMessage());
            }
    
            //Выводим сообщение об успешном подключении
            Toast.makeText(getActivity(), "CONNECTED", Toast.LENGTH_LONG).show();
            
            //создаем обработчик нажатия
            oclBtn = new OnClickListener() {		
				public void onClick(View v) {
					 //Пытаемся послать данные
	                try {
	                    //Получаем выходной поток для передачи данных
	                    OutputStream outStream = clientSocket.getOutputStream();
	         
	                    int value = 0;
	         
	                    //В зависимости от того, какая кнопка была нажата, 
	                    //изменяем данные для посылки
						switch(v.getId()){
						case R.id.allumerLED:
							//кнопка ОК
							textResultat.setText("Светодиод включен");
							value = 61;
							break;
						case R.id.eteindreLED:
							//кнопка Cancel
							textResultat.setText("Светодиод выключен");
							value = 60;
						}
						
						//Пишем данные в выходной поток
	                    outStream.write(value);
	                    
	                } catch (IOException e) { 
                    //Если есть ошибки, выводим их в лог
                    Log.d("BLUETOOTH", e.getMessage()); 
                 }
				}
            };
            btnAllumerLED.setOnClickListener(oclBtn);
            btnEteindreLED.setOnClickListener(oclBtn);                      
            return rootView;
        }
    }

}
  • AndroidManifest.xml

Код: Выделить всё

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.project_bt_allumerled"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="16" />

    <uses-permission android:name="android.permission.BLUETOOTH" />
	<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.project_bt_allumerled.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
  • Error Log

Код: Выделить всё

eclipse.buildId=4.3.2.M20140221-1700
java.version=1.8.0
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=fr_FR
Framework arguments:  -product org.eclipse.epp.package.java.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product

Error
Sat May 10 01:31:34 CEST 2014
Unhandled event loop exception

java.lang.NullPointerException
	at com.android.ddmuilib.logcat.LogCatPanel.updateUnreadCount(LogCatPanel.java:1212)
	at com.android.ddmuilib.logcat.LogCatPanel.bufferChanged(LogCatPanel.java:1168)
	at com.android.ddmuilib.logcat.LogCatPanel.reloadLogBuffer(LogCatPanel.java:1196)
	at com.android.ddmuilib.logcat.LogCatPanel.updateAppliedFilters(LogCatPanel.java:1136)
	at com.android.ddmuilib.logcat.LogCatPanel.access$1600(LogCatPanel.java:98)
	at com.android.ddmuilib.logcat.LogCatPanel$8.widgetSelected(LogCatPanel.java:667)
	at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:248)
	at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
	at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1057)
	at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4170)
	at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3759)
	at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$9.run(PartRenderingEngine.java:1113)
	at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
	at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:997)
	at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:140)
	at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:611)
	at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
	at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:567)
	at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150)
	at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:124)
	at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
	at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
	at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
	at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:354)
	at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:181)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:636)
	at org.eclipse.equinox.launcher.Main.basicRun(Main.java:591)
	at org.eclipse.equinox.launcher.Main.run(Main.java:1450)
	at org.eclipse.equinox.launcher.Main.main(Main.java:1426)
Очень нужна ваша помощь... Благодарю заранее

Re: Bluetooth Проблемы с отладчиком!

Добавлено: 10 май 2014, 09:34
Mikhail_dev
А LogCat работает? А то какая-то странная ошибка. Может ошибка и есть, только её не выводят из-за этой ошибки.

Re: Bluetooth Проблемы с отладчиком!

Добавлено: 10 май 2014, 13:17
Dmitry91
Вчера запускал отладчик, в LogCat ничего не появлялось. Поэтому привел ошибку из ErrorLog. Сейчас перезагрузил комп, Eclipse, и LogCat ожил, выдал следующую ошибку
  • LogCat

Код: Выделить всё

05-10 10:10:54.243: E/Trace(652): error opening trace file: No such file or directory (2)
05-10 10:10:55.593: E/AndroidRuntime(652): FATAL EXCEPTION: main
05-10 10:10:55.593: E/AndroidRuntime(652): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.project_bt_allumerled/com.example.project_bt_allumerled.MainActivity}: java.lang.NullPointerException
05-10 10:10:55.593: E/AndroidRuntime(652): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
05-10 10:10:55.593: E/AndroidRuntime(652): 	at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
05-10 10:10:55.593: E/AndroidRuntime(652): 	at android.app.ActivityThread.access$600(ActivityThread.java:130)
05-10 10:10:55.593: E/AndroidRuntime(652): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
05-10 10:10:55.593: E/AndroidRuntime(652): 	at android.os.Handler.dispatchMessage(Handler.java:99)
05-10 10:10:55.593: E/AndroidRuntime(652): 	at android.os.Looper.loop(Looper.java:137)
05-10 10:10:55.593: E/AndroidRuntime(652): 	at android.app.ActivityThread.main(ActivityThread.java:4745)
05-10 10:10:55.593: E/AndroidRuntime(652): 	at java.lang.reflect.Method.invokeNative(Native Method)
05-10 10:10:55.593: E/AndroidRuntime(652): 	at java.lang.reflect.Method.invoke(Method.java:511)
05-10 10:10:55.593: E/AndroidRuntime(652): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
05-10 10:10:55.593: E/AndroidRuntime(652): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
05-10 10:10:55.593: E/AndroidRuntime(652): 	at dalvik.system.NativeStart.main(Native Method)
05-10 10:10:55.593: E/AndroidRuntime(652): Caused by: java.lang.NullPointerException
05-10 10:10:55.593: E/AndroidRuntime(652): 	at com.example.project_bt_allumerled.MainActivity$PlaceholderFragment.onCreateView(MainActivity.java:102)
05-10 10:10:55.593: E/AndroidRuntime(652): 	at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:829)
05-10 10:10:55.593: E/AndroidRuntime(652): 	at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1035)
05-10 10:10:55.593: E/AndroidRuntime(652): 	at android.app.BackStackRecord.run(BackStackRecord.java:635)
05-10 10:10:55.593: E/AndroidRuntime(652): 	at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1397)
05-10 10:10:55.593: E/AndroidRuntime(652): 	at android.app.Activity.performStart(Activity.java:5017)
05-10 10:10:55.593: E/AndroidRuntime(652): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2032)
05-10 10:10:55.593: E/AndroidRuntime(652): 	... 11 more

Re: Bluetooth Проблемы с отладчиком!

Добавлено: 10 май 2014, 16:22
Mikhail_dev
Не видите ошибку? Вот я вижу.

Re: Bluetooth Проблемы с отладчиком!

Добавлено: 10 май 2014, 19:04
Dmitry91
Ошибка в этой строке
BluetoothDevice device = bluetooth.getRemoteDevice("00:13:02:01:00:09");

Только, я не понимаю, что нужно исправить. Не могли бы Вы мне подсказать?

Re: Bluetooth Проблемы с отладчиком!

Добавлено: 10 май 2014, 23:17
Mikhail_dev
bluetooth, он не инициализирован.

Re: Bluetooth Проблемы с отладчиком!

Добавлено: 11 май 2014, 05:37
Dmitry91
Я думал, что bluetooth инициализируется с помощью этой строки:

Код: Выделить всё

//Мы хотим использовать тот bluetooth-адаптер, который задается по умолчанию 
            BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
Нашел также описание на сайте http://developer.android.com/reference/ ... evice.html
To get a BluetoothDevice, use BluetoothAdapter.getRemoteDevice(String) to create one representing a device of a known MAC address (which you can get through device discovery with BluetoothAdapter)
Извините, если я не понимаю элементарные вещи

Re: Bluetooth Проблемы с отладчиком!

Добавлено: 11 май 2014, 08:46
Mikhail_dev
Но ведь что-то у вас там null. И это что-то в принципе тут только bluetooth. Чтобы это проверить, напишите
if (bluetooth = null)
Log.d("log_tag", "bluetooth really nool");
Почему он null, это другой вопрос. Но я скажу что с блютусом дел не имел. Но думаю что все прекрасно гуглится.

Re: Bluetooth Проблемы с отладчиком!

Добавлено: 11 май 2014, 14:31
Dmitry91
Mikhail_dev, проблема решилась. При инициализации прописал:
private BluetoothAdapter bluetooth = null;
Но думаю, что ошибка была всего лишь в том, что отладчик не может работать с функцией bluetooth, а какой-либо защиты предусмотрено не было.
Большое Вам спасибо за помощь и потраченное время!