Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何共享片段和活动之间的连接_Java_Android_Bluetooth_Connection - Fatal编程技术网

Java 如何共享片段和活动之间的连接

Java 如何共享片段和活动之间的连接,java,android,bluetooth,connection,Java,Android,Bluetooth,Connection,我有蓝牙碎片。 我的第一个活动是建立BT连接。向用户提供了一个选项,根据用户的选择,将加载不同的活动 public class BluetoothFragment extends Fragment { private NameMappingDataSource mName; private DeviceAutoConnectDataSource deviceAutoConnect; private A

我有蓝牙碎片。 我的第一个活动是建立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;
                }
            }

您可以保存上次连接的设备地址,然后使用它

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

您可以保存上次连接的设备地址,然后使用它

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);
看一看,看一看