我已经实现了一个通过蓝牙连接传感器并从中接收数据的应用程序。我想传递两个活动。第一个是ConnectionScreen
,其中是连接逻辑,第二个是ActivityTypes
,我想从第一个“跳转”。
我试图在Handler
ConnectionScreen
BroadcastReceiver
中尝试这样做,但我不知道如何...我还发现必须使用public class ConnectionScreen extends Activity {
private static final String TAG = "DeviceListActivity";
private static final boolean D = false;
private static ArrayList<ActivityEntity> ActivityEntityList = new ArrayList<ActivityEntity>();
private static final int REQUEST_ENABLE_BT = 2;
private static ArrayList<CustomizedBluetoothDevice> mDeviceList;
private static ListView mListViewDeviceList;
private Button mButtonStartScan;
private int currentPosition;
private static String mCurrentDeviceAddress = null;
private static String mConnectedDeviceName = null;
private static ConnectThread mConnectThread;
public static BluetoothAdapter mBluetoothAdapter = null;
private static BluetoothMeterService mChatService = null;
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
public static DeviceListAdapter mBaseAdapter;
private static Context context;
public static void updateUI() {
mBaseAdapter = new DeviceListAdapter(context, mDeviceList, R.layout.macaddr1);
mListViewDeviceList.setAdapter(mBaseAdapter);
}
private void getPairedDevice() {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
CustomizedBluetoothDevice customizedDevice = new CustomizedBluetoothDevice(
device);
if(customizedDevice.getAddress().equals(mCurrentDeviceAddress)){
customizedDevice.setStatus(Constants.STATE_CONNECTED);
}
mDeviceList.add(customizedDevice);
}
}
}
private void initialization() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
finish();
return;
}
mBaseAdapter = new DeviceListAdapter(ConnectionScreen.this, mDeviceList, R.layout.macaddr1);
mListViewDeviceList = (ListView) findViewById(R.id.listview_devicelist);
mListViewDeviceList.setAdapter(mBaseAdapter);
mListViewDeviceList.setOnItemClickListener(mDeviceClickListener);
mButtonStartScan = (Button) findViewById(R.id.btn_startScan);
mButtonStartScan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setup();
doDiscovery();
}
});
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
this.registerReceiver(mReceiver, filter);
}
public static void startConnect(CustomizedBluetoothDevice device) {
launchActivity(context, device.getAddress());
}
// The on-click listener for all devices in the ListViews
// It will auto-connect with the device.
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int position, long arg3) {
// Cancel discovery because it's costly and we're about to connect
mBluetoothAdapter.cancelDiscovery();
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mDeviceList.get(position).getAddress());
currentPosition = position;
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
unpairDevice(device);
}
else {
pairDevice(device);
}
}
};
/**
* Start device discover with the BluetoothAdapter
*/
private void doDiscovery() {
// If we're already discovering, stop it
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mBluetoothAdapter.startDiscovery();
}
private void pairDevice(BluetoothDevice device) {
try {
if (D)
Log.d(TAG, "Start Pairing...");
Method m = device.getClass().getMethod("createBond", (Class[]) null);
m.invoke(device, (Object[]) null);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
private void unpairDevice(BluetoothDevice device) {
try {
Method m = device.getClass()
.getMethod("removeBond", (Class[]) null);
m.invoke(device, (Object[]) null);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
// The BroadcastReceiver that listens for discovered devices and
// changes the title when discovery is finished
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's already paired, skip it, because it's been listed
// already
CustomizedBluetoothDevice mDevice = new CustomizedBluetoothDevice(
device);
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
if (mDeviceList.contains(mDevice) == false) {
mDeviceList.add(mDevice);
updateUI();
}
}
}
// When the device bond state changed.
else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
int prevBondState = intent.getIntExtra(
BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, -1);
int bondState = intent.getIntExtra(
BluetoothDevice.EXTRA_BOND_STATE, -1);
if (prevBondState == BluetoothDevice.BOND_BONDED
&& bondState == BluetoothDevice.BOND_NONE) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (currentPosition != -1
&& currentPosition < mDeviceList.size()) {
CustomizedBluetoothDevice mDevice = mDeviceList
.get(currentPosition);
if (device.getAddress().compareTo(mDevice.getAddress()) == 0) {
mDevice.setStatus(0);
updateUI();
pairDevice(device);
}
}
} else if (prevBondState == BluetoothDevice.BOND_BONDING
&& bondState == BluetoothDevice.BOND_BONDED) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (currentPosition != -1
&& currentPosition < mDeviceList.size()) {
CustomizedBluetoothDevice mDevice = mDeviceList .get(currentPosition);
if (device.getAddress().equals(mDevice.getAddress())) {
updateUI();
startConnect(mDevice);
}
}
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_list);
context = this; initialization();
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, ConnectionScreen.REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
} else {
setup();
}
}
@Override
protected void onStart() {
super.onStart();
}
private void setup() {
mDeviceList = new ArrayList<CustomizedBluetoothDevice>();
currentPosition = -1;
getPairedDevice();
updateUI();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ConnectionScreen.REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setup();
} else {
// User did not enable Bluetooth or an error occured
if (D)
Log.d(TAG, "BT not enabled");
Toast.makeText(this, R.string.bt_not_enabled_leaving,Toast.LENGTH_SHORT).show();
finish();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
// Make sure we're not doing discovery anymore
if (mBluetoothAdapter != null) {
mBluetoothAdapter.cancelDiscovery();
}
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}
public static void launchActivity(Context context, String deviceAddress){
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mCurrentDeviceAddress = deviceAddress;
mChatService = new BluetoothMeterService(context, mHandler);
connectDevice();
if (mChatService != null) {
if (mChatService.getState() == Constants.STATE_NONE) {
mChatService.start();
}
}
}
// Automatically try to connect with the known mac address;
private static class ConnectThread extends Thread {
private final BluetoothDevice device;
public ConnectThread(BluetoothDevice d) {
this.device = d;
}
public void run() {
while (mConnectThread == Thread.currentThread()) {
if (mChatService.getState() == Constants.STATE_CONNECTED) {
Log.e(TAG, "STATE_CONNECTED");
break;
} else if (mChatService.getState() == Constants.STATE_CONNECTING) {
try {
Log.e(TAG, "STATE_CONNECTING");
mChatService.connect(device);
} catch (Exception e) {
}
} else
try { Log.e(TAG, "STATE_DISCONECTED");
mChatService.start();
Thread.sleep(3000);
} catch (Exception e) {
Thread.currentThread().interrupt();
}
}
}
}
// create the bluetooth device object, and try to connect with it
// consistantly and automatically.
private static void connectDevice() {
if (mCurrentDeviceAddress == null) {
Toast.makeText(context, "Bluetooth MAC address is not assigned.",
Toast.LENGTH_SHORT).show();
return;
}
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mCurrentDeviceAddress);
mConnectThread = new ConnectThread(device);
mConnectThread.start();
}
// The Handler that gets information back from the BluetoothMeterService
private static final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.e(TAG, msg.toString());
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case Constants.STATE_CONNECTED:
Log.e(TAG, "handler - STATE_CONNECTED");
for(CustomizedBluetoothDevice device : mDeviceList){
if(device.getAddress() == mCurrentDeviceAddress){
device.setStatus(Constants.STATE_CONNECTED);
}
}
updateUI();
break;
case Constants.STATE_CONNECTING:
Log.e(TAG, "handler - STATE_CONNECTING");
for(CustomizedBluetoothDevice device : mDeviceList){
if(device.getAddress() == mCurrentDeviceAddress){
device.setStatus(Constants.STATE_CONNECTING);
}
}
updateUI();
break;
case Constants.STATE_NONE:
Log.e(TAG, "handler - STATE_NONE");
for(CustomizedBluetoothDevice device : mDeviceList){
if(device.getAddress() == mCurrentDeviceAddress){
device.setStatus(Constants.STATE_NONE);
}
}
updateUI();
break;
case Constants.STATE_DISCONNECTING:
Log.e(TAG, "handler - STATE_DISCONNECTING");
for(CustomizedBluetoothDevice device : mDeviceList){
if(device.getAddress() == mCurrentDeviceAddress){
device.setStatus(Constants.STATE_DISCONNECTING);
}
}
updateUI();
break;
}
break;
case MESSAGE_WRITE:
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
Log.e(TAG, "handler - MESSAGE_READ " + readMessage);
HrmReading hrm = new HrmReading( readBuf );
ActivityEntity activity = hrm.getAllInfo();
activity.setStartDateTime(null);
String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
activity.setCurrentDateTime(timeStamp);
activity.setEndDateTime(null);
ActivityEntityList.add(activity);
Intent i = new Intent(ConnectionScreen.context,ActivityTypes.class);
startActivity(i);
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// TODO I think here must be implemented the link to ActivityTypes
break;
case MESSAGE_DEVICE_NAME:
Log.e(TAG, "handler - MESSAGE_READ " + MESSAGE_DEVICE_NAME);
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
break;
case MESSAGE_TOAST:
Log.e(TAG, "handler - MESSAGE_READ " + MESSAGE_TOAST);
break;
}
}
};
}
来完成同样的问题。
以下是这两项活动中更重要的代码:
public class ActivityTypes extends Activity {
String[] activities = {"Aerobics", "Cycling", "Running", "Strength", "Walking",};
int[] total_images = {R.drawable.aerobics, R.drawable.cycling, R.drawable.running,
R.drawable.strength, R.drawable.walking};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen);
Spinner spinnerOfActivities = (Spinner) findViewById(R.id.spinner_activities);
spinnerOfActivities.setAdapter(new MyAdapter(this,android.R.layout.simple_spinner_item,
activities));
}
public class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context ctx, int txtViewResourceId, String[] objects) {
super(ctx, txtViewResourceId, objects);
}
@Override
public View getDropDownView(int position, View cnvtView, ViewGroup prnt) {
return getCustomView(position, cnvtView, prnt);
}
@Override
public View getView(int pos, View cnvtView, ViewGroup prnt) {
return getCustomView(pos, cnvtView, prnt);
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View mySpinner = inflater.inflate(R.layout.custom_spinner, parent, false);
TextView main_text = (TextView) mySpinner.findViewById(R.id.text_of_activities);
main_text.setText(activities[position]);
ImageView left_icon = (ImageView) mySpinner.findViewById(R.id.picture_of_activity);
left_icon.setImageResource(total_images[position]);
return mySpinner;
}
}
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Do you want to exit the application?")
.setNegativeButton(R.string.no, null)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
moveTaskToBack(true);
}
}).create().show();
}
和ActivityTypes类:
{{1}}
PS:我说“!!!!!!!!!!!!!!!”在第一堆代码中,我认为应该完成链接。
答案 0 :(得分:-1)
尝试更改
Intent i = new Intent(ConnectionScreen.context, ActivityTypes.class);
为...
Intent i = new Intent(this, ActivityTypes.class);