2016-03-29 58 views
1

我有藍牙片段。 我有我的第一個建立BT連接的活動。有一個選項提供給用戶,根據他們的選擇,將加載一個不同的活動。如何分享片段和活動之間的連接

public class BluetoothFragment extends Fragment { 
       private NameMappingDataSource mName; 
       private DeviceAutoConnectDataSource deviceAutoConnect; 
       private ActivateDatasource activateDatasource; 
       List<DisplayNameMapping> dataItemsdevice = new ArrayList<DisplayNameMapping>(); 
       private static final String TAG = "BluetoothChatFragment"; 
       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; 
       private ListView mConversationView; 
       private EditText mOutEditText; 
       private Button mSendButton; 
       private String mConnectedDeviceName = null; 
       private String mConnectedDeviceAddress = null; 
       private ArrayAdapter<String> mConversationArrayAdapter; 
       private StringBuffer mOutStringBuffer; 
       private BluetoothAdapter mBluetoothAdapter = null; 
       private BluetoothService mMessage = null; 
       private Context context; 
       boolean mBound = false; 
       @Override 
       public Context getContext() { 
        return context; 
       } 
       public void setContext(Context context) { 
        this.context = context; 
       } 
       @Override 
       public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        mName = new NameMappingDataSource(getActivity()); 
        deviceAutoConnect = new DeviceAutoConnectDataSource(getActivity()); 
        activateDatasource = new ActivateDatasource(getActivity()); 
        setHasOptionsMenu(true); 
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
        if (mBluetoothAdapter == null) { 
         FragmentActivity activity = getActivity(); 
         Toast.makeText(activity, "Bluetooth is not available", Toast.LENGTH_LONG).show(); 
         activity.finish(); 
        } 

       } 
       @Override 
       public void onStart() { 
        super.onStart(); 
        if (!mBluetoothAdapter.isEnabled()) { 
         Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
         startActivityForResult(enableIntent, REQUEST_ENABLE_BT); 
        } else if (mMessage == null) { 
         setupChat(); 
        } 
       } 
       @Override 
       public void onDestroy() { 
        super.onDestroy(); 
        if (mMessage != null) { 
         mMessage.stop(); 
        } 
       } 
       @Override 
       public void onResume() { 
        super.onResume(); 

        if (mMessage != null) { 
         if (mMessage.getState() == BluetoothService.STATE_NONE) { 
          mMessage.start(); 
         } 
        } 
       @Override 
       public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, 
             @Nullable Bundle savedInstanceState) { 
        return inflater.inflate(R.layout.fragment_bluetooth_chat, container, false); 
       } 
       @Override 
       public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { 
        mConversationView = (ListView) view.findViewById(R.id.in); 
        mOutEditText = (EditText) view.findViewById(R.id.edit_text_out); 
        mSendButton = (Button) view.findViewById(R.id.button_send); 

       } 
       private void setupChat() { 
        mConversationArrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.message); 

        mConversationView.setAdapter(mConversationArrayAdapter); 
        mOutEditText.setOnEditorActionListener(mWriteListener); 

        mSendButton.setOnClickListener(new View.OnClickListener() { 
         public void onClick(View v) { 
          View view = getView(); 
          if (null != view) { 
           TextView textView = (TextView) view.findViewById(R.id.edit_text_out); 
           String message = textView.getText().toString(); 
           sendMessage(message.getBytes()); 
          } 
         } 
        }); 
        final Button testButton = (Button) getActivity().findViewById(R.id.button1); 
        testButton.setTag(1); 
        testButton.setBackgroundResource(R.drawable.open); 
        testButton.setOnClickListener(new View.OnClickListener() { 
         @Override 
         public void onClick(View v) { 
          final int status = (Integer) v.getTag(); 
          if (status == 1) { 
           v.setTag(0); 
          } else { 
           testButton.setBackgroundResource(R.drawable.open); 
           v.setTag(1); 
          } 
         } 
        }); 
        mMessage = new BluetoothService(getActivity(), mHandler); 

        mOutStringBuffer = new StringBuffer(""); 
       } 
       private void ensureDiscoverable() { 
        if (mBluetoothAdapter.getScanMode() != 
          BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) { 
         Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); 
         discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); 
         startActivity(discoverableIntent); 
        } 
       } 
       public void sendMessage(byte[] message) { 
        if (mMessage.getState() != BluetoothService.STATE_CONNECTED) { 
         Toast.makeText(getActivity(), R.string.not_connected, Toast.LENGTH_SHORT).show(); 
         return; 
        } 
        if (message.length > 0) { 
         mMessage.write(message); 
         mOutStringBuffer.setLength(0); 
         mOutEditText.setText(mOutStringBuffer); 
        } 
       } 
       private TextView.OnEditorActionListener mWriteListener 
         = new TextView.OnEditorActionListener() { 
        public boolean onEditorAction(TextView view, int actionId, KeyEvent event) { 
         // If the action is a key-up event on the return key, send the message 
         if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) { 
          String message = view.getText().toString(); 
          sendMessage(message.getBytes()); 
         } 
         return true; 
        } 
       }; 
       private void setStatus(int resId) { 
        FragmentActivity activity = getActivity(); 
        if (null == activity) { 
         return; 
        } 
        final ActionBar actionBar = activity.getActionBar(); 
        if (null == actionBar) { 
         return; 
        } 
        actionBar.setSubtitle(resId); 
       } 
       private void setStatus(CharSequence subTitle) { 
        FragmentActivity activity = getActivity(); 
        if (null == activity) { 
         return; 
        } 
        final ActionBar actionBar = activity.getActionBar(); 
        if (null == actionBar) { 
         return; 
        } 
        actionBar.setSubtitle(subTitle); 
       } 
       private final Handler mHandler = new Handler() { 
        @Override 
        public void handleMessage(Message msg) { 
         int t = 0; 
         FragmentActivity activity = getActivity(); 
         switch (msg.what) { 
          case Constants.MESSAGE_STATE_CHANGE: 
           switch (msg.arg1) { 
            case BluetoothService.STATE_CONNECTED: 
             setStatus(getString(R.string.title_connected_to, mConnectedDeviceName)); 
             mConversationArrayAdapter.clear(); 
             break; 
            case BluetoothService.STATE_CONNECTING: 
             setStatus(R.string.title_connecting); 
             break; 
            case BluetoothService.STATE_LISTEN: 
            case BluetoothService.STATE_NONE: 
             setStatus(R.string.title_not_connected); 
             break; 
           } 
           break; 
          case Constants.MESSAGE_WRITE: 
           byte[] writeBuf = (byte[]) msg.obj; 
           mConversationArrayAdapter.add("Me: " + writeBuf); 
           break; 
          case Constants.MESSAGE_READ: 
           byte[] readBuf = (byte[]) msg.obj; 
           String readMessage = new String(readBuf, 0, msg.arg1); 

           mConversationArrayAdapter.add(mConnectedDeviceName + ": " + readMessage); 
           break; 
          case Constants.MESSAGE_DEVICE_NAME: 
           mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME); 
           mConnectedDeviceAddress = msg.getData().getString(Constants.DEVICE_ADDRESS); 
           if (null != activity) { 
            Toast.makeText(activity, "Connected to " 
              + mConnectedDeviceName, Toast.LENGTH_SHORT).show(); 
           } 
           break; 
          case Constants.MESSAGE_TOAST: 
           if (null != activity) { 
            Toast.makeText(activity, msg.getData().getString(Constants.TOAST), 
              Toast.LENGTH_SHORT).show(); 
            mConnectedDeviceAddress=null; 
           } 
           break; 
         } 
        } 
       }; 
       public void onActivityResult(int requestCode, int resultCode, Intent data) { 
        switch (requestCode) { 
         case REQUEST_CONNECT_DEVICE_SECURE: 
          if (resultCode == Activity.RESULT_OK) { 
           connectDevice(data, true); 
          } 
          break; 
         case REQUEST_CONNECT_DEVICE_INSECURE: 
          if (resultCode == Activity.RESULT_OK) { 
           connectDevice(data, false); 

          } 
          break; 
         case REQUEST_ENABLE_BT: 
          if (resultCode == Activity.RESULT_OK) { 
           setupChat(); 
          } else { 
           Log.d(TAG, "BT not enabled"); 
           Toast.makeText(getActivity(), R.string.bt_not_enabled_leaving, 
             Toast.LENGTH_SHORT).show(); 
           getActivity().finish(); 
          } 
        } 
       } 
       private void connectDevice(Intent data, boolean secure) { 
        String address = data.getExtras() 
          .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS); 
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); 
        mMessage.connect(device, secure); 
       } 
       @Override 
       public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 
        inflater.inflate(R.menu.bluetooth_chat, menu); 
       } 
       @Override 
       public boolean onOptionsItemSelected(MenuItem item) { 
        switch (item.getItemId()) { 
         case R.id.secure_connect_scan: { 
          Intent serverIntent = new Intent(this.context, DeviceListActivity.class); 
          startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE); 
          return true; 
         } 
         case R.id.insecure_connect_scan: { 
          Intent serverIntent = new Intent(this.context, DeviceListActivity.class); 
          startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE); 
          return true; 
         } 
         case R.id.discoverable: { 
          ensureDiscoverable(); 
          return true; 
         } 
         case R.id.menu_user: { 
          if(mConnectedDeviceAddress!=null) { 
           mName.open(); 
           List<DisplayNameMapping> str = mName.getDisplayNameMappingLiked(mConnectedDeviceAddress); 
           mName.close(); 
           String setname = str.get(0).getDisplay_name(); 
           showInputDialogCheckPWAdminUser(setname, mConnectedDeviceAddress); 
          } 
          return true; 
         } 
         case R.id.menu_history: { 

          Intent userIntent = new  Intent(getActivity(),UserListActivity.class); 
           userIntent.putExtra("addressdevice", mdeviceaddress); 
           startActivity(userIntent); 

         } 
        } 
        return false; 
       } 
      } 

如何發送短信到這裏bletoothfragment.class 的使用的連接,請幫助我。我不知道

  public class UserListActivity extends Activity implements UserListAdapter.customButtonListener { 
       Button btnadduser,btnconfig; 
       @Override 
       protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        context=this; 
        getActionBar().setDisplayHomeAsUpEnabled(true); 
        userdata = new UserDataSource(this); 
        namedata = new NameMappingDataSource(this); 
        userdevicedata=new UserDeviceDatasource(this); 
        setContentView(R.layout.activity_user_list); 
        btnconfig=(Button) findViewById(R.id.btnconfig); 

        btnconfig.setOnClickListener(new View.OnClickListener() { 
         @Override 
         public void onClick(View v) { 
          try { 
           'How to send message to here used connection of bletoothfragment.class ' 
          } catch (Exception ex) { 

          } 
         } 
        });  
       } 


       public void onButtonClickListner(int position, String value) { 

       } 

       public boolean onOptionsItemSelected(MenuItem item) { 
        switch (item.getItemId()) { 
         case android.R.id.home: 
          this.finish(); 
          return true; 
         default: 
          return super.onOptionsItemSelected(item); 
        } 
       } 
      } 
+0

看看[這個答案](http://stackoverflow.com/a/17569897/4281182) –

回答

0

您可以保存上次連接的設備地址,然後您可以使用它。

String address = intent.getExtras() 
      .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS); 
     // Get the BluetoothDevice object 
     BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); 
     // Attempt to connect to the device 
     mChatService.connect(device, secure);