Below you see some code that works fine - but only once. It is suppsed to block until the runOnUIThread is finished. And it does, when it runs the first time it is called. But when called the second time, it runs through to the end, then the runOnUIThread starts running. It could be, that after the methos was run the first time, the thread that caled it still has the lock, and when it calls the method the second time, it runs through. Is this right? And what can I do to fix that? Or is it a timing problem, the second time the caller gets the lock first?
static Integer syn = 0;
#Override
public String getTanFromUser(long accid, String prompt) {
// make parameters final
final long accid_int = accid;
final String prompt_int = prompt;
Runnable tanDialog = new Runnable() {
public void run() {
synchronized(syn) {
tanInputData = getTANWithExecutionStop(TransferFormActivity.this);
syn.notify() ;
}
}
};
synchronized(syn) {
runOnUiThread(tanDialog);
try {syn.wait();}
catch (InterruptedException e) {}
}
return tanInputData;
}
Background: The thread that calls this method is an asynctask inside a bound service that is doing transactions with a bank in the background. At unregular intervalls the bank send requests for user verification (captche, controll questions, requests for pin, etc.) and the service must display some dialogs vis a weak-referenced callback to the activities in the foreground. Since the service is doing several nested while-loops, it is easier to show the dialogs synchroniously than stopping an restarting the service (savind/restoring the state data would be too complex).
You could try if using a Callable inside a FutureTask instead of a Runnable works better. That combination is as far as I understand meant to provide return values from threads.
public String getTanFromUser(long accid, String prompt) {
// make parameters final
final long accid_int = accid;
final String prompt_int = prompt;
Callable<String> tanDialog = new Callable<String>() {
public String call() throws Exception {
return getTANWithExecutionStop(TransferFormActivity.this);
}
};
FutureTask<String> task = new FutureTask<String>(tanDialog);
runOnUiThread(task);
String result = null;
try {
result = task.get();
}
catch (InterruptedException e) { /* whatever */ }
catch (ExecutionException e) { /* whatever */ }
return result;
}
A Callable is like a Runnable but has a return value.
A FutureTask does the synchronization and waits for the result. Similar to your wait() / notify(). FutureTask also implements Runnable so it can be used for runOnUiThread.
Related
I have this piece of an activity:
public class ResultActivity extends AppCompatActivity implements ResultListener {
private String code = "";
private String data = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
code = intent.getStringExtra("code");
data = intent.getStringExtra("data");
MyExternal.DecodeAndSend(this, code, data);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Where MyExternal is a class in other library.
The method DecodeAndSend is something like this:
public static boolean DecodeAndSend(ResultListener caller, String codigo, String data)
{
try {
ExecutorService pool = Executors.newFixedThreadPool(1);
HashMap<String,String> arguments = new HashMap<>();
Future<String> resultado = pool.submit(new ServerConnection(caller, url, arguments));
String status = resultado.get();
if (status.equals("OK"))
caller.OnSuccess();
else
caller.OnError(status);
pool.shutdown();
return true;
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return false;
}
Finally, ServerConnection class implements Callable<String> so I show you the call method:
#Override
public String call() throws Exception {
Thread.sleep(2000);
return "OK";
}
The call to Thread.sleep(2000); is actually a call to a web server to send some data.
The problem is that the ResultActivity does not show its layout until the call call returns.
What is missing in this code?
DecodeAndSend is called from the main thread. It calls Future.get() which waits for the job to finish, so it's blocking the main thread. You should call this method from a background thread as well. I think it would be okay to send it to your same thread pool since it is submitted after the first job that it will wait for.
You cannot return anything about the request results from this method, because it is asynchronous.
public static void DecodeAndSend(ResultListener caller, String codigo, String data)
{
ExecutorService pool = Executors.newFixedThreadPool(1);
HashMap<String,String> arguments = new HashMap<>();
Future<String> resultado = pool.submit(new ServerConnection(caller, url, arguments));
pool.submit(new Runnable() {
public void run () {
try {
String status = resultado.get();
if (status.equals("OK"))
caller.OnSuccess();
else
caller.OnError(status);
pool.shutdown();
return;
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
caller.OnError(null); // No status, only an exception
});
}
However, your ServerConnection class already takes a caller parameter, so it should probably just handle the callback itself. And depending on what you're doing in the callback, you might want to post the callback calls to the main thread.
By the way, convention in Java is to always start method names with a lower-case letter (camel case).
Feature.get() is a blocking call. The UI Thread is blocked waiting for that call to return, hence can't take care of drawing your layout. Try passing the result listener to ResultListener to the ServerConnection and use the two callbacks to update your UI accordingly
Future.get() is a blocking call - execution stops until the result arrives
The result can only be retrieved using method get when the computation has completed, blocking if necessary until it is ready.
So your Activity's onCreate method calls that stuff, and then blocks until call (which is running on another thread) returns its result. So onCreate doesn't finish, and the layout doesn't complete.
If you want to use that blocking code, but after the view has laid out, I'd use another part of the Activity lifecycle like onStart (set a flag so you only run it once!). Otherwise you'll need to use some other concurrency technique to get your result and use it. It depends on what you're actually doing with the result of your call function
In android, there are many async APIs such as WebView's evaluateJavascript, which will Asynchronously evaluates JavaScript in the context of the currently displayed page. Usually an execution will just proceed to the successive statements after the call of an async API without any waiting.
But how can I wait until this call finishes its executing, before proceeding to the successive statements. For example,
webview.evaluateJavascript("JS code", new ValueCallback<String> {
public void onReceiveValue(String value) {
//get JS return here
}
});
//Remaining code
How can I make sure the remaining code is executed after webview.evaluateJavascript has finished its executing (i.e., its callback onReceiveValue has finished its executing).
Edit: To be more precise, what I want is that remaining code should be executed after onReceiveValue has finished executing.
I find out a workaround by using JavaScript interface. The idea is that we create a bridge class that contains a method that takes the javascript execution result as input. Then we can obtain the result at the Java end. This method works because bridge methods are invoked by JavaScript code, which is run on another thread. We only need to wait on the UI thread for a little milliseconds, then the result is here for you. The following code is an illustration:
class Bridge {
public String result = null;
#JavascriptInterface
public void putJsResult(String result) {
this.result = result;
}
public String getJsResult() {
return this.result;
}
}
Bridge bridge = new Bridge();
wv.addJavascriptInterface(bridge, "bridge");
webview.evaluateJavascript("bridge.putJsResult(func())", null);
Thread.sleep(100);
//Result is there
String result = bridge.getJsResult();
When you have to wait for code execution, a simple class to use is CountDownLatch.
An example for your problem can be:
public class AboutActivity extends Activity {
private volatile CountDownLatch jsLatch = new CountDownLatch(1);
private volatile String jsReceivedValue = null
initWebView() {
// webview init
...
webview.evaluateJavascript("JS code", new ValueCallback<String> {
public void onReceiveValue(String value) {
//get JS return here
jsReceivedValue = value
jsLatch.countDown();
}
});
try {
// wait 60 seconds or assume there was some problem during the loading
jsLatch.await(60, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// thread interrupted or time elapsed
}
if (jsReceivedValue == null) {
// show "problem during loading"
} else {
//Remaining code
}
}
}
Note that waiting for code execution on main thread, can lead to unresponsive app.
You can show a loading spinner while using a simple thread to avoid this:
new Thread(new Runnable() {
#Override
public void run() {
initWebView();
}
}).start();
I want to save all the messages received in the onMessageReceived of the service inside a SQLite db.
I was planning to open the db, insert the data and close the db. This would work well with an intent service as all the calls to the onMessageReceived would be queued and thus execute one by one.
However if the onMessageReceived gets called concurrently for multiple messages, it could cause issues of the Db being closed while another call is trying to write thus leading to issues.
Can anyone confirm what kind of behaviour i should expect.
If it is not an intent service, i might have to look at the DB singleton pattern and synchronization blocks
Currently, FirebaseMessagingService extends Service directly, so it is not an IntentService.
Source
Snapshot:
You can check LinkedBlockingDeque<> class which queues your requests and can be performed in background sequentially.
Check below sample class of mine -
public class Processor implements Runnable {
private final LinkedBlockingDeque<Task> mTaskQueue = new LinkedBlockingDeque<Task>();
private boolean mExecuteTask = true;
#Override
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
// You can put some end condition if needed
while (mExecuteTask) {
Task task;
try {
// Waits if necessary until an element becomes available
task = (Task) mTaskQueue.take();
} catch (InterruptedException e) {
continue; // re-test the condition on the eclosing while
}
if (task != null) {
task.runnable.run();
}
}
}
// Call this method to put Runnable in Queue.
public synchronized void put(int id, Runnable runnable) {
try {
Task task = new Task();
task.runnable = runnable;
task.id = id; // someUniqueId to avoid duplication
// Check Id of tasks already present in Queue
mTaskQueue.addLast(task);
} catch (IllegalStateException ie) {
throw new Error(ie);
}
}
private static class Task {
public Runnable runnable;
// Unique Id of task
public int id;
}
}
I have written schedule task by using timer. It is working fine withing single activity.But when i am going to another activity it is not working.My intention is to send data to the server some particular time interval. I am giving the code snippet. I am sorry for the format.
private void login()
{
try {
EditText userNameET = (EditText)findViewById(R.id.userName);
EditText passwordET = (EditText)findViewById(R.id.password);
String userName = userNameET.getText().toString();
String password = passwordET.getText().toString();
boolean isLoginOK = isValidUser(userName, password);
String autoSynchStrVal = "";
String autoSyncFreqStr = "";
long autoSyncFreqInMiliSec = 3600000; // default 1 hrs
if (isLoginOK) {
//added by anirban
CommonUtils.IS_NEW_VERSION_AVAILABLE = isNewVersionAvailable();
CommonUtils.IS_NEW_Notification_AVAILABLE = isNewNotificationAvailable();
autoSynchStrVal = CommonUtils.getPolicyValue(appInstance, "IS_MOBI_AUTO_SYNCH_REQ", 0, 0);
if(autoSynchStrVal != null && !"".equals(autoSynchStrVal) && "1".equals(autoSynchStrVal)){
//boolean isAllTransactionsUploaded = false;
// boolean isAllTransactionsUploaded = VersionCheckingActivity.isAllTransactionsUploaded();
// boolean isMobiEligibleForAutoSync = UploadDownload.isMobiEligibleForAutoSync(appInstance ,isAllTransactionsUploaded);
// if(isMobiEligibleForAutoSync){
autoSyncFreqStr = CommonUtils.getPolicyValue(appInstance, "MOBI_AUTO_SYNCH_FREQUENCY", 0, 0);
if(autoSyncFreqStr != null && !"".equals(autoSyncFreqStr)){
autoSyncFreqInMiliSec = (long) (Double.valueOf(autoSyncFreqStr) * 60 * 60 * 1000); // in millisecond
}
/* boolean isMobiEligibleForAutoSync = false;
try {
isMobiEligibleForAutoSync = UploadDownload.isMobiEligibleForAutoSync(appInstance ,
VersionCheckingActivity.isAllTransactionsUploaded());
if(isMobiEligibleForAutoSync){
_doSynch();
}
} catch (UDBAccessException e) {
e.printStackTrace();
} */
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
ULoginActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// here we are checking again for eligibility for auto synch
boolean isMobiEligibleForAutoSync = false;
try {
isMobiEligibleForAutoSync = UploadDownload.isMobiEligibleForAutoSync(appInstance ,
VersionCheckingActivity.isAllTransactionsUploaded());
Log.d("inside Run : ", "before Synch");
if(isMobiEligibleForAutoSync){
_doSynch();
Log.d("inside Run : ", "after Synch");
}
} catch (UDBAccessException e) {
e.printStackTrace();
}
}
});
}
}, 1000, autoSyncFreqInMiliSec); //here interval is autoSyncFreqInMiliSec
}
endAction(RESULT_LOGIN_OK, null); // it will finish the activity
} else {
// showing login error
TextView login_msg = (TextView)findViewById(R.id.login_screen_msg);
login_msg.setTextAppearance(this, R.style.error_msg);
//login_msg.setTextColor(Color.RED);
login_msg.setText("Login failed.");
}
} catch (UDBAccessException e) {
UUIHandlers.showErrorMessage(this, e.getMessage());
}catch (Exception e) {
UUIHandlers.showErrorMessage(this, e.getMessage());
}
}
To make it work when you leave the current activity, you have to run that code of snippet on the background service.
As you are executing on the current Activity it runs the code for the first time, but as you leave the activity the code wont be triggered itself unless it is registered to a background service.
Here and here you have examples on how to use them
If you want to execute something after some time, even when your activity is not currently in the foreground, you can use the AlarmManager.
Note: The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.
If you want to periodically send information to a server, I suggest you use a Service or an IntentService.
A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.
You can find a good example using a LocalService also here.
Finally got the solution .
Now from Async task( different thread), You are trying to insert data in the database which is locked by UI thread. This will throw an exception because the first write has a lock on the db.
If you hold your timer in a field of your activity (Activity subclass) it will probably go away once you launch another activity. Consider moving your timer to service (Service subclass). This will hold your timer going regardless of your activity flow.
Read this for reference about services:
https://developer.android.com/guide/components/services.html
Is it possible for a background thread to enqueue a message to the main UI thread's handler and block until that message has been serviced?
The context for this is that I would like my remote service to service each published operation off its main UI thread, instead of the threadpool thread from which it received the IPC request.
This should do what you need. It uses notify() and wait() with a known object to make this method synchronous in nature. Anything inside of run() will run on the UI thread and will return control to doSomething() once finished. This will of course put the calling thread to sleep.
public void doSomething(MyObject thing) {
String sync = "";
class DoInBackground implements Runnable {
MyObject thing;
String sync;
public DoInBackground(MyObject thing, String sync) {
this.thing = thing;
this.sync = sync;
}
#Override
public void run() {
synchronized (sync) {
methodToDoSomething(thing); //does in background
sync.notify(); // alerts previous thread to wake
}
}
}
DoInBackground down = new DoInBackground(thing, sync);
synchronized (sync) {
try {
Activity activity = getFromSomewhere();
activity.runOnUiThread(down);
sync.wait(); //Blocks until task is completed
} catch (InterruptedException e) {
Log.e("PlaylistControl", "Error in up vote", e);
}
}
}