I'm a new android developer,
Due to security reasons, I want to make input delay in my sign in action, (Just showing a ProgressDialog for like 2 seconds and then continuing the main procedure). I already know how I can do it using MultiThread programming, but since there is nothing going on in the other thread, I thought maybe there can be some way to do it without using background workers.
I would be glad if you could tell me an easy way to do it in android
Thanx
I suggest you to use Action Bar Sherlock you don't need threading. Just call
setSupportProgressBarIndeterminateVisibility(boolean)
i think learning this api harder than using threads but new generation Android (after api 11) apps generally use action bar progress.
You can delay the main thread for 2 sec.
Well, just for the future reference, I found another way to solve this problem using Timer, I think it's better than Background Thread, I created a wrapper function which calls the main event after an specific amount of time
public void onClick(View view) {
try {
progressDialog = ProgressDialog.show(this, "sometitle", "somecontent");
/**
* input delay
*/
Timer delayWorker = new Timer();
TimerTask task = new TimerTask() {
public View view = null;
#Override
public void run() {
onClickAction(view);
this.cancel();
}
};
task.getClass().getField("view").set(task, view);
delayWorker.schedule(task, INPUT_DELAY);
} catch (Exception e) {
/**
* error occurred
*/
}
}
private void onClickAction(View view) {
/**
* actual action click
*/
}
Related
I am trying to write an app that shows the user a string on textview, and replace the text due to user input. This should happen on time intervals of 60 seconds.
I tried to use a countdown timer, which sets a boolean var to false on it's onFinish method. While this boolean is true, I am trying to change the strings in the textview (further work will be to change the text due to the user actions, but I'm still trying to get this work for simple actions).
For now, the app seems to be stucked and nothing happens, but if I am removing the while loop, there is a single text on the screen (as it should be).
Is there a problem using a while loop for that purpose? Is there a different way to work along with the timer?
(p.s I know there are some problems in the code, but this is just for isolating the problem. Thanks!)
EDIT:
I will try to clarify my intentions:
I want to give the user tasks, which he should perform in a given time. I want to display the time remaining on the screen, along with the task to perform. When the user finishes the task, if there is still time on the clock, he will press a button and another task will appear. The goal is to finish as many tasks as possible in the given time.
My code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_game);
Bundle b = getIntent().getExtras();
game = b.getParcelable("game_record");
figuresList = new ArrayList<String>(game.getFiguresList());
clockView = (TextView) findViewById(R.id.clockView);
figureText = (TextView) findViewById(R.id.figureText);
timer = new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
clockView.setText(Long.toString(millisUntilFinished / 1000));
}
public void onFinish() {
clockView.setText("done!");
isTurn = false;
}
};
playRound();
}
private void playRound() {
figuresIterator = figuresListUsage.iterator();
isTurn = true;
String nextFigure = figuresIterator.next();
timer.start();
while (isTurn == true) {
figureText.setText(nextFigure);
nextFigure = figuresIterator.next();
}
}
It's a little difficult to understand your games logic but the main problem i see with your code is that you are entering the loop in a lifecycle event handler. Take a look at this lifecycle description. You are stopping it in onCreate and there is still work to be done before the activity will finish its lifecycle handling.
I suggest you try making play round event bound or use a diffrent thread for it. there are alot of threading APIs for android and as i dont know the nature of your game rounds i cant recommend any.
I am having a application which have a splash screen. My problem is i need a splash screen with the pinwheel spinner(progress bar). I have also added the android java code.
Java code
package com.SSF;
import android.os.Bundle;
import android.widget.Toast;
import com.worklight.androidgap.WLDroidGap;
public class SSF extends WLDroidGap {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
/**
* onWLInitCompleted is called when the Worklight runtime framework initialization is complete
*/
#Override
public void onWLInitCompleted(Bundle savedInstanceState){
super.loadUrl(getWebMainFilePath());
// Add custom initialization code after this line
}
}
Having a splash screen is redundant, and should be avoided unless maybe it's the first run of the app. Users like to open the app and start using it right away.
Only really heavy apps (mostly games ) need to load a lot of things, but even there, there are plenty of optimizations to make it short (just load what it needs in the near future, for example).
Anyway, for the progress bar, just create a layout with a progress bar view in the middle, use "setContentView" on it, and that's it...
You can also customize the progress bar by yourself, for example using this post.
You can try this code. please
public class MainActivity extends Activity {
private ImageView splashImageView;
boolean splashloading = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
splashImageView = new ImageView(this);
splashImageView.setScaleType(ScaleType.FIT_XY);
splashImageView.setImageResource(R.drawable.ic_launcher);
setContentView(splashImageView);
// interesting music
/**
* Gets your sound file from res/raw
*/
splashloading = true;
Handler h = new Handler();
h.postDelayed(new Runnable() {
public void run() {
splashloading = false;
setContentView(R.layout.activity_main);
}
}, 3000);
}
Best of luck!
try below code:-
// METHOD 1
/****** Create Thread that will sleep for 5 seconds *************/
Thread background = new Thread() {
public void run() {
try {
// Thread will sleep for 5 seconds
// show progress bar here
sleep(5*1000);
// After 5 seconds redirect to another intent
Intent i=new Intent(getBaseContext(),FirstScreen.class);
startActivity(i);
//Remove activity
finish();
// hide progress bar here
} catch (Exception e) {
}
}
};
// start thread
background.start();
for more info see below link:-
http://androidexample.com/Splash_screen_-_Android_Example/index.php?view=article_discription&aid=113&aaid=135
http://www.androidhive.info/2013/07/how-to-implement-android-splash-screen-2/
Up until Worklight 6.2 it was not possible to customize the splash screen in a Worklight-based Android application, be it adding a spinner, extending the time the splash is displayed or creating an entirely customized experienced.
Starting Worklight 6.2 the entire flow is customizable if the developer so chooses. This is documented at: Managing the splash screen in an Android-based hybrid application, which also provides various code examples.
BTW, you already asked about this... Splash Screen with loading in four environment(android,ios,blackberry and windows) using html coding or common plugin for hybrid apps
In android why should we use a asyntask and service, instead of using a new thread() and write the necessary background functionality?
I know that we should not run long running operations like downloading a file from server on the mainthread aka UI thread. And should use a asynctask or service.
But why cant we create a new thread() {which is eventually a new thread other than the main thread} and write necessarily long running operation in that thread.
why did google create the AsyncTask and Service without suggesting to use the regular New Thread()???
thanks in advance
edit1:
may be i wasn't clear in my question or not sure, if i am, even now. help me out.
i get it, the whole point starts from
Do not block the UI thread
Do not access the Android UI toolkit from outside the UI thread
why ?
1.how much can the UI thread handle ? how can we determine a breakpoint? how is a ANR point determined? can we track?
2. when a service component handles long running operations why can't a activity component handle?
Remember that if you do use a service, it still runs in your application's main thread by default, so you should still create a new thread within the service if it performs intensive or blocking operations
http://developer.android.com/guide/components/services.html
the above statement is from android documentation.
3.why cant a service start in a new thread straight away, if we are so concerned about main thread? don't get me wrong in question 3, i am trying to understand the advantage of starting the service in main thread. by default.
in the above statement , does it suggest the main thread's ability to start and handle a service's long running operation load? if so does it contradict with question 1.
Well let's look how you'd perform a simple task using a Thread.
The first step is to create a Thread using a Runnable. Something like this:
private void fetchResultsAsync() {
Runnable runner = new Runnable() {
#Override
public void run() {
List<String> results = fetchResultsFromWebServer();
}
};
new Thread(runner).run();
}
The thing is, we need to show the results so it would actually be more like this:
private void fetchResultsAsync() {
Runnable runner = new Runnable() {
#Override
public void run() {
List<String> results = fetchResultsFromWebServer();
workFinished(results);
}
};
new Thread(runner).run();
}
private void workFinished(List<String> results) {
// show the results on the UI
}
It looks good, but there's a problem; the callback method (workFinished) has to update the UI. If we do this from any non-main thread, there will be big problems. We need a thread-safe way to call that method, which is what Handlers are for. Let's also throw in a method for updating our progress, which is very common. The code would now look like this:
private final Handler myHandler = new Handler();
private void fetchResultsAsync() {
Runnable runner = new Runnable() {
#Override
public void run() {
List<String> results = fetchResultsFromWebServer();
workFinished(results);
}
};
new Thread(runner).run();
}
private void showProgress(int result) {
myHandler.post(new Runnable() {
#Override
public void run() {
// update a progress bar here
}
});
}
private void workFinished(final List<String> results) {
myHandler.post(new Runnable() {
#Override
public void run() {
// show the results on the UI
}
});
}
Compare this to the implementation using an AsyncTask:
private void fetchWithTask() {
new AsyncTask<Void, Integer, List<String>>() {
#Override
protected List<String> doInBackground(Void... params) {
return fetchResultsFromWebServer();
}
#Override
protected void onPostExecute(List<String> strings) {
// show the results on the UI
}
#Override
protected void onProgressUpdate(Integer... values) {
// update a progress bar here
}
}.execute();
}
It doesn't differ much by lines of code, but it's much more obvious what needs to happen and where. It protects you from nasty mistakes like forgetting to wrap UI-touching code in a Runnable that has to be posted to a UI-Thread-owned Handler.
Now imagine that you have several different types of small background tasks that need to be performed. It would be very easy to call the wrong showProgress or workFinished method from the wrong background Thread because you have to plug all those pieces together yourself.
There's also a very nasty bug lurking in the use of Handler's default constructor. If the containing class is first referenced by a non-UI thread during runtime, the Handler would belong to that Thread. AsyncTask hides always does things on the correct Thread. This is hard to catch!
At first blush AsyncTasks don't seem all that useful, but the callback plumbing is where they really pay off in spades.
"instead of using a new thread() and write the necessary background functionality?"
Why rewrite the background functionality? AsyncTask does it for you. As njk2 mentioned a Service is not really a fair comparison, though IntentService automatically creates a new thread for you in onHandleIntent().
edit: To answer your other questions, blocking the UI thread, will block all user interaction and the app will appear to "freeze". Definitely not something we want to do at all.
I'm re writing an IOS app in android. It's a task I've set to try and learn android.
In android I've being learning about different async messaging options. What I have found so far are:
Callbacks
Broadcasts
Message Handlers
I'm trying to decide which approach is best to suit my purposes. In my IOS application I have 10 screen objects and 1 coordinator object. This is my n-1.
The way my ios currently works is my screen object calls a work method in my coordinator passing itself as a delegate. The coordinator performs some async work and calls various methods on the delegate when the job is done : completed / failed with reason etc.
Multiple screen objects can request work to be done at the same time.
So far my feeling that the callback / message handler approaches in android is more like a 1-1 relationship.
I'm leaning towards using the local broadcast manager. This does seem more like NSNotification than delegate methods but seems made for n-1 relationships.
Is the broadcast manager the best way to achieve n - 1 async work ?
Also are my assumption about the 1-1 relationship of callbacks and handlers correct?
You can indeed use the broadcasts like NSNotification, but I would generally use broadcasts to message between different parts of my App, for example to communicate between a Service and an Activity, rather than within a specific part.
I don't see why you can't do exactly what you do in iOS on android as well. You would have a protocol in iOS defining what functions to call, and you can do the same in Java/Android by using interfaces.
In iOS you would have something like:
doStuffWithObject:(NSObject<SpecialStuff> *)object {}
while in Java you would have:
doStuffWithObject(SpecialStuff object) {}
with SpecialStuff being your protocol or interface.
Because you don't have performSelectorOnBackground in android its a bit more work. Either use Timers, perhaps a separate Thread in combination with Handlers or use ASyncTask depending on what serves you best and how big the asynchronous task is.
ASyncTask is definitely worth looking into.
You could of course also make use of Observer and Observable.
A simple example with an handler and a timer that notifies its listeners of a new time every second (note that the handler is created on the main thread in this case, such that you can send messages back similar to using performSelectorOnMainThread in iOS):
class SomeExample {
private final ArrayList<TimeListener> timeListeners;
private final Handler handler = new Handler();
private final TimeUpdateRunnable timeUpdateRunnable = new TimeUpdateRunnable();
public SomeExampleView {
timeListeners = new ArrayList<TimeListener>();
updateTimer = new Timer("General Update Timer");
TimeUpdateTask timeUpdateTask = new TimeUpdateTask();
updateTimer.scheduleAtFixedRate(timeUpdateTask, (60 * 1000) - (System.currentTimeMillis() % (60 * 1000)), 60 * 1000);
}
public void addTimeListener(TimeListener timeListener) {
timeListeners.add(timeListener);
}
public boolean removeTimeListener(TimeListener timeListener) {
return timeListeners.remove(timeListener);
}
class TimeUpdateTask extends TimerTask {
public void run() {
handler.post(timeUpdateRunnable);
}
}
private class TimeUpdateRunnable implements Runnable {
public void run() {
for (TimeListener timeListener : timeListeners) {
timeListener.onTimeUpdate(System.currentTimeMillis());
}
}
}
}
And my listener interface which is similar to Observer
public interface TimeListener {
void onTimeUpdate(long time);
}
I am now working on an android app in which I need to display a text after some processing is done.
I'm using a Thread to run a process in the back while my progress dialog is being displayed to the user. The Thread works properly and I've followed it step by step and, apparently, it also ends fine; however, the method in which I call it does not seem to come to an end (at least, during a normal cycle) because the text I am setting afterward does display immediately, I have to wait and do some other action (like in order for it to display
Below is the piece of code I'm having trouble with:
private OnClickListener saldoDisp = new OnClickListener(){
public void onClick(View v){
int x = s2.getSelectedItemPosition();
branchSel = arrSucsId[x];
mainProc();
saldoAdminTex.setText(strSaldo); //The late one
}
};
public void mainProc(){
chekP = new Thread (null,doProc,"Background");
chekP.start();
mProgress =ProgressDialog.show(SivetaAsaldo.this, "","Obteniendo saldo...",true, false);
}
private Runnable doProc = new Runnable(){
public void run(){
if(getSaldoAdmin(levelSel,branchSel))
{
mProgress.dismis();
Log.i(TAG,"Task completed properly");
}else
handler.post(tosti);
}
};
So I do get the "Task completed properly" but seems like it still waits for something else, any clues guys?
Thanks for taking a bit of your time to check it out =).
saldoAdminTex.setText(strSaldo); //The late one
is going to get called immediately. It doesn't wait until after the Thread started in mainProc ends. You also cannot dismiss the Progress Dialog in your runnable. You can only do UI related things on the main UI thread.
It would help you to read the article on Painless Threading on the Android Dev site.
About your ProgressDialog, please see this answer about how to use a AsyncTask with a ProgressDialog.
Looking at your code, this:
saldoAdminTex.setText(strSaldo);
would potentially be executed before your thread finishes as the thread will be running in parallel to that line.
An alternative way would be to do this:
public void mainProc(){
mProgress =ProgressDialog.show(SivetaAsaldo.this, "","Obteniendo saldo...",true,false);
handler.post(new Runable(){
public void run(){
if(getSaldoAdmin(levelSel,branchSel))
{
mProgress.dismis();
saldoAdminTex.setText(strSaldo);
Log.i(TAG,"Task completed properly");
}else
handler.post(tosti);
}
});
}