我希望像主要活动这样的另一个类从蓝牙接收数据,我无法切换到另一个活动

时间:2016-11-13 19:23:21

标签: java android multithreading android-studio android-bluetooth

我想要与Main活动相同的活动,我只是希望另一个活动在切换到另一个活动后也应该收到来自蓝牙的相同数据但在切换到另一个活动时发生连接失败并显示:

> W/BluetoothAdapter: getBluetoothService() called with no
> BluetoothManagerCallback I/Choreographer: Skipped 52 frames!  The
> application may be doing too much work on its main thread.

请帮忙。

DeviceListActivity

public class DeviceListActivity extends Activity {
// Debugging for LOGCAT
private static final String TAG = "DeviceListActivity";
private static final boolean D = true;


// declare button for launching website and textview for connection status
//Button tlbutton;
TextView textView1;

// EXTRA string to send on to mainactivity
public static String EXTRA_DEVICE_ADDRESS = "device_address";

// Member fields
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;

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

@Override
public void onResume()
{
    super.onResume();

    checkBTState();

    textView1 = (TextView) findViewById(R.id.connecting);
    textView1.setTextSize(40);
    textView1.setText(" ");

    // Initialize array adapter for paired devices
    mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);

    // Find and set up the ListView for paired devices
    ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
    pairedListView.setAdapter(mPairedDevicesArrayAdapter);
    pairedListView.setOnItemClickListener(mDeviceClickListener);

    // Get the local Bluetooth adapter
    mBtAdapter = BluetoothAdapter.getDefaultAdapter();

    // Get a set of currently paired devices and append to 'pairedDevices'
    Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();

    // Add previosuly paired devices to the array
    if (pairedDevices.size() > 0) {
        findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);//make title viewable
        for (BluetoothDevice device : pairedDevices) {
            mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
        }
    } else {
        String noDevices = getResources().getText(R.string.none_paired).toString();
        mPairedDevicesArrayAdapter.add(noDevices);
    }
}

// Set up on-click listener for the list (nicked this - unsure)
private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {

        textView1.setText("Connecting...");
        // Get the device MAC address, which is the last 17 chars in the View
        String info = ((TextView) v).getText().toString();
        String address = info.substring(info.length() - 17);

        // Make an intent to start next activity while taking an extra which is the MAC address.
        Intent i = new Intent(DeviceListActivity.this, MainActivity.class);
        i.putExtra(EXTRA_DEVICE_ADDRESS, address);
        startActivity(i);
    }
};

private void checkBTState() {
    // Check device has Bluetooth and that it is turned on
    mBtAdapter=BluetoothAdapter.getDefaultAdapter(); // CHECK THIS OUT THAT IT WORKS!!!
    if(mBtAdapter==null) {
        Toast.makeText(getBaseContext(), "Device does not support Bluetooth", Toast.LENGTH_SHORT).show();
    } else {
        if (mBtAdapter.isEnabled()) {
            Log.d(TAG, "...Bluetooth ON...");
        } else {
            //Prompt user to turn on Bluetooth
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);

        }
    }
}
}

MainActivity

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

Button btnOn, btnOff;
TextView txtString, txtStringLength, sensorView0, sensorView1, sensorView2, sensorView3;
Handler bluetoothIn;

final int handlerState = 0;                      //used to identify handler message
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder recDataString = new StringBuilder();

 public static ConnectedThread mConnectedThread;

// SPP UUID service - this should work for most devices
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

// String for MAC address
public static String address;

public static String address2;

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



    setContentView(R.layout.activity_main);

    btnOn = (Button) findViewById(R.id.buttonOn);
    btnOff = (Button) findViewById(R.id.buttonOff);
    txtString = (TextView) findViewById(R.id.txtString);
    txtStringLength = (TextView) findViewById(R.id.testView1);
    sensorView0 = (TextView) findViewById(R.id.sensorView0);
    sensorView1 = (TextView) findViewById(R.id.sensorView1);
    sensorView2 = (TextView) findViewById(R.id.sensorView2);
    sensorView3 = (TextView) findViewById(R.id.sensorView3);



    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
   // setSupportActionBar(toolbar);


    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
 drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);


    bluetoothIn = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == handlerState) {                                     //if message is what we want
                String readMessage = (String) msg.obj;                         // msg.arg1 = bytes from connect thread
                recDataString.append(readMessage);                          //keep appending to string until ~
                int endOfLineIndex = recDataString.indexOf("~");                    // determine the end-of-line
                if (endOfLineIndex > 0) {                                           // make sure there data before ~
                    String dataInPrint = recDataString.substring(0, endOfLineIndex);    // extract string
                    txtString.setText("Data Received = " + dataInPrint);
                    int dataLength = dataInPrint.length();                          //get length of data received
                    txtStringLength.setText("String Length = " + String.valueOf(dataLength));

                    if (recDataString.charAt(0) == '#')                             //if it starts with # we know it is what we are looking for
                    {
                        String sensor0 = recDataString.substring(1, 5);             //get sensor value from string between indices 1-5
                        String sensor1 = recDataString.substring(6, 10);            //same again...
                        String sensor2 = recDataString.substring(11, 15);
                        String sensor3 = recDataString.substring(16, 20);

                        sensorView0.setText(" Sensor 0 Voltage = " + sensor0 + "V");    //update the textviews with sensor values
                        sensorView1.setText(" Sensor 1 Voltage = " + sensor1 + "V");
                        sensorView2.setText(" Sensor 2 Voltage = " + sensor2 + "V");
                        sensorView3.setText(" Sensor 3 Voltage = " + sensor3 + "V");
                    }
                    recDataString.delete(0, recDataString.length());                    //clear all string data
                    // strIncom =" ";
                    dataInPrint = " ";
                }
            }
        }
    };

    btAdapter = BluetoothAdapter.getDefaultAdapter();       // get Bluetooth adapter
    checkBTState();


    // Set up onClick listeners for buttons to send 1 or 0 to turn on/off LED
    btnOff.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            mConnectedThread.write("0");    // Send "0" via Bluetooth
            Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
        }
    });

    btnOn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            mConnectedThread.write("1");    // Send "1" via Bluetooth
            Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
        }
    });
}



private void checkBTState() {

    if(btAdapter==null) {
        Toast.makeText(getBaseContext(), "Device does not support bluetooth", Toast.LENGTH_LONG).show();
    } else {
        if (btAdapter.isEnabled()) {
        } else {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);
        }
    }
}


@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public void onResume() {
    super.onResume();

    //Get MAC address from DeviceListActivity via intent
    Intent intent = getIntent();

    //Get the MAC address from the DeviceListActivty via EXTRA
    address = intent.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);

    //create device and set the MAC address
    BluetoothDevice device = btAdapter.getRemoteDevice(address);

    try {
        btSocket = createBluetoothSocket(device);
    } catch (IOException e) {
        Toast.makeText(getApplicationContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
    }
    // Establish the Bluetooth socket connection.
    try
    {
        btSocket.connect();
    } catch (IOException e) {
        try
        {
            btSocket.close();
        } catch (IOException e2)
        {
            //insert code to deal with this
        }
    }
    mConnectedThread = new ConnectedThread(btSocket);
    mConnectedThread.start();

    //I send a character when resuming.beginning transmission to check device is connected
    //If it is not an exception will be thrown in the write method and finish() will be called
    mConnectedThread.write("x");
}


public void onPause()
{
    super.onPause();
    try
    {
        //Don't leave Bluetooth sockets open when leaving activity
        btSocket.close();
    } catch (IOException e2) {
        //insert code to deal with this
    }
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            try {
                mConnectedThread.wait();
            } catch (Exception e) {

            }

        }
    });
}



@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;
}

private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {

    return  device.createRfcommSocketToServiceRecord(BTMODULEUUID);
    //creates secure outgoing connecetion with BT device using UUID
}





@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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}






@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_additem) {
        Intent addIntent = new Intent(getApplicationContext(),AddActivity2.class);
        address2 = address;
        startActivity(addIntent);
        try {

        }catch (Exception e){}


    } else if (id == R.id.nav_viewItems) {

    } else if (id == R.id.nav_favourite) {

    } else if (id == R.id.nav_sensors) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}




//create new class for connect thread
 class ConnectedThread extends Thread {
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    //creation of the connect thread
    public ConnectedThread(BluetoothSocket socket) {
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        try {
            //Create I/O streams for connection
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }


    public void run() {
        byte[] buffer = new byte[256];
        int bytes;

        // Keep looping to listen for received messages
        while (true) {
            try {
                bytes = mmInStream.read(buffer);            //read bytes from input buffer
                String readMessage = new String(buffer, 0, bytes);
                // Send the obtained bytes to the UI Activity via handler
                bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }
    //write method
    public void write(String input) {
        byte[] msgBuffer = input.getBytes();           //converts entered String into bytes
        try {
            mmOutStream.write(msgBuffer);                //write bytes over BT connection via outstream
        } catch (IOException e) {
            //if you cannot write, close the application
            Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
            finish();

        }
    }
}
}

0 个答案:

没有答案