I have one very unusual case when calling an Android hidden API over reflection freezes the calling thread eternally. I cannot debug the underlying code as it is a code from Android itself normally not visible. I tried running the code in an asynctask, in a normal thread but nor asynctask.cancel nor thread.interrupt kills the thread, the thread stays visible, I can see it while debugging. Is it really not possible to run a code encapsulated and kill it completely eventually?
This problems occurs only on Android O and only on some devices, that's why I need to test-run it to see if it works on the current device and be able to activate a feature according to that. The code below, I don't really see a solution for this:
Thread endCallThread;
Runnable myRunnable;
private void checkFeatureSupport(final Context context) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
myRunnable = new Runnable() {
#Override
public void run() {
doInBackgroundWrapper();
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
//handleResult();
}
});
}
}
};
endCallThread = new Thread(myRunnable, "endCallThread");
endCallThread.start();
new CountDownTimer(3000, 3000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
Log.e("TESTAUTOMATION", "endCall did not finished in 3 seconds");
// stop async task if not in progress
if (endCallThread.isAlive()) {
try {
endCallThread.interrupt();
endCallThread = null;
myRunnable = null;
System.gc();
Log.e("TESTAUTOMATION", "endCallThread interrupted");
} catch (Exception ex) {
Log.e("TESTAUTOMATION", "endCallThread interrupted exception");
}
//handleResult();
}
}
}.start();
} else {
mEndCallSupported = true;
}
}
}
private void doInBackgroundWrapper() {
try {
if (getContext() == null) {
return;
}
final TelephonyManager telMan = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
if (telMan == null) {
return;
}
final Class<?> classTemp = Class.forName(telMan.getClass().getName());
final Method methodTemp = classTemp.getDeclaredMethod("getITelephony");
methodTemp.setAccessible(true);
ITelephony telephonyService = (ITelephony) methodTemp.invoke(telMan);
// If this call does not return a security exception we say the call principally works.
Log.d("TESTAUTOMATION", "endCall before");
// This call endCall may freeze depending on device, mostly seen on Nexus 5x with Android 8&8.1
telephonyService.endCall();
Log.d("TESTAUTOMATION", "endCall after");
mSupported = true;
} catch (Exception ex) {
ex.printStackTrace();
mSupported = false;
}
}
To reproduce this the device should better no have a SIM inserted.
Thread.interrupt() in a common case does not stop a thread, it just marks specific boolean field (isInterrupted) as true. If a developer wants to stop thread's work at some point (after calling Thread.interrupt()) he can rely on this boolean filed Thread.isInterrupted() when he is implementing some work in a separate thread.
So I guess there is no such checking in the reflected hidden method what you are trying to call.
To stop your thread you can try deprecated Thread.stop() but it is a really bad practice.
Related
I have an executorService that does not wait for the executorService part to complete and it directly returns the return value without waiting
below is my code: Please see if I am implementing the executorService properly and help me correct it if required
public boolean validateForm() {
flag=true;
executorService = Executors.newSingleThreadExecutor();
Future f = executorService.submit(new Runnable() {
public void run() {
Log.e("FLAGssssss", "" + flag);
checkSourceCode(new BooleanCallBack() {
#Override
public void onSuccess(boolean result) {
Log.e("RESULT ISSSSS", "" + result);
validateCode = result;
Log.e("validateSourceCode ISSSSS", "" + validateSourceCode(result));
if (validateSourceCode(result) == false) {
flag = false;
}
Log.e("FLAG ISSSSS", "" + flag);
}
});
}
});
try {
if (f.get() != null) {
flag = true;
}
Log.e("FUTURE IS", "" + f.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
if (!accept_checkbox.isChecked()) {
Toast.makeText(getActivity().getBaseContext(), "Accept The Terms & Conditions To Proceed", Toast.LENGTH_LONG).show();
// accept_checkbox.requestFocus();
flag = false;
}
if (!validateAddress()) {
flag = false;
}
if (!validatelandmark()) {
flag = false;
}
if (!validateDistrict()) {
flag = false;
}
if (!validatePincode()) {
flag = false;
}
if (!validateFullfillment()) {
flag = false;
}
if (flag) {
saveData();
}
executorService.shutdown();
return flag; //flag is returned even before the executorService above is executed first
}
It looks like there is some confusion on what constitutes a callback from being constructed vs. a callback executing.
The following code is creating and submitting a new Runnable task, but the Runnable is only printing a message and then constructing a BooleanCallBack. I'm not sure exactly what BooleanCallBack does, but assuming it really is a callback, the code in the callback will not execute right away.
For simplicity, lets think of the Runnable like this:
Future future = executorService.submit(new Runnable() {
public void run() {
sysou("runnable is running");
checkSourceCode(new BooleanCallBack() {
#Override
public void onSuccess(boolean result) {
sysou("callback from the runnable is running");
}
});
}
});
When you invoke future.get(), it waits for the run() method to complete execution, which involves constructing the BooleanCallBack but not actually running it. Similar to how constructing a new Runnable object does not mean the code in the run() method is executed.
So if your code calls future.get(), the only thing you can be sure of is that the run() method has completed (i.e. you have gotten the "runnable is running" message). NOT that BooleanCallBack.onSuccess() has executed.
If you actually want to wait for the "callback from the runnable is running" bit, then you need to establish a reference to the BooleanCallBack so you can check its status.
I have the following code which is executed asynchronously. I would like to make it synchronous in order to follow some logical flow but I cannot work out how.
You will see that scanning is set to true to indicate that the method is still working, at the beginning - I then initiate a findPrinters(...) command - this contains a DiscoveryHandler which runs asynchronously - foundPrinter() is called each time an item is discovered. discoveryFinished() is when the discovery process is successfully completed, and discoveryError(...) is called whenever an error occurs.
I rely on something being set in my DiscoveryHandler before I would like to return from this method. Hence why I have while (scanning) underneath it. But this feels like a hack to me, and not the correct way of doing things. I cannot get wait() and notify() working. Can someone tell me what the correct way to do this is please?
private boolean findPrinter(final Context ctx) {
try {
scanning = true;
BluetoothDiscoverer.findPrinters(ctx, new DiscoveryHandler() {
public void foundPrinter(DiscoveredPrinter device) {
if (device instanceof DiscoveredPrinterBluetooth) {
DiscoveredPrinterBluetooth btDevice = (DiscoveredPrinterBluetooth) device;
if (btDevice.friendlyName.startsWith("XXXX")) {
try {
connection = new BluetoothConnection(btDevice.address);
connection.open();
if (connection.isConnected()) {
address = btDevice.address;
}
} catch (Exception ex) {
}
}
}
}
public void discoveryFinished() {
scanning = false;
}
public void discoveryError(String arg0) {
scanning = false;
}
});
} catch (Exception ex) {
}
while (scanning) {}
return false;
}
You could do this with CountDownLatch, which might be the lightest synchronization primitive in java.util.concurrent:
private boolean findPrinter(final Context ctx) {
final CountDownLatch latch = new CountDownLatch(1);
final boolean[] result = {false};
...
BluetoothDiscoverer.findPrinters(ctx, new DiscoveryHandler() {
...
public void discoveryFinished() {
result[0] = true;
latch.countDown();
}
public void discoveryError(String arg0) {
result[0] = false;
latch.countDown();
}
...
}
// before final return
// wait for 10 seconds for the response
latch.await(10, TimeUnit.SECONDS);
//return the result, it will return false when there is timeout
return result[0];
}
There are a bunch of ways you can do this and wait()/notify() is probably not the best since you probably want to return something from your async method. As such I suggest using something like a BlockingQueue. Here is a simplified example of how you can do this:
private boolean findPrinter(final Context ctx) {
final BlockingQueue<?> asyncResult = new SynchronousQueue<?>();
try {
BluetoothDiscoverer.findPrinters(ctx, new DiscoveryHandler() {
public void foundPrinter(DiscoveredPrinter device) {
if (device instanceof DiscoveredPrinterBluetooth) {
DiscoveredPrinterBluetooth btDevice = (DiscoveredPrinterBluetooth) device;
if (btDevice.friendlyName.startsWith("XXXX")) {
try {
connection = new BluetoothConnection(btDevice.address);
connection.open();
if (connection.isConnected()) {
address = btDevice.address;
}
} catch (Exception ex) {
}
}
}
}
public void discoveryFinished() {
asyncResult.put(true);
}
public void discoveryError(String arg0) {
asyncResult.put(arg0);
}
});
} catch (Exception ex) {
}
Object result = asyncResult.take();
if (result instanceof Boolean) {
return (Boolean) result;
} else if (result instanceof String) {
logError((String) result);
}
return false;
}
One problem with using SynchronousQueue here though is that if discoveryFinished()/discoveryError() is called more than once, then the thread executing the code asynchronously will block forever since the SynchronousQueue assumes there will be exactly one take() per every put() and will block if a put() is made without a corresponding take() or vice versa. So if in your case those methods can be called more than once you would probably use a different kind of BlockingQueue instead (see documentation).
I have to send a set of files to several computers through a certain port. The fact is that, each time that the method that sends the files is called, the destination data (address and port) is calculated. Therefore, using a loop that creates a thread for each method call, and surround the method call with a try-catch statement for a BindException to process the situation of the program trying to use a port which is already in use (different destination addresses may receive the message through the same port) telling the thread to wait some seconds and then restart to retry, and keep trying until the exception is not thrown (the shipping is successfully performed).
I didn't know why (although I could guess it when I first saw it), Netbeans warned me about that sleeping a Thread object inside a loop is not the best choice. Then I googled a bit for further information and found this link to another stackoverflow post, which looked so interesting (I had never heard of the ThreadPoolExecutor class). I've been reading both that link and the API in order to try to improve my program, but I'm not yet pretty sure about how am I supposed to apply that in my program. Could anybody give a helping hand on this please?
EDIT: The important code:
for (Iterator<String> it = ConnectionsPanel.list.getSelectedValuesList().iterator(); it.hasNext();) {
final String x = it.next();
new Thread() {
#Override
public void run() {
ConnectionsPanel.singleAddVideos(x);
}
}.start();
}
private static void singleAddVideos(String connName) {
String newVideosInfo = "";
for (Iterator<Video> it = ConnectionsPanel.videosToSend.iterator(); it.hasNext();) {
newVideosInfo = newVideosInfo.concat(it.next().toString());
}
try {
MassiveDesktopClient.sendMessage("hi", connName);
if (MassiveDesktopClient.receiveMessage(connName).matches("hello")) {
MassiveDesktopClient.sendMessage(newVideosInfo, connName);
}
} catch (BindException ex) {
MassiveDesktopClient.println("Attempted to use a port which is already being used. Waiting and retrying...", new Exception().getStackTrace()[0].getLineNumber());
try {
Thread.sleep(MassiveDesktopClient.PORT_BUSY_DELAY_SECONDS * 1000);
} catch (InterruptedException ex1) {
JOptionPane.showMessageDialog(null, ex1.toString(), "Error", JOptionPane.ERROR_MESSAGE);
}
ConnectionsPanel.singleAddVideos(connName);
return;
}
for (Iterator<Video> it = ConnectionsPanel.videosToSend.iterator(); it.hasNext();) {
try {
MassiveDesktopClient.sendFile(it.next().getAttribute("name"), connName);
} catch (BindException ex) {
MassiveDesktopClient.println("Attempted to use a port which is already being used. Waiting and retrying...", new Exception().getStackTrace()[0].getLineNumber());
try {
Thread.sleep(MassiveDesktopClient.PORT_BUSY_DELAY_SECONDS * 1000);
} catch (InterruptedException ex1) {
JOptionPane.showMessageDialog(null, ex1.toString(), "Error", JOptionPane.ERROR_MESSAGE);
}
ConnectionsPanel.singleAddVideos(connName);
return;
}
}
}
Your question is not very clear - I understand that you want to rerun your task until it succeeds (no BindException). To do that, you could:
try to run your code without catching the exception
capture the exception from the future
reschedule the task a bit later if it fails
A simplified code would be as below - add error messages and refine as needed:
public static void main(String[] args) throws Exception {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(corePoolSize);
final String x = "video";
Callable<Void> yourTask = new Callable<Void>() {
#Override
public Void call() throws BindException {
ConnectionsPanel.singleAddVideos(x);
return null;
}
};
Future f = scheduler.submit(yourTask);
boolean added = false; //it will retry until success
//you might use an int instead to retry
//n times only and avoid the risk of infinite loop
while (!added) {
try {
f.get();
added = true; //added set to true if no exception caught
} catch (ExecutionException e) {
if (e.getCause() instanceof BindException) {
scheduler.schedule(yourTask, 3, TimeUnit.SECONDS); //reschedule in 3 seconds
} else {
//another exception was thrown => handle it
}
}
}
}
public static class ConnectionsPanel {
private static void singleAddVideos(String connName) throws BindException {
String newVideosInfo = "";
for (Iterator<Video> it = ConnectionsPanel.videosToSend.iterator(); it.hasNext();) {
newVideosInfo = newVideosInfo.concat(it.next().toString());
}
MassiveDesktopClient.sendMessage("hi", connName);
if (MassiveDesktopClient.receiveMessage(connName).matches("hello")) {
MassiveDesktopClient.sendMessage(newVideosInfo, connName);
}
for (Iterator<Video> it = ConnectionsPanel.videosToSend.iterator(); it.hasNext();) {
MassiveDesktopClient.sendFile(it.next().getAttribute("name"), connName);
}
}
}
I've got an app with several screens. In addition, I have a globally-running timer that occasionally (every minute or so) attempts to refresh their transaction data from a website and store it in a JSONArray (static JSONArray jTransactions).
When you go to the Transaction screen, the first thing it does is populate a ListView with the contents of jTransactions, and it will refresh the displayed info every few seconds. However if the web-thread is currently running, I get null values for everything.
I've got enough coder savvy to know that it's a threading issue, but I'm not experienced enough with JAVA/Android development to know how to handle it. And my Google-fu may be weak but the only answers I found either didn't apply or involved heavy rewriting.
I guess my question is this - how can I alter my code so that there's no direct collision between my activity and the fetch thread?
Also I fully accept that my code is probably ugly; as I said, I'm still learning the platform.
Here's a pared-down version of the thread I'm running:
static int iRefreshTransactions = 30000;
static boolean bRefreshingTransactions = false;
static Calendar cLastRefreshTransactions = null;
final Runnable mRefreshTransactions = new Runnable() {
public void run() {
mHandler.removeCallbacks(this);
Thread T = new tRefreshTransactions();
T.start();
}
};
private class tRefreshTransactions extends Thread {
#Override
public void run() {
bRefreshingTransactions = true;
RetrieveTransactions();
bRefreshingTransactions = false;
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
cLastRefreshTransactions = Calendar.getInstance();
ShowToast("cLastRefreshTransactions(): " + cLastRefreshTransactions.getTime().toLocaleString());
mHandler.postDelayed(mRefreshTransactions, iRefreshTransactions);
}
};
private Handler failhandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// handle the failure somehow
}
};
}
Here's a pared-down version of the RetrieveTransactions() code:
// Retrieve the user's latest transactions from the website.
public boolean RetrieveTransactions() {
String result;
FailureReason = "";
iTransactions = 0;
// Retrieve the Page.
result = GetPage(Url);
// Strip the transactions from the page and convert them to a JSONArray.
try {
String sTransactions = textExtract(result, "var dataTable1Data=", ";\n", 0);
jTransactions = new JSONArray(sTransactions);
iTransactions = jTransactions.length();
return true;
} catch (JSONException e1) {
// Generally if it fails during this, there was no JSONArray to parse (hence no transactions).
FailureReason = "No Transactions Found";
return false;
}
}
And finally here's the pared-down code that displays the transactions in a listview, which is called at activity launch and every 5 seconds or so thereafter:
public void ShowTransactions() {
try {
if (!bRefreshingTransactions) {
if (iTransactions==0) {
return;
}
if (iTransactions==0) return;
List<String> listContents = new ArrayList<String>(iTransactions);
for (int i = 0; i < iTransactions; i++) {
listContents.add(jTransactions.getString(iTransactions - i - 1));
}
lvRecentTransactions.setAdapter(new ArrayAdapterTransactions(MyContext, listContents));
}
} catch (Exception e) {
// Do error stuff here
}
}
Thank you in advance. :)
It seems to be mutual exclusion problem. Make jTransaction synchronized or put the jTransaction variable in synchonized block.
synchronized(jTransactions ){
String sTransactions = textExtract(result, "var dataTable1Data=", ";\n", 0);
jTransactions = new JSONArray(sTransactions);
iTransactions = jTransactions.length();
}
I didn't test the code but I hope synchronization will help you.
I want to create long-running application for performing various tasks on different threads. Each task should have one-minute timeout. Here is my implementation:
runner = new Thread(new Runnable() {
#Override
public void run() { }
// some actions here
});
runner.start();
startJoin = System.currentTimeMillis();
runner.join(TIMEOUT);
stopJoin = System.currentTimeMillis();
if ((stopJoin - startJoin) >= TIMEOUT)
throw new TimeoutException("Timeout when reading the response from process");
In general case it is working and throwing TimeoutExceptions, but sometimes it is doing nothing after even few hours. So the questions is if Thread.join is reliable on Android?
I have an idea to use Thread.wait and notify instead of that, what is the better way in your opinion?
Refer below program.
public static void main(String[] args) throws InterruptedException {
long TIMEOUT=100;
Thread runner = new Thread(new Runnable() {
#Override
public void run() {
for(;;){
System.out.println("running ");
}
}
// some actions here
});
runner.start();
long startJoin = System.currentTimeMillis();
runner.join(TIMEOUT);
long stopJoin = System.currentTimeMillis();
if ((stopJoin - startJoin) >= TIMEOUT)
try {
throw new Exception("Timeout when reading the response from process");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Running Thread");
}
This program never ends that means your logic is incorrect.
Better to use TimerTask.
I prefer doing all time base task using Timer and TimerTask. Check the following code and probably this should be useful to you:
Timer t =new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
//The task you want to perform after the timeout period
}
}, TIMEOUT);
EDIT
I am giving a try at solving your problem. I am using the code written by #amicngh as my base code and have done some modifications to it. I presume that after the TIMEOUT period you want to close the running thread. Check the following code runs fine and the explanation that follows:
public class ThreadTest {
public static void main(String[] args) throws InterruptedException {
final long TIMEOUT=100;
final long startJoin = System.currentTimeMillis();
Thread runner = new Thread(new Runnable() {
long stopJoin;
#Override
public void run() {
try{
for(;;){
System.out.println("running ");
stopJoin = System.currentTimeMillis();
if ((stopJoin - startJoin) >= TIMEOUT){
throw new Exception();
}
}
}
catch (Exception e) {
// TODO: handle exception
}
}
// some actions here
});
runner.start();
synchronized (ThreadTest.class) {
ThreadTest.class.wait(TIMEOUT);
}
/*if ((stopJoin - startJoin) >= TIMEOUT)
try {
throw new Exception("Timeout when reading the response from process");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
System.out.println("Running Thread");
}
}
The Thread API description says that it is unsafe to destroy or stop (hence both these method has been deprecated) and one of the way to stop a thread is to throw an exception. Hence I am checking for the Timeout inside the runner thread. Now about making the Main thread wait it is done by the 2 lines of code which uses synchronized to synchronize the access to the thread.
Hope this code and explanation solves your problem.