如何在另一个活动中使用蓝牙传输数据?

时间:2016-12-29 20:03:02

标签: java android bluetooth

我是java编程的新手,我遇到了问题。我正在使用蓝牙工作在arduino汽车的控制器。该车有3种运行模式:测试自动手动。我制作了一个MainActivity,其布局包含每个模式的3个按钮和一个用于蓝牙连接的按钮 Connect 。在另一个活动 SecondActivity 中有另一个布局,其中包含用于控制汽车方向和速度的按钮,但令人惊讶的是 mBluetooth.write 无效。

这是MainActivity:

public class MainActivity extends AppCompatActivity {

ImageButton test, manual,connect;
Button back;

private BluetoothAdapter mbluetoothAdapter;
protected AlertDialog.Builder builder;
ConnectThread mBluetooth = new ConnectThread();
String mBluetoothName = "";
String mBluetoothAdress = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    final Context context = this;
    //final LayoutInflater factory = getLayoutInflater();
    //final View textEntryView = factory.inflate(R.layout.activity_main);
    builder = new AlertDialog.Builder(this);
    mbluetoothAdapter = BluetoothAdapter.getDefaultAdapter();


    connect = (ImageButton) findViewById(R.id.connect);
    test = (ImageButton) findViewById(R.id.test);
    manual = (ImageButton) findViewById(R.id.manual);


    test.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(context,SecondActivity.class );
            context.startActivity(intent);
        }

    });
    manual.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(context,SecondActivity.class );
            context.startActivity(intent);
        }

    });
    connect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!mbluetoothAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivity(enableBtIntent);
            } else {
                if (!mBluetooth.mBluetoothAddress.equals("")) {//if another connection is already exits then close it first
                    stopAllActivities();
                } else {
                    try {
                        Intent serverIntent = new Intent(MainActivity.this, DeviceListActivity.class);
                        startActivityForResult(serverIntent, Helper.REQUEST_CONNECT_DEVICE);
                    } catch (Exception e) {
                        showToast(getString(R.string.errorOccured) + ": " + e.getMessage());
                        e.printStackTrace();
                    }
                }
            }
        }
    });
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case Helper.REQUEST_CONNECT_DEVICE:
            if (resultCode == Activity.RESULT_OK) {
                mBluetoothName = data.getExtras().getString(Helper.EXTRA_BLUETOOTH_NAME);
                mBluetoothAdress = data.getExtras().getString(Helper.EXTRA_BLUETOOTH_ADDRESS);

                // setBluetoothInfo();
                showToast(R.string.connectedDevice + mBluetoothName);

                if (!mBluetoothAdress.equals("")) {
                    if (!mBluetooth.connect(mBluetoothAdress)){


                    }
                }
            }
            break;
    }
}

private void showToast(String message) {
    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}

private void stopAllActivities() {
    mBluetooth.write("S"); //send Stop Signal before it closes the connection

    mBluetooth.mBluetoothAddress = ""; // reset address
    mBluetooth.close();//close Connection

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    //getMenuInflater().inflate(R.menu.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();

    return super.onOptionsItemSelected(item);
}

@Override
public void onPause() {
    if (mbluetoothAdapter != null) {
        if (mbluetoothAdapter.isDiscovering()) {
            mbluetoothAdapter.cancelDiscovery();
        }
    }
    super.onPause();
}}

这是SecondActivity:

public class SecondActivity extends AppCompatActivity {
final Context context = this;
Button back;
ImageButton btnup, btndown, btnright, btnleft;
ConnectThread mBluetooth = new ConnectThread();//??????

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

    back = (Button) findViewById(R.id.back);
    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(context, MainActivity.class);
            context.startActivity(intent);
        }

    });

    btnup = (ImageButton) findViewById(R.id.btnup);
    btndown = (ImageButton) findViewById(R.id.btndown);
    btnleft = (ImageButton) findViewById(R.id.btnleft);
    btnright = (ImageButton) findViewById(R.id.btnright);
    final TextView direction = (TextView) findViewById(R.id.text_direction);
    final TextView steering = (TextView) findViewById(R.id.steering_direction);
    final Chronometer chronometer = (Chronometer) findViewById(R.id.chronometer);

    btndown.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                mBluetooth.write("2");
                direction.setText(R.string.Backwards);
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                mBluetooth.write("x");
                direction.setText(R.string.blank);
            }


            return false;

        }
    });
    btnup.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                mBluetooth.write("8");
                direction.setText(R.string.Forward);
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                mBluetooth.write("z");
                direction.setText(R.string.blank);
            }


            return false;

        }
    });

    btnright.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                mBluetooth.write("6");
                steering.setText(R.string.Right);
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                mBluetooth.write("c");
                steering.setText(R.string.none);
            }


            return false;

        }
    });
    btnleft.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                mBluetooth.write("4");
                steering.setText(R.string.Left);
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                mBluetooth.write("v");
                steering.setText(R.string.none);
            }


            return false;

        }
    });


}}

我在一项活动中测试了蓝牙连接和按钮的代码并且工作正常

2 个答案:

答案 0 :(得分:0)

这可能是一种锻炼。 在MainActivity中使ConnectThread实例mBluetooth为静态。现在,这将作为类字段,并将保留其实例,直到应用程序的整个生命周期。

以下是代码:

<强> MainActivity.java

