蓝牙应用在启动时崩溃

时间:2018-06-23 16:23:52

标签: android bluetooth

我绝对是android开发的初学者。我尝试制作蓝牙应用  并在启动时崩溃。该应用程序应搜索并连接到用户输入名称的特定设备。我已经捕获了所有异常,但我一无所知。任何帮助,将不胜感激。随附完整代码。 谢谢。

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.bluetooth.*;
import android.widget.*;
import android.util.*;
import android.content.*;
import android.view.View;
import java.io.*;
import java.util.*;


public class MainActivity extends AppCompatActivity {

public BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
UUID newUUID = UUID.randomUUID();
InputStream inStream;
byte[] buffer = new byte[1024];
public ArrayList<BluetoothDevice> devices = new ArrayList<>();
public TextView text = findViewById(R.id.textView);
public String incomingMessage;
private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        // When discovery finds a device
        if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
            final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);

            switch (state) {
                case BluetoothAdapter.STATE_OFF:
                    Log.d("", "onReceive: STATE OFF");
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                    Log.d("", "mBroadcastReceiver1: STATE TURNING OFF");
                    break;
                case BluetoothAdapter.STATE_ON:
                    Log.d("", "mBroadcastReceiver1: STATE ON");
                    break;
                case BluetoothAdapter.STATE_TURNING_ON:
                    Log.d("", "mBroadcastReceiver1: STATE TURNING ON");
                    break;
            }
        }
    }
};

private final BroadcastReceiver mBroadcastReceiver2 = new BroadcastReceiver() {

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

        if (BluetoothAdapter.ACTION_SCAN_MODE_CHANGED.equals(action)) {

            int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR);

            switch (mode) {
                //Device is in Discoverable Mode
                case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
                    Log.d("", "mBroadcastReceiver2: Discoverability Enabled.");
                    break;
                //Device not in discoverable mode
                case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
                    Log.d("", "mBroadcastReceiver2: Discoverability Disabled. Able to receive connections.");
                    break;
                case BluetoothAdapter.SCAN_MODE_NONE:
                    Log.d("", "mBroadcastReceiver2: Discoverability Disabled. Not able to receive connections.");
                    break;
                case BluetoothAdapter.STATE_CONNECTING:
                    Log.d("", "mBroadcastReceiver2: Connecting....");
                    break;
                case BluetoothAdapter.STATE_CONNECTED:
                    Log.d("", "mBroadcastReceiver2: Connected.");
                    break;
            }

        }
    }
};
private BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        Log.d("", "onReceive: ACTION FOUND.");

        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            devices.add(device);
            Log.d("", "onReceive: " + device.getName() + ": " + device.getAddress());
        }

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

        if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
            BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
                Log.d("", "BroadcastReceiver: BOND_BONDED.");
            }
            if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING) {
                Log.d("", "BroadcastReceiver: BOND_BONDING.");
            }
            if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) {
                Log.d("", "BroadcastReceiver: BOND_NONE.");
            }
        }
    }
};

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

