gpt4 book ai didi

Android蓝牙应用程序进程被杀死

转载 作者:太空狗 更新时间:2023-10-29 13:33:21 24 4
gpt4 key购买 nike

我是 Android 编程的新手。我有两个类:main 和 btmanager。当我尝试在手机上测试我的应用程序时,我得到的只是一条信息,表明进程已被杀死。我究竟做错了什么 ?

代码实现:

主类:

public class MainActivity extends Activity {

BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

Btmanager manager;


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

if (bluetooth == null)
{
Toast.makeText(this, "Bluetooth is not enabled on this device", Toast.LENGTH_LONG).show();
System.exit(0);
}


}

@Override
public void onStart()
{
super.onStart();

if (!bluetooth.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 2);
}

manager.run();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}




public void closeApp (View view)
{
System.exit(0);
}
}

Btmanager 类:

public class Btmanager extends Thread {

private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public static final UUID myUUID = UUID.fromString("0x1101");
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

public Btmanager(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;

// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(myUUID);
} catch (IOException e) { }
mmSocket = tmp;
}

public void run() {
// Cancel discovery because it will slow down the connection
bluetooth.cancelDiscovery();

try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}

}

/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}

最佳答案

我在你的代码中看到了 2 个问题:

  1. 您没有实例化Btmanager 对象,当您调用run 时它仍然是null。 (将导致 NullPointerException - 您的应用程序将崩溃)。
  2. 您调用run 方法而不是Btmanagerstart 方法。如果你想让run方法中的代码在一个新的线程中运行,你必须调用start。调用run 将导致它在相同 线程中运行。这会阻塞您的 UI 线程,如果阻塞时间过长,可能会导致您的应用崩溃。

关于Android蓝牙应用程序进程被杀死,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13210525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com