我对android的编程很陌生。我有两个班:主班和BTManager。当我尝试在手机上测试我的应用程序时,我得到的只是一个信息,即procees被杀。我做错什么了?
代码实现:
主要类别:
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) { }
}
最佳答案
我在你的代码中看到两个问题:
您没有实例化Btmanager
对象,当您调用null
时它仍然是run
。(将导致NullPointerException
-你的应用程序将崩溃)。
您调用run
方法而不是start
的Btmanager
方法。如果希望run
方法中的代码在新线程中运行,则必须调用start
。调用run
将导致它在同一线程中运行。这会阻塞您的ui线程,如果阻塞时间过长,可能会导致应用程序崩溃。