public class MainActivity extends AppCompatActivity {

ImageButton test, manual,connect;
Button back;

private BluetoothAdapter mbluetoothAdapter;
protected AlertDialog.Builder builder;
//Static instance declaration
public static ConnectThread mBluetooth;
String mBluetoothName = "";
String mBluetoothAdress = "";

//Static block to initialise static instance
static{
    mBluetooth=new ConnectThread();
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    final Context context = this;
    //final LayoutInflater factory = getLayoutInflater();
    //final View textEntryView = factory.inflate(R.layout.activity_main);
    builder = new AlertDialog.Builder(this);
    mbluetoothAdapter = BluetoothAdapter.getDefaultAdapter();


    connect = (ImageButton) findViewById(R.id.connect);
    test = (ImageButton) findViewById(R.id.test);
    manual = (ImageButton) findViewById(R.id.manual);


    test.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(context,SecondActivity.class );
            context.startActivity(intent);
        }

    });
    manual.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(context,SecondActivity.class );
            context.startActivity(intent);
        }

    });
    connect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!mbluetoothAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivity(enableBtIntent);
            } else {
                if (!mBluetooth.mBluetoothAddress.equals("")) {//if another connection is already exits then close it first
                    stopAllActivities();
                } else {
                    try {
                        Intent serverIntent = new Intent(MainActivity.this, DeviceListActivity.class);
                        startActivityForResult(serverIntent, Helper.REQUEST_CONNECT_DEVICE);
                    } catch (Exception e) {
                        showToast(getString(R.string.errorOccured) + ": " + e.getMessage());
                        e.printStackTrace();
                    }
                }
            }
        }
    });
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case Helper.REQUEST_CONNECT_DEVICE:
            if (resultCode == Activity.RESULT_OK) {
                mBluetoothName = data.getExtras().getString(Helper.EXTRA_BLUETOOTH_NAME);
                mBluetoothAdress = data.getExtras().getString(Helper.EXTRA_BLUETOOTH_ADDRESS);

                // setBluetoothInfo();
                showToast(R.string.connectedDevice + mBluetoothName);

                if (!mBluetoothAdress.equals("")) {
                    if (!mBluetooth.connect(mBluetoothAdress)){


                    }
                }
            }
            break;
    }
}

private void showToast(String message) {
    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}

private void stopAllActivities() {
    mBluetooth.write("S"); //send Stop Signal before it closes the connection

    mBluetooth.mBluetoothAddress = ""; // reset address
    mBluetooth.close();//close Connection

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    //getMenuInflater().inflate(R.menu.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();

    return super.onOptionsItemSelected(item);
}

@Override
public void onPause() {
    if (mbluetoothAdapter != null) {
        if (mbluetoothAdapter.isDiscovering()) {
            mbluetoothAdapter.cancelDiscovery();
        }
    }
    super.onPause();
}}

<强> SecondActivity.java

public class SecondActivity extends AppCompatActivity {
final Context context = this;
Button back;
ImageButton btnup, btndown, btnright, btnleft;
//Declare a static reference from MainActivity class
ConnectThread mBluetooth = MainActivity.mBluetooth;

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

    back = (Button) findViewById(R.id.back);
    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(context, MainActivity.class);
            context.startActivity(intent);
        }

    });

    btnup = (ImageButton) findViewById(R.id.btnup);
    btndown = (ImageButton) findViewById(R.id.btndown);
    btnleft = (ImageButton) findViewById(R.id.btnleft);
    btnright = (ImageButton) findViewById(R.id.btnright);
    final TextView direction = (TextView) findViewById(R.id.text_direction);
    final TextView steering = (TextView) findViewById(R.id.steering_direction);
    final Chronometer chronometer = (Chronometer) findViewById(R.id.chronometer);

    btndown.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                mBluetooth.write("2");
                direction.setText(R.string.Backwards);
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                mBluetooth.write("x");
                direction.setText(R.string.blank);
            }


            return false;

        }
    });
    btnup.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                mBluetooth.write("8");
                direction.setText(R.string.Forward);
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                mBluetooth.write("z");
                direction.setText(R.string.blank);
            }


            return false;

        }
    });

    btnright.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                mBluetooth.write("6");
                steering.setText(R.string.Right);
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                mBluetooth.write("c");
                steering.setText(R.string.none);
            }


            return false;

        }
    });
    btnleft.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                mBluetooth.write("4");
                steering.setText(R.string.Left);
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                mBluetooth.write("v");
                steering.setText(R.string.none);
            }


            return false;

        }
    });


}}

希望这会有所帮助。祝你好运!

答案 1 :(得分:0)

阅读我在第二项活动中找到的代码:

ConnectThread mBluetooth = new ConnectThread(); //??????

这意味着您要创建另一个与MainAvtivity中创建的对象不同的对象,因此此新对象尚未连接。这解释了为什么如果在同一个MainActivity中使用相同的对象,则方法写入工作。

我建议您将此对象设为静态并在secondActivity中使用它。所以删除

ConnectThread mBluetooth = new ConnectThread(); //??????

在MainActivity中制作静态mBluetooth对象

Static ConnectThread mBluetooth = new ConnectThread();

我们需要在SecondActivity中使用

编写内容
MainAcivity.mBluetooth.write(data);

不建议所有make对象静态,但如果它不是一个大的应用程序是一个很好的解决方法。

希望这对你有所帮助!