public void onCLick(View button) {
    IntentFilter m4 = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    registerReceiver(mBroadcastReceiver4,m4);
    if(adapter==null)
    {
        Log.d("","Bluetooth is null");
        onDestroy();
    }
    EditText deviceName = findViewById(R.id.editText);
    String name = deviceName.getText().toString();
    BluetoothDevice targetDevice = null;
    if (!adapter.isEnabled()) {
        Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableIntent, 1);

        IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(mBroadcastReceiver1,BTIntent);

        Toast.makeText(getApplicationContext(),"BT TURNED ON",Toast.LENGTH_LONG).show();

        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
        startActivity(discoverableIntent);

        IntentFilter intentFilter = new IntentFilter(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
        registerReceiver(mBroadcastReceiver2,intentFilter);

    }
    Set<BluetoothDevice> paired_devices = adapter.getBondedDevices();
    Toast.makeText(getApplicationContext(),"GETTING BONDED DEVICES",Toast.LENGTH_LONG).show();
    if (paired_devices.size() > 0) {
        for (BluetoothDevice mdevice : paired_devices) {
            if (mdevice.getName().equals("name")) {
                Toast.makeText(getApplicationContext(),"FOUND DEVICE",Toast.LENGTH_LONG).show();
                targetDevice = mdevice;
                break;
            }
        }

    }
    else
    {
        Toast.makeText(getApplicationContext(),"SEARCHING DEVICES",Toast.LENGTH_LONG).show();
        if(adapter.isDiscovering())
            adapter.cancelDiscovery();
        adapter.startDiscovery();
        IntentFilter deviceFound = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mBroadcastReceiver3,deviceFound);
        for(BluetoothDevice mdevice:devices)
        {
            if(name.equalsIgnoreCase(mdevice.getName()))
            {
                targetDevice = mdevice;
            }
        }
        if(devices.size()==0)
        {
            Toast.makeText(getApplicationContext(),"NO DEVICE FOUND... QUITTING",Toast.LENGTH_LONG).show();
        }
    }

    BluetoothSocket mSocket = null;
    try {
        assert targetDevice != null;
        mSocket = targetDevice.createInsecureRfcommSocketToServiceRecord(newUUID);
    } catch (IOException | AssertionError e) {
        Toast.makeText(getApplicationContext(),"COULD NOT BE CONNECTED",Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }

    try {
        assert mSocket != null;
        mSocket.connect();
    } catch (IOException|AssertionError e) {
        e.printStackTrace();
        Toast.makeText(getApplicationContext(),"COULD NOT MAKE CONNECTION",Toast.LENGTH_LONG).show();
    }

    try {
        assert mSocket != null;
        inStream = mSocket.getInputStream();
    } catch (IOException|AssertionError | NullPointerException e) {
        Toast.makeText(getApplicationContext(),"PROBLEM CONNECTING",Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }
    while(true)
    {
        try {
            int bytes = inStream.read(buffer);
             incomingMessage = new String(buffer,0,bytes);

        } catch (IOException e) {
            e.printStackTrace();
            break;
        }
    }
    text.setText(incomingMessage);
    Toast.makeText(getApplicationContext(),"END OF PROGRAM",Toast.LENGTH_LONG).show();
}

}

[https://i.stack.imgur.com/3v3qI.png] [https://i.stack.imgur.com/42Ge5.png]

按下按钮后logcat崩溃的第二个链接

1 个答案:

答案 0 :(得分:0)

在渲染视图之前,您无法通过ID查找视图。如果您在全局级别编写findViewById,那么活动将尝试在设置布局之前加载该视图。

将您的findViewById代码放在setContentView()之后。

package in.ks.widgetClock.defaultClasses.webservice;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.bluetooth.*;
import android.widget.*;
import android.util.*;
import android.content.*;
import android.view.View;
import java.io.*;
import java.util.*;

import in.ks.widgetClock.R;


public class MainActivity extends AppCompatActivity {

    public BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    UUID newUUID = UUID.randomUUID();
    InputStream inStream;
    byte[] buffer = new byte[1024];
    public ArrayList<BluetoothDevice> devices = new ArrayList<>();
    public TextView text;

    public String incomingMessage;
    private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // When discovery finds a device
            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);

                switch (state) {
                    case BluetoothAdapter.STATE_OFF:
                        Log.d("", "onReceive: STATE OFF");
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF:
                        Log.d("", "mBroadcastReceiver1: STATE TURNING OFF");
                        break;
                    case BluetoothAdapter.STATE_ON:
                        Log.d("", "mBroadcastReceiver1: STATE ON");
                        break;
                    case BluetoothAdapter.STATE_TURNING_ON:
                        Log.d("", "mBroadcastReceiver1: STATE TURNING ON");
                        break;
                }
            }
        }
    };

    private final BroadcastReceiver mBroadcastReceiver2 = new BroadcastReceiver() {

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

            if (BluetoothAdapter.ACTION_SCAN_MODE_CHANGED.equals(action)) {

                int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR);

                switch (mode) {
                    //Device is in Discoverable Mode
                    case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
                        Log.d("", "mBroadcastReceiver2: Discoverability Enabled.");
                        break;
                    //Device not in discoverable mode
                    case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
                        Log.d("", "mBroadcastReceiver2: Discoverability Disabled. Able to receive connections.");
                        break;
                    case BluetoothAdapter.SCAN_MODE_NONE:
                        Log.d("", "mBroadcastReceiver2: Discoverability Disabled. Not able to receive connections.");
                        break;
                    case BluetoothAdapter.STATE_CONNECTING:
                        Log.d("", "mBroadcastReceiver2: Connecting....");
                        break;
                    case BluetoothAdapter.STATE_CONNECTED:
                        Log.d("", "mBroadcastReceiver2: Connected.");
                        break;
                }

            }
        }
    };
    private BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            Log.d("", "onReceive: ACTION FOUND.");

            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                devices.add(device);
                Log.d("", "onReceive: " + device.getName() + ": " + device.getAddress());
            }

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

            if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
                    Log.d("", "BroadcastReceiver: BOND_BONDED.");
                }
                if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING) {
                    Log.d("", "BroadcastReceiver: BOND_BONDING.");
                }
                if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) {
                    Log.d("", "BroadcastReceiver: BOND_NONE.");
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = findViewById(R.id.textView);
    }

    public void onCLick(View button) {
        IntentFilter m4 = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        registerReceiver(mBroadcastReceiver4,m4);
        if(adapter==null)
        {
            Log.d("","Bluetooth is null");
            onDestroy();
        }
        EditText deviceName = findViewById(R.id.editText);
        String name = deviceName.getText().toString();
        BluetoothDevice targetDevice = null;
        if (!adapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, 1);

            IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
            registerReceiver(mBroadcastReceiver1,BTIntent);

            Toast.makeText(getApplicationContext(),"BT TURNED ON",Toast.LENGTH_LONG).show();

            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
            startActivity(discoverableIntent);

            IntentFilter intentFilter = new IntentFilter(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
            registerReceiver(mBroadcastReceiver2,intentFilter);

        }
        Set<BluetoothDevice> paired_devices = adapter.getBondedDevices();
        Toast.makeText(getApplicationContext(),"GETTING BONDED DEVICES",Toast.LENGTH_LONG).show();
        if (paired_devices.size() > 0) {
            for (BluetoothDevice mdevice : paired_devices) {
                if (mdevice.getName().equals("name")) {
                    Toast.makeText(getApplicationContext(),"FOUND DEVICE",Toast.LENGTH_LONG).show();
                    targetDevice = mdevice;
                    break;
                }
            }

        }
        else
        {
            Toast.makeText(getApplicationContext(),"SEARCHING DEVICES",Toast.LENGTH_LONG).show();
            if(adapter.isDiscovering())
                adapter.cancelDiscovery();
            adapter.startDiscovery();
            IntentFilter deviceFound = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(mBroadcastReceiver3,deviceFound);
            for(BluetoothDevice mdevice:devices)
            {
                if(name.equalsIgnoreCase(mdevice.getName()))
                {
                    targetDevice = mdevice;
                }
            }
            if(devices.size()==0)
            {
                Toast.makeText(getApplicationContext(),"NO DEVICE FOUND... QUITTING",Toast.LENGTH_LONG).show();
            }
        }

        BluetoothSocket mSocket = null;
        try {
            assert targetDevice != null;
            mSocket = targetDevice.createInsecureRfcommSocketToServiceRecord(newUUID);
        } catch (IOException | AssertionError e) {
            Toast.makeText(getApplicationContext(),"COULD NOT BE CONNECTED",Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }

        try {
            assert mSocket != null;
            mSocket.connect();
        } catch (IOException|AssertionError e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(),"COULD NOT MAKE CONNECTION",Toast.LENGTH_LONG).show();
        }

        try {
            assert mSocket != null;
            inStream = mSocket.getInputStream();
        } catch (IOException|AssertionError | NullPointerException e) {
            Toast.makeText(getApplicationContext(),"PROBLEM CONNECTING",Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
        while(true)
        {
            try {
                int bytes = inStream.read(buffer);
                incomingMessage = new String(buffer,0,bytes);

            } catch (IOException e) {
                e.printStackTrace();
                break;
            }
        }
        text.setText(incomingMessage);
        Toast.makeText(getApplicationContext(),"END OF PROGRAM",Toast.LENGTH_LONG).show();
    }

}