[英]Is there any chance to simply call method in new thread?
my problem is that when I run the android app, it takes a minute for this method to run if the printer is offline.我的问题是,当我运行 android 应用程序时,如果打印机处于离线状态,此方法需要一分钟才能运行。 I would like to run it on another thread in the background and the original thread could run uninterrupted.我想在后台的另一个线程上运行它,并且原始线程可以不间断地运行。 Thanks for any advice, happy codding!感谢您的任何建议,祝编码愉快!
public class MainActivity extends WebView {
public PrinterManager printerManager;
public final int REQUEST_COARSE_LOCATION_PERMISSIONS = 52;
private JSPlugin plugin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBluetoothReceiver, filter);
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_COARSE_LOCATION_PERMISSIONS: {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//printerManager.connectDefaultPrinter(0);
//printerManager.connectDefaultPrinter(1);
printerManager.connectAll(); <----- This method call i want to do in new thread
} else {
Toast.makeText(this,
"NO Bluetooth RIGHTS",
Toast.LENGTH_LONG).show();
}
return;
}
}
}
You could simply create a Thread object and put your method into it.您可以简单地创建一个 Thread object 并将您的方法放入其中。
Here the code that should work for your case:这里的代码适用于您的案例:
public class MainActivity extends WebView {
public PrinterManager printerManager;
public final int REQUEST_COARSE_LOCATION_PERMISSIONS = 52;
private JSPlugin plugin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBluetoothReceiver, filter);
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_COARSE_LOCATION_PERMISSIONS: {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
ConnectingThread connectingThread = new ConnectingThread();
connectingThread.start();
} else {
Toast.makeText(this, "NO Bluetooth RIGHTS", Toast.LENGTH_LONG).show();
}
return;
}
}
}
private class ConnectingThread extends Thread {
public ConnectingThread() {
}
public void run() {
// You can set a low priority, if you want, using:
//Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
printerManager.connectAll();
}
}
}
Basing on your management needs, you can decide to place the definition of your connectingThread in a different position.根据您的管理需要,您可以决定将连接线程的定义放在不同的 position 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.