1

大家好.. 我在我的应用程序中使用了 android 蓝牙聊天应用程序代码我想将设备名称传递给另一个活动,所以当我从列表视图中选择与 android 聊天应用程序相同的设备名称时,我将设备名称保存在公共静态变量中。

之后,我在另一个活动中使用了这个设备名称。借助这个设备名称,我在第二个活动中启动了蓝牙聊天服务,与蓝牙聊天标准代码示例相同。我没有在我的主要活动中使用这个服务,因为我想在我的第二个活动中连接设备

我只使用了安全密钥。但是当我使用此服务时,有时会与我的其他设备连接或有时不连接。

当我尝试从双方连接进行连接时。但第一次它没有连接。我已经使用了很多东西来启动服务,例如 onResume 或 ONStart 或 OnCreate 但我没有成功。我的英语不好,所以请仔细阅读。

MY Main Activity Code=======

     public static String EXTRA_DEVICE_ADDRESS = "device_address";

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


// Debugging


private static final String TAG = "BluetoothChat";
private static final boolean D = true;



// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";

// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;

// Layout Views
private TextView mTitle;
private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton;

private Button mSearch;

// Name of the connected device
private String mConnectedDeviceName = null;
// Array adapter for the conversation thread
private ArrayAdapter<String> mConversationArrayAdapter;
// String buffer for outgoing messages
private StringBuffer mOutStringBuffer;
// Local Bluetooth adapter
public static  BluetoothAdapter mBluetoothAdapter = null;


private LinearLayout mLin_getView;


@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    if(D) Log.e(TAG, "+++ ON CREATE +++");

    // Set up the window layout
    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

    setContentView(R.layout.main);


    // Set up the custom title

    mLin_getView=(LinearLayout) findViewById(R.id.mLin_addView);

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

    // If the adapter is null, then Bluetooth is not supported
    if (mBluetoothAdapter == null) {
        Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        finish();
        return;
    }
}

@SuppressLint("NewApi")
@Override
public void onStart() {
    super.onStart();
    if(D) Log.e(TAG, "++ ON START ++");

    // If BT is not on, request that it be enabled.
    // setupChat() will then be called during onActivityResult
    if (!mBluetoothAdapter.isEnabled()) {
        Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
    // Otherwise, setup the chat session
    } else {
        //if (mChatService == null)
        setupChat();


    }
}

@Override
public synchronized void onResume() {
    super.onResume();
    if(D) Log.e(TAG, "+ ON RESUME +");

    // Performing this check in onResume() covers the case in which BT was
    // not enabled during onStart(), so we were paused to enable it...
    // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.

}

@SuppressLint("NewApi")
private void setupChat() {
    Log.d(TAG, "setupChat()");



    mSearch = (Button) findViewById(R.id.btn_search);


    mSearch.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            // Send a message using content of the edit text widget
            initilizeFiled();
            /*Intent serverIntent = new Intent(BluetoothChat.this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);*/
        }
    });




    mOutStringBuffer = new StringBuffer("");
}

protected void initilizeFiled() {
    // TODO Auto-generated method stub
     Button scanButton = (Button) findViewById(R.id.button_scan);



     mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
     mNewDevicesArrayAdapter = 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);

     // Find and set up the ListView for newly discovered devices
     ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
     newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
     newDevicesListView.setOnItemClickListener(mDeviceClickListener);

     // Register for broadcasts when a device is discovered
     IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
     this.registerReceiver(mReceiver, filter);

     // Register for broadcasts when discovery has finished
     filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
     this.registerReceiver(mReceiver, filter);

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

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

     // If there are paired devices, add each one to the ArrayAdapter
     if (pairedDevices.size() > 0) {

         findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);

         for (BluetoothDevice device : pairedDevices) {
             mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
         }
     } else {
         String noDevices = getResources().getText(R.string.none_paired).toString();
         mPairedDevicesArrayAdapter.add(noDevices);
     }
}

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @SuppressLint("NewApi")
    @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
            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);
            }
        }
    }
};
// The on-click listener for all devices in the ListViews
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
    public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {

        // Cancel discovery because it's costly and we're about to connect
        mBtAdapter.cancelDiscovery();

        // 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);

        Log.d("Device Address", address);
        connectDevice(address, true);


    }
};

@SuppressLint("NewApi")
private void doDiscovery() {

    if (D) Log.d(TAG, "doDiscovery()");

    // Indicate scanning in the title
    setProgressBarIndeterminateVisibility(true);
    setTitle(R.string.scanning);

    // Turn on sub-title for new devices
    findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);

    // If we're already discovering, stop it
    if (mBtAdapter.isDiscovering()) {
        mBtAdapter.cancelDiscovery();
    }

    // Request discover from BluetoothAdapter
    mBtAdapter.startDiscovery();
}
@Override
public synchronized void onPause() {
    super.onPause();
    if(D) Log.e(TAG, "- ON PAUSE -");


    if (mBtAdapter != null) {
        mBtAdapter.cancelDiscovery();
    }

}

@Override
public void onStop() {
    super.onStop();
    if(D) Log.e(TAG, "-- ON STOP --");
}

@Override
public void onDestroy() {
    super.onDestroy();
    // Stop the Bluetooth chat services
    //if (mChatService != null) mChatService.stop();
    if(D) Log.e(TAG, "--- ON DESTROY ---");

    if (mBtAdapter != null) {
        mBtAdapter.cancelDiscovery();
    }

    // Unregister broadcast listeners
    this.unregisterReceiver(mReceiver);
}







// The Handler that gets information back from the BluetoothChatService


public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(D) Log.d(TAG, "onActivityResult " + resultCode);
    switch (requestCode) {
    case REQUEST_CONNECT_DEVICE_SECURE:
        // When DeviceListActivity returns with a device to connect
        if (resultCode == Activity.RESULT_OK) {
           // connectDevice(data, true);
        }
        break;
    case REQUEST_CONNECT_DEVICE_INSECURE:
        // When DeviceListActivity returns with a device to connect
        if (resultCode == Activity.RESULT_OK) {
           // connectDevice(data, false);
        }
        break;
    case 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
            setupChat();
        } else {
            // User did not enable Bluetooth or an error occured
            Log.d(TAG, "BT not enabled");
            Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
            finish();
        }



    }
}







private void connectDevice(String Address,boolean secure) {
    // Get the device MAC address


    String address = Address;
    // Get the BLuetoothDevice object
   // BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);

    Const.deviceName=device;

    Intent ib=new Intent(DashboardActivity.this,RemmoteActivity.class);

    startActivity(ib);



}

}

第二次活动=========

private BluetoothAdapter mBluetoothAdapter = null;


 private String mConnectedDeviceName = 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;

    String TAG="Remmote";

    // Key names received from the BluetoothChatService Handler
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";


ImageView Img_video, Img_camera, Img_song, Img_play, Img_forward,
        Img_backward, Img_volume_up, Img_volume_down, Img_splash,
        Img_capture, Img_zoom_in, Img_zoom_out;

private BluetoothChatService mChatService=null;
private StringBuffer mOutStringBuffer;
private BluetoothDevice device_Name;




@Override
protected void onCreate(Bundle savedInstanceState) {

    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_remote_screen);



    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    mChatService=new BluetoothChatService(this,mHandler);
    mOutStringBuffer=new StringBuffer("");

     mOutStringBuffer=new StringBuffer("");

     device_Name=Const.device;





     if (mChatService != null) {
            // Only if the state is STATE_NONE, do we know that we haven't started already
            if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
              // Start the Bluetooth chat services
              mChatService.start();
            }
        }



    initilizeField();
}


   public void onStart() {
        super.onStart();
      Log.print(TAG, "++ ON START ++");

        // If BT is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult
        if (!mBluetoothAdapter.isEnabled()) {

             Toast.makeText(getApplicationContext(), "Bluetooth Device Enabled", Toast.LENGTH_SHORT).show();

        } else {
             Toast.makeText(getApplicationContext(), "Bluetooth Device Enabled", Toast.LENGTH_SHORT).show();
        }
    }
   @Override
    public synchronized void onResume() {
        super.onResume();
         Log.print(TAG, "+ ON RESUME +");

         mChatService.connect(device_Name, true);


    }
    @Override
    public synchronized void onPause() {
        super.onPause();
      Log.print(TAG, "- ON PAUSE -");
    }

    @Override
    public void onStop() {
        super.onStop();
     Log.print(TAG, "-- ON STOP --");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Stop the Bluetooth chat services
        if (mChatService != null) mChatService.stop();
         Log.print(TAG, "--- ON DESTROY ---");
    }


@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {



    case R.id.mImg_camera:

        sendMessage("Camera");


        break;
    case R.id.mImg_video:

        break;
    case R.id.mImg_songs:

        break;
    case R.id.Img_play:

        break;
    case R.id.Img_forward:

        break;
    case R.id.Img_backward:

        break;
    case R.id.Img_volume_up:

        break;

    default:
        break;
    }
}
 public void sendMessage(String message) {
        // Check that we're actually connected before trying anything
        if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
            Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();


            return;
        }

        // Check that there's actually something to send
        if (message.length() > 0) {
            // Get the message bytes and tell the BluetoothChatService to write
            byte[] send = message.getBytes();
            mChatService.write(send);

            // Reset out string buffer to zero and clear the edit text field
            mOutStringBuffer.setLength(0);
         //   mOutEditText.setText(mOutStringBuffer);77
        }
    }

 private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {



            case Const.Camera:


                com.example.utils.Log.print("your tab is here====="+1000);

                //BluetoothChat.this.sendMessage("Camera");
                break;


            case MESSAGE_STATE_CHANGE:

                 Log.print(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);

                switch (msg.arg1) {
                case BluetoothChatService.STATE_CONNECTED:
                     Toast.makeText(getApplicationContext(), "STATE_CONNECTED", Toast.LENGTH_SHORT).show();
                    break;
                case BluetoothChatService.STATE_CONNECTING:
                     Toast.makeText(getApplicationContext(), "STATE_CONNECTING", Toast.LENGTH_SHORT).show();
                    break;
                case BluetoothChatService.STATE_LISTEN:
                case BluetoothChatService.STATE_NONE:
                     Toast.makeText(getApplicationContext(), "STATE_NOT_LISTEN", Toast.LENGTH_SHORT).show();
                    break;
                }
                break;
            case MESSAGE_WRITE:
                byte[] writeBuf = (byte[]) msg.obj;
                // construct a string from the buffer
                String writeMessage = new String(writeBuf);

                Toast.makeText(getApplicationContext(), writeMessage, Toast.LENGTH_SHORT).show();
                //mConversationArrayAdapter.add("Me:  " + writeMessage);
                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);
                Toast.makeText(getApplicationContext(), "Read", Toast.LENGTH_SHORT).show();



               // captureImage();
              //  mConversationArrayAdapter.add(mConnectedDeviceName+":  " + readMessage);
                break;
            case MESSAGE_DEVICE_NAME:
                // save the connected device's name
                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                Toast.makeText(getApplicationContext(), "Connected to "
                               + mConnectedDeviceName, Toast.LENGTH_SHORT).show();




                break;
            case MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                               Toast.LENGTH_SHORT).show();
                break;



            }
        }
    };

在公共静态变量的 const 类中

public static BluetoothDevice device;

BluetoothChatService 代码与android默认程序示例相同

4

0 回答 0