Bluetooth в Android

1

В настоящее время я разрабатываю Sofware, использующий bluetooth для общения.

Вот мой класс bluetooth:

public class btClass extends Activity  implements View.OnClickListener
{
    private BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    private static final int REQUEST_ENABLE_BT = 10;
    private Context context;
    private btReceiver mReceiver = new btReceiver();
    private String[] result = new String[]{""};
    private Activity hangar;

    public btClass()
    {
        if (!this.adapter.isEnabled())
        {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

            startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);

            int result = 0;
            onActivityResult(REQUEST_ENABLE_BT, result, enableBtIntent);
            if(result != RESULT_OK)
            {
                String exception = "Bluetooth failure!\r\nEnabling bluetooth adapter failed!";

                AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this.context);
                dlgAlert.setMessage(exception);
                dlgAlert.setTitle("Hangar error");
                dlgAlert.setPositiveButton("OK", null);
                dlgAlert.setCancelable(true);
                dlgAlert.create().show();
            }
        }
    }

    @Override
    protected void onCreate(Bundle intent)
    {
        super.onCreate(intent);

        this.hangar = this.getParent();

        this.context = this.getApplicationContext();
    }

    public void onClick(View v) 
    {
        doDiscovery();      
    }

    private void doDiscovery()
    {
        if(this.adapter.isDiscovering())
            this.adapter.cancelDiscovery();

        if(!this.adapter.startDiscovery())
        {
            String exception = "Bluetooth failure!\r\nDiscovering bluetooth devices failed!";

            AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this.context);
            dlgAlert.setMessage(exception);
            dlgAlert.setTitle("Hangar error");
            dlgAlert.setPositiveButton("OK", null);
            dlgAlert.setCancelable(true);
            dlgAlert.create().show();
        }

        // Register the BroadcastReceiver
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        try
        {
            this.registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestr
        }
        catch(Exception e)
        {
            String exception = "'registerReceiver' threw Exception of type '" + e.getMessage();
            StackTraceElement[] trace = e.getStackTrace();
            for(int i = 0; i < trace.length; i++)
                exception = exception + "\r\n" + trace[i];

            AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);
            dlgAlert.setMessage(exception);
            dlgAlert.setTitle("Hangar error");
            dlgAlert.setPositiveButton("OK", null);
            dlgAlert.setCancelable(true);
            dlgAlert.create().show();
        }

        while(this.adapter.isDiscovering())
            ;

        unregisterReceiver(this.mReceiver);

        result = new String[]{""};
        if(this.mReceiver != null)
            result = this.mReceiver.foundDevicesNames();
    }

    public String[] getBluetoothDevices()
    {       
        return result;
    }
}

Теперь проблема в том, что я перехватываю "nullPointerException", когда я вызываю startActivityForResult в строке 16.

Где моя вина?

Приветствие Хенрика

EDIT: новый код:

package de.schweigstill.hangar;

import android.bluetooth.*;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.app.Activity;
import android.app.AlertDialog;

public class btClass extends Activity  implements View.OnClickListener
{
    private BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    private static final int REQUEST_ENABLE_BT = 10;
    private Context context;
    private btReceiver mReceiver = new btReceiver();
    private String[] result = new String[]{""};
    private HangarActivity hangar;

    public btClass(Context context)
    {
        super();
    }

    @Override
    public void onCreate(Bundle intent)
    {
        super.onCreate(intent);

        this.hangar = (HangarActivity)this.getParent();

        this.context = this.getApplicationContext();
    }

    public void onClick(View v) 
    {
        if (!this.adapter.isEnabled())
        {
            Intent enableBtIntent = new intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);

            int result = 0;
            onActivityResult(REQUEST_ENABLE_BT, result, enableBtIntent);
            if(result != RESULT_OK)
            {
                String exception = "Bluetooth failure!\r\nEnabling bluetooth adapter failed!";

                AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this.context);
                dlgAlert.setMessage(exception);
                dlgAlert.setTitle("Hangar error");
                dlgAlert.setPositiveButton("OK", null);
                dlgAlert.setCancelable(true);
                dlgAlert.create().show();
            }
        }

        doDiscovery();      
    }

    private void doDiscovery()
    {
        try
        {           
            if(this.adapter.isDiscovering())
                this.adapter.cancelDiscovery();

            if(!this.adapter.startDiscovery())
            {
                String exception = "Bluetooth failure!\r\nDiscovering bluetooth devices failed!";

                AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this.context);
                dlgAlert.setMessage(exception);
                dlgAlert.setTitle("Hangar error");
                dlgAlert.setPositiveButton("OK", null);
                dlgAlert.setCancelable(true);
                dlgAlert.create().show();
            }

            // Register the BroadcastReceiver
            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

            this.registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestr

            while(this.adapter.isDiscovering())
                ;

            unregisterReceiver(this.mReceiver);

            result = new String[]{""};
            if(this.mReceiver != null)
            {
                result = this.mReceiver.foundDevicesNames();
                for(int i = 0; i < result.length; i++)
                    this.hangar.aAd.add(result[i]);
            }
        }
        catch(Exception e)
        {
            String exception = "In 'doDiscovery()' has an Exception of type '" + e.toString() + "' been thrown \r\n Trace:";//.getMessage();
            StackTraceElement[] trace = e.getStackTrace();
            for(int i = 0; i < trace.length; i++)
                exception = exception + "\r\n" + trace[i];

            AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);
            dlgAlert.setMessage(exception);
            dlgAlert.setTitle("Hangar error");
            dlgAlert.setPositiveButton("OK", null);
            dlgAlert.setCancelable(true);
            dlgAlert.create().show();
        }
    }

    public String[] getBluetoothDevices()
    {       
        return result;
    }
}
Теги:
bluetooth
nullpointerexception

2 ответа

1

Каков код класса btReceiver?

Попробуй это:

Удалите следующую строку из своего btClass:

private btReceiver mReceiver = new btReceiver();

Создайте BroadcastReceiver, как это в вашем btClass:

 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // If it already paired, skip it, because it been listed already
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                }
            // When discovery is finished, change the Activity title
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setProgressBarIndeterminateVisibility(false);
                setTitle(R.string.select_device);
                if (mNewDevicesArrayAdapter.getCount() == 0) {
                    String noDevices = getResources().getText(R.string.none_found).toString();
                    mNewDevicesArrayAdapter.add(noDevices);
                }
            }
        }
    };
0

Я думаю, проблема в том, что вы пытаетесь вызвать активность из конструктора. Я бы не советовал вводить логику в конструктор Activity.

Вы можете переместить этот код в метод lifecycle onCreate() или лучше позвонить, когда произойдет определенное действие (например, нажатие кнопки и т.д.),

  • 0
    Здравствуйте, Алексей, я переместил упомянутый код, но я получаю исключение nullPointerException для this.registerReceiver в методе doDiscovery (). Что еще не так? Приветствует хенрика
  • 0
    Привет Хенрик. Из выдержки из кода не очевидно, почему вы можете получить NullPointerException в этой строке. И я предполагаю, что фрагмент кода не актуален. Не могли бы вы предоставить последний код и трассировку стека исключений.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню