- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
好的,伙计们,我需要一点蓝牙方面的帮助。我是 Java 的新手,所以我需要帮助从四个不同的 fragment 传递/控制同一个蓝牙设备。我读了一些关于服务、线程和对象或类似的东西,但我认为有更简单和更容易理解的方法来做到这一点......我的第一个 Activity 将设备地址发送到 MainControls 并成功连接,但我不知道如何访问它来自另一个 fragment 。
这是我的主要 fragment :
public class MainControls extends AppCompatActivity {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
public String address;
String bckg;
TextView textView;
private ProgressDialog progress;
//BLE
public BluetoothAdapter myBluetooth = null;
public BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
//SPP UUID
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
/**
* The {@link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_controls);
textView = (TextView)findViewById(R.id.textView);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent i = this.getIntent();
address = i.getStringExtra("addr");
bckg = i.getStringExtra("bckg");
mSectionsPagerAdapter = new
SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.led);
tabLayout.getTabAt(1).setIcon(R.drawable.sliders);
tabLayout.getTabAt(2).setIcon(R.drawable.controller);
tabLayout.getTabAt(3).setIcon(R.drawable.wrench);
new ConnectBT().execute();
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_options, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.about)
{
//return true;
}
if (id == R.id.info)
{
//return true;
}
if (id == R.id.nastavenia)
{
//return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
tab1Led tab1 = new tab1Led();
return tab1;
case 1:
tab2Sliders tab2 = new tab2Sliders();
return tab2;
case 2:
tab3Controller tab3 = new tab3Controller();
return tab3;
case 3:
tab4Custom tab4 = new tab4Custom();
return tab4;
default:
return null;
}
}
@Override
public int getCount() {
// Show 3 total pages.
return 4;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Led";
case 1:
return "Sliders";
case 2:
return "Controller";
case 3:
return "Custom";
}
return null;
}
}
private void msg(String s){
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
/*Bluetooth class
*
*
*/
public class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true;
@Override
protected void onPreExecute()
{
progress = ProgressDialog.show(MainControls.this, "Connecting...",
"Please wait!!!"); //show a progress dialog
}
@Override
protected Void doInBackground(Void... devices) //while the progress
dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
myBluetooth = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice btDevice =
myBluetooth.getRemoteDevice(address);
btSocket =
btDevice.createInsecureRfcommSocketToServiceRecord(myUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();
}
}
catch (IOException e)
{
ConnectSuccess = false;
}
return null;
}
@Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
msg("Connection Failed. Try again.");
Intent i = new Intent(MainControls.this, DeviceSearch.class);
startActivity(i);
}
else {
msg("Successfully Connected.");
isBtConnected = true;
}
progress.dismiss();
}
}
/*Bluetooth class
*
*
*/
}
我的代码运行正常,我的所有 fragment 都可以协同工作,而且我没有遇到任何错误。我成功连接到我想要的设备但是当我想从另一个 fragment 访问它时,问题就开始了……
这是 tab1Led,我的第一个 fragment :
public class tab1Led extends Fragment
{
public String address;
public int bckg;
TextView status, delayTextView;
int count, delay;
private SeekBar delaySeek;
public BluetoothAdapter myBluetooth;
public BluetoothSocket btSocket = null;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
final Context context = getActivity().getApplicationContext();
//JJ
View view = inflater.inflate(R.layout.led, container, false);
TextView textView = (TextView)view.findViewById(R.id.textView);
delayTextView = (TextView)view.findViewById(R.id.delayTextView);
status = (TextView)view.findViewById(R.id.status);
bckg = getActivity().getIntent().getExtras().getInt("bckg");
address = getActivity().getIntent().getExtras().getString("addr");
delaySeek = (SeekBar)view.findViewById(R.id.delaySeek);
if(bckg == 0){
textView.setText("Selected background: dark \n" + address);
}
else if(bckg == 1){
textView.setText("Selected background: light \n" + address);
}
else{
textView.setText("Error");
}
count = 0;
delay = 250;
delaySeek.setProgress(250);
delayTextView.setText("Delay: " + String.valueOf(delay) + "ms");
ImageButton imageButton = (ImageButton)
view.findViewById(R.id.imageButton);
delaySeek.setOnSeekBarChangeListener(new
SeekBar.OnSeekBarChangeListener() {
int progressChangedValue = 0;
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
progressChangedValue = progress;
delay = delaySeek.getProgress();
delayTextView.setText("Delay: " + String.valueOf(delay) +
"ms");
}
public void onStartTrackingTouch(SeekBar seekBar) {
delay = delaySeek.getProgress();
delayTextView.setText("Delay: " + String.valueOf(delay) +
"ms");
}
public void onStopTrackingTouch(SeekBar seekBar) {
delay = delaySeek.getProgress();
delayTextView.setText("Delay: " + String.valueOf(delay) +
"ms");
}
});
imageButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if(count == 0){
status.setText("LED is: OFF");
count++;
}
else if(count == 1){
status.setText("LED is: ON");
count--;
}
else {
count = 0;
}
}
});
return view;
}
private void msg(String s){
Toast.makeText(getContext(), s, Toast.LENGTH_SHORT).show();
}
}
好的,我已准备就绪,我需要在按钮关闭时发送字符,在按钮打开时发送字符,但我只是无法访问蓝牙设备。感谢您的帮助:)
最佳答案
您的蓝牙控件显然应该在线程中以获得更多控制。
这是一个如何实现蓝牙连接的示例,名为 sendToTarget 的方法将负责将来自蓝牙的数据发送到 UI Activity 或 fragment 。
public class MyBluetoothService {
private static final String TAG = "MY_APP_DEBUG_TAG";
private Handler mHandler; // handler that gets info from Bluetooth service
// Defines several constants used when transmitting messages between the
// service and the UI.
private interface MessageConstants {
public static final int MESSAGE_READ = 0;
public static final int MESSAGE_WRITE = 1;
public static final int MESSAGE_TOAST = 2;
// ... (Add other message types here as needed.)
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private byte[] mmBuffer; // mmBuffer store for the stream
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams; using temp objects because
// member streams are final.
try {
tmpIn = socket.getInputStream();
} catch (IOException e) {
Log.e(TAG, "Error occurred when creating input stream", e);
}
try {
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "Error occurred when creating output stream", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
mmBuffer = new byte[1024];
int numBytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs.
while (true) {
try {
// Read from the InputStream.
numBytes = mmInStream.read(mmBuffer);
// Send the obtained bytes to the UI activity.
Message readMsg = mHandler.obtainMessage(
MessageConstants.MESSAGE_READ, numBytes, -1,
mmBuffer);
readMsg.sendToTarget();
} catch (IOException e) {
Log.d(TAG, "Input stream was disconnected", e);
break;
}
}
}
// Call this from the main activity to send data to the remote device.
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
// Share the sent message with the UI activity.
Message writtenMsg = mHandler.obtainMessage(
MessageConstants.MESSAGE_WRITE, -1, -1, mmBuffer);
writtenMsg.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Error occurred when sending data", e);
// Send a failure message back to the activity.
Message writeErrorMsg =
mHandler.obtainMessage(MessageConstants.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString("toast",
"Couldn't send data to the other device");
writeErrorMsg.setData(bundle);
mHandler.sendMessage(writeErrorMsg);
}
}
// Call this method from the main activity to shut down the connection.
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close the connect socket", e);
}
}
}
关于java - 从其他 fragment 控制蓝牙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47058418/
我有一个像这样的 fragment 栈 F1 -> F2 -> F3 -> F4 -> F5 现在我需要删除 F2、F3、F4 fragment 。 我需要如果我从 F5 fragment 按下后退按
我需要帮助来理解以下场景的工作原理以及如何实现结果。 我有一个名为 ShoppingCart 的类。它有一个名为 addItemsToShoppingCartFromPreviousOrder 的方法
我有一个包含 ViewPager 的 fragment 。这个 ViewPager 显然是由其他 Fragments 填充的。 我的问题是,ViewPager 中的 Fragment 是否有任何方法(
所以我正在实现一个 FragmentActivity 并尝试添加一个 fragment ,但是我遇到了多个问题。我以前做过这个,实际上我使用的代码与上一个项目(它工作的地方)相同,但由于某种原因它在这
Closed. This question needs details or clarity。它当前不接受答案。
我想将 Android X fragment (androidx.fragment.app.Fragment) 转换为 Android native fragment (android.app.Fra
假设我有一个包含 10 列文本类型 (20) 的 SQLite 表。 ListFragment 将从数据库中提取 4 列并使用 SimpleCursorAdapter 显示在列表中。 选择后,List
我有一个对话框 fragment ,我为延迟初始化创建了一个类。当我显示对话框时,它显示正常。但是,当我关闭对话框时,它崩溃的原因是: fragment 与 fragment 管理器无关。 我也尝试过
我想在 View 分页器更改为 fragment 时刷新该 fragment 。 package com.mcivisoft.rcbeam; import android.os.Bundle; imp
我有一个名为的 Activity MainActivity 我在容器 R.id.mainContainer 中添加了 fragment “BenefitFragment”。 在 BenefitFrag
所以我有这个 ClientListView,效果很好,可以显示客户,我可以单击一个客户并在右侧获取他们的详细信息(在我的第二个 fragment 中)。由此处的布局定义: 这很好用,但后来我
我试过这段代码,但点击第一个 fragment 中的按钮并没有改变第二个 fragment 中的字符串值。 这是第一个 fragment 的 kotlin 文件。它有两个按钮,点击它们可以更改字符串值
我有以下情况:我打开 fragment A 和目标,通过按钮的单击事件转到 fragment B。当我在 fragment B 中并点击后退按钮(为了返回 fragment A) 我想将一些参数传递给
我制作了一个 NavigationDrawer fragment ,其中包含 Home、Settings、Feedback 等项目。 home 项在点击 home 时应该打开,home 是在应用程序启
我正在一个接一个地替换 2 个 fragment ,两个 fragment 都有不同的选项菜单。当我替换第二个 fragment 时,它也显示第一个 fragment 的菜单。 setHasOptio
我有问题: android.app.Fragment$InstantiationException: Unable to instantiate fragment ${packageName}.${a
我正在研究 fragment 转换。当我用第二个 fragment 替换第一个 fragment 时,它出现在第一个 fragment 的下方。我希望它移动到第一个 fragment 之上。我该怎么做
我在抽屉导航里总共有 12 个 fragment 。每个 fragment 都有 volley 方法。每个 fragment 都显示自己的 Volley 响应,除了 position = 1 和 po
我在我的 Activity 中使用了两个 fragment 。最初我将向 Activity 添加一个 fragment 。然后在第一个 fragment 中使用监听器我想用第二个 fragment 替
我正在实现一个“fragments-101”程序,当相应的按钮被点击时我会替换一个 fragment 。然而,下面的事情发生了: 为什么会这样?为什么初始 fragment 没有被完全替换?MainA
我是一名优秀的程序员,十分优秀!