I am using facebook graph request for uplaoding video. This api has onProgressCallback method which gives current bytes written and maximum bytes that can be written for a file as follows:
#Override
public void onProgress(final long current, final long max) {
if (isFirstLoad) {
progressBarHorizonatl.setProgress(0);
progressBarHorizonatl.setMax((int) max);
isFirstLoad = false;
}
progressBarHorizontal.setProgress((int) current);
}
this method is called repeatedly while uploading the video but progress bar is not updated. It will get updated at the last call only. Can anyone help me what might be the problem.
Update ProgressBar on UI thread. Try attached code.
#Override
public void onProgress(final long current, final long max) {
if (isFirstLoad) {
progressBarHorizonatl.setProgress(0);
progressBarHorizonatl.setMax((int) max);
isFirstLoad = false;
}
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Log.d("UI thread", "I am the UI thread");
progressBarHorizontal.setProgress((int) current);
}
});
}
Related
In my program, it is needed to receive user latitude and longitude as soon as GPS is Enabled... I'm using onGpsStatusChanged to constantly check GPS Status and the checking works... The only problem is that it tries to retrieve user location instantly, and it returns latitude 0.0 and longitude 0.0 cause it takes some seconds to get those informations... If I try to retrieve some seconds later using clickListener on a button it works perfectly...
Then I thought: If I could make the device wait some seconds after GPS is Enabled and only then retrieve the coordinates it would work...
But: If I use another Thread or AsyncTask (already tried both), it keeps returning 0.0 for coordinates, cause the real coordinates are cached into the Map's Main Activity Thread...
So, how to make android wait in the main Thread? I've tried 'wait(long)' and the app crashes. I'm trying to solve this for weeks and my time is running out... Some holy soul help me please
you can achieve that by using handler
int time=3000 // in milliseconds
Handler h=new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
//here you can do the job
}
},time);
if you want to update the UI from the handler you will end up with an error but you can userunOnUiThread
runOnUiThread(new Runnable() {
#Override
public void run() {
//code to update the ui
}
});
good luck
i not recommend you handler,you can use Interface here.
where you get all values use pass it to your activity and use that one.
Here i have posted example just try to follow and use this way.
You can pass interval here according to your need.
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 30000
and one more thing you can pass fastest interval that is also help you.
Thanks
I have been creating a simple Waiter class for it. It is really easy to understand and does the job very well. I post it for those who need it. just copy Waiter class and WaitListener interface and use it like I show.
Here is the Class:
import android.os.Handler;
import android.os.Looper;
public class Waiter {
WaitListener waitListener;
int waitTime = 0;
Handler handler;
int waitStep = 1000;
int maxWaitTime = 5000;
boolean condition = false;
public Waiter(Looper looper, final int waitStep, final int maxWaitTime){
handler = new Handler(looper);
this.waitStep = waitStep;
this.maxWaitTime = maxWaitTime;
}
public void start(){
handler.post(new Runnable() {
#Override
public void run() {
waitListener.checkCondition();
if (condition) {
waitListener.onConditionSuccess();
} else {
if (waitTime <= maxWaitTime) {
waitTime += waitStep;
handler.postDelayed(this, waitStep);
} else {
waitListener.onWaitEnd();
}
}
}
});
}
public void setConditionState(boolean condition){
this.condition = condition;
}
public void setWaitListener(WaitListener waitListener){
this.waitListener = waitListener;
}
}
And here is the Interface :
public interface WaitListener {
public void checkCondition();
public void onWaitEnd();
public void onConditionSuccess();
}
You can for example use it like that for a connection check:
ConnectivityManager mConnMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final int result = mConnMgr.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, "enableMMS");
final Waiter waiter = new Waiter(getMainLooper(), 1000, 5000);
waiter.setWaitListener(new WaitListener() {
#Override
public void checkCondition() {
Log.i("Connection", "Checking connection...");
NetworkInfo networkInfo = mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS);
waiter.setConditionState(networkInfo.isConnected());
}
#Override
public void onWaitEnd() {
Log.i("Connection", "No connection for sending");
//DO
}
#Override
public void onConditionSuccess() {
Log.i("Connection", "Connection success, sending...");
//DO
}
});
waiter.start();
I am currently building an app that plays music on a wifi speaker. The app can connect to multiple speakers, and each speaker plays different music.
Due to frequent loss in receiving the song playing progress sent by the speakers to the app, I have to run one timer for each speaker that is playing a music in order to keep track of the song progress continuously. So that every time I receive a song progress, I will just update the timer, and then the timer will start counting from the updated song progress.
This is the code that runs a timer.
public class SongTimer
{
Timer mTimer;
int count;
long duration;
int groupAddress;
SongTimerListener listener;
boolean timer;
private Handler mHandler = new Handler();
public interface SongTimerListener
{
public void onPositionCounted(int position);
public void onFinishCounting();
}
public SongTimer(int position, long duration, int groupAddress, SongTimerListener listener)
{
this.listener = listener;
this.count = position;
this.duration = duration;
this.groupAddress = groupAddress;
timer = true;
}
public void startTimer()
{
mTimer = new Timer();
mTimer.schedule(new TimerTask()
{
#Override
public void run()
{
if (timer)
{
if(count<=(duration/1000))
{
mHandler.post(new Runnable()
{
public void run(){
if (DataHolder.PlayProgress.containsKey(DataHolder.tSpeaker.mAddress))
{
long progress = DataHolder.PlayProgress.get(DataHolder.tSpeaker.mAddress);
count=(int)progress;
}
}
});
}
else
{
mHandler.post(new Runnable()
{
public void run()
{
count = 0;
}
});
}
}
else
{
mHandler.post(new Runnable()
{
public void run()
{
mTimer.cancel();
mTimer = null;
if(SongTimer.this.listener != null)
{
SongTimer.this.listener.onFinishCounting();
}
}
});
}
count++;
if(SongTimer.this.listener != null)
{
SongTimer.this.listener.onPositionCounted(count);
}
}
}, 1000, 1000);
}
public void stopTimer()
{
timer = false;
DataHolder.PlayProgress.put(this.groupAddress, (long)count);
}
}
The user chooses a speaker and then one timer will be started when user plays a music with the speaker. When the user switches to another speaker and plays a song with it, a new timer will be started again. All the timers that were started will be stored in a HashMap using the groupAddress as the key for the object, timer.
When user taps pause, timer will be fetch from the HashMap and then terminate it, but the last position counted will be remembered.
When user taps resume time will be started again (new Timer()) and then starts counting from the last position stored.
Here comes the problem:
When multiple timers start to run, they work fine. But when the user taps pause, one timer will be fetch from the HashMap and then terminate it. But unfortunately all timers were terminated at the same time. I checked the Log for the object ID of the timers, they were all different. So I don't understand what is wrong here.
Please help. Many Thanks!
try this one
public class SongTimer{
int count;
long duration;
int groupAddress;
SongTimerListener listener;
boolean timer,run;
View user; //the view who this is going to be attached to
public interface SongTimerListener {
public void onPositionCounted(int position);
public void onFinishCounting();
}
//your constructor
public SongTimer(int position, long duration, int groupAddress,
SongTimerListener listener, View viewToAttach){ //added new parameter
this.listener = listener;
this.count = position;
this.duration = duration;
this.groupAddress = groupAddress;
timer = run = true;
user = viewToAttach;
new Thread(new Runnable() { // your timer
#Override
public void run() {
while(run){
if(!timer)
continue;
//now add your implementation here, (its too late here)
//put your code that you already have here, but minor changes
//if you need to call a Ui method use the user.post(runnable); it
// the same as handler.post(runnable), also with this you have
// reference to your view to which you want to alter, so all you
// to do is do what you want to do easily without actually needing
// your interface call. and all Views that they rely on the music
//mechanism that you talked about will each have an instance of this
//class. your pausing mechanism has already being implemented so
//maintain your old pausing mechanism. Also if you are done and want
// totally stop the thread or kill this class set the boolean run
//variable to false.
}
}).start();
}
hope it helps
I have a splash screen implementation on Codename One with an animated text sequence. I do not want to use the nextForm property on my Splash Form since I want the sequence complete before I navigate. Hence, I have used showForm. It works fine on the emulator but when I test on a real device, the next form I have loaded programmatically takes time to load, the transition is slow and sometimes it crashes. I cant seem to figure out why...
I have included the sample code below:
#Override
protected void beforeSplash(Form f) {
// If the resource file changes the names of components this call will break notifying you that you should fix the code
super.beforeSplash(f);
final String text = "Sample text to be animated here for testing purpose!";
final SpanLabel l = findSloganLabel(f);
Animation anim = new Animation() {
private long lastTime = System.currentTimeMillis();
public boolean animate() {
long t = System.currentTimeMillis();
int i = l.getText().length();
if (t - lastTime >= 450) {
if (i == text.length()) {
showForm("Register", null);
return false;
} else {
System.out.println("Animating Label...");
if (i == text.length() - 1) {
l.setText(text);
l.revalidate();
} else {
l.setText(text.substring(0, i) + "_");
l.revalidate();
}
}
lastTime = t;
}
return false;
}
public void paint(Graphics g) {
}
};
f.registerAnimated(anim);
}
You can do something like this:
#Override
protected void postSplash(Form f) {
UITimer timer = new UITimer(new Runnable() {
public void run() {
showForm("MainForm", null);
}
});
timer.schedule(XX-MiliSec, false, f);
}
So in your splash form's postForm method add timer..
And schedule it after XX Milli-seconds (whatever your animation duration is)
It will execute showForm() method after that mentioned Milli-seconds
You have two simple options, the first which I think it better is to not use the "next form" property and then just invoke showForm("mainFormName", null) when the animation completes.
The second is really how the next form was designed to work, its designed for you to do a background process on a background thread that might take time, to simulate this we sleep for a few seconds but you should override that method to do whatever you want. Just override this in your state machine and do whatever you want:
protected boolean processBackground(Form f) {
try {
Thread.sleep(3000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
return true;
}
You're looking for an AnimationListener
anim.setAnimationListener(new Animation.AnimationListener() {
#Override public void onAnimationStart(Animation animation) {
}
#Override public void onAnimationEnd(Animation animation) {
showForm();
}
#Override public void onAnimationRepeat(Animation animation) {
}
});)
I have a handler used to display images in a specified interval loop, on reaching the last image, it goes back to the first image which is the correct. However, i'm having problems with it as it's causing some devices to crash and makes the CPU usage go up significantly, i'm just wondering what is wrong with the code?
I instantiate it like the following at the top of the fragment:
final public static Handler handler = new Handler();
boolean isRunning = false;
Then in the onPostExecute part of an AsyncTask, I have this code:
#Override
protected void onPostExecute(Void v) {
if(!isRunning) {
Runnable runnable = new Runnable() {
#Override
public void run() {
anImageView.setVisibility(View.VISIBLE);
isRunning = true;
counter++;
//imageDownloader.download(data.get(i).getImageURL(), anmageView);
if(TabsViewPagerFragmentActivity.theImages !=null && TabsViewPagerFragmentActivity.theImages.size() > 0){
Bitmap anImage = TabsViewPagerFragmentActivity.theImages.get(i);
anImageView.setImageBitmap(anImage);
}
i++;
if(i>TabsViewPagerFragmentActivity.theImages.size()-1)
{
i=0;
}
handler.postDelayed(this, 1500);
}
};
handler.postDelayed(runnable, 0);
}
}
The above AsyncTask is called within the onCreate() method.
Secondly, I have a refresh button which re-downloads these images in order to get the latest ones as they change periodically. Therefore I have an onClick() event attached to the refresh button. This also works fine but here is the code which is called:
#Override
protected void onPostExecute(Void v) {
for(int i=0;i<data.size()-1;i++) {
Bitmap anImage = getBitmapFromURL(data.get(i).getImageURL());
theImagesRefreshed.add(anImage);
}
if(!isRunning) {
Runnable runnable = new Runnable() {
#Override
public void run() {
anImageView.setVisibility(View.VISIBLE);
isRunning = true;
counter++;
//imageDownloader.download(data.get(i).getImageURL(), anImageView);
if(theImagesRefreshed !=null && theImagesRefreshed.size() > 0){
Bitmap anImage = theImagesRefreshed.get(i);
anImageView.setImageBitmap(anImage);
}
i++;
if(i>theImagesRefreshed.size()-1)
{
i=0;
}
handler.postDelayed(this, 1500);
}
};
handler.postDelayed(runnable, 0);
}
}
I think that the handler is not setup right and is causing the performance issues. Can anyone see anything wrong with this code?
Thanks in advance!
You need to call Looper.prepare() while using handlers in threads .So write Looper.prepare() after you are creating instance of Runnable
I'm trying to make a countdown timer in android for use in a small android app. The app will countdown from some number of seconds to 0, upon which it will do some action. I'm using the coundowntimer supplied by android.os.countdowntimer. Here is my code:
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quizlayout);
new CountDownTimer(30000, 1000) {
TextView tx = (TextView) findViewById(R.id.textView2);
public void onTick(long millisUntilFinished) {
tx.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
tx.setText("done!");
}
}.start();
}
However, this countdown timer is really slow. It takes like 3 real-time seconds for the timer to countdown by one second. I wonder what's going on? The code I have above is more or less copied straight from google (CountDownTimer)
Can anyone help me as per why my timer is so slow, and offer a way to speed it up a bit?
(EDIT): I am running this on an emulator, the intel atom x86. I am emulating an android 2.3.3 environment.
According to Android documentation for countdown timer
The calls to onTick(long) are synchronized to this object so that one call to onTick(long) won't ever occur before the previous callback is complete. This is only relevant when the implementation of onTick(long) takes an amount of time to execute that is significant compared to the countdown interval.
Take a look at this example for countdown timer
Countdown timer example
Alternately you can spawn a new thread and just get that thread to sleep for the interval you want and take actions when it wakes or vice versa.
You can also timertask
use a handler that will post the same runnable . this will remove the need for extra threads :
Handler handler=new Handler();
handler.postRunnable(... , 1000) ;
in the runnable , call the postRunnable again for the same handler (and add a condition for when to stop) .
CountDownTimer is not efficient regardless to ui updating performances. For a flawless ui update, it is better to create a custom countdown. I did my own so here it is. It is flawless on my app.
public abstract class CountDown {
int totalTime = 0;
int tickTime = 0;
Thread thread;
boolean canceled = false;
public CountDown(int totalTime,int tickTime){
this.totalTime = totalTime;
this.tickTime = tickTime;
}
public abstract void onTick();
public abstract void onFinish();
public void start(){
thread = new Thread(new Runnable() {
#Override
public void run() {
// Do in thread
canceled = false;
for (int elapsedTime = 0; elapsedTime < totalTime; elapsedTime += tickTime) {
if(!canceled){
onTick();
try {
thread.sleep(tickTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
break;
}
}
if(!canceled){
onFinish();
}
}
});
thread.start();
}
public void cancel(){
canceled = true;
}
}
Remember that every time you have to update your ui, call a runOnUiThread, or else you will have an exception, you are not in a handler and not on ui thread.
Here is how to use it in your code, it is identical to CountDownTimer, so you could just rename lines in your code :
CountDown cDown = new CountDown(10000, 20) {
public void onTick() {
// Do something
}
public void onFinish() {
runOnUiThread(new Runnable() {
#Override
public void run() {
myButton.setImageDrawable(drawable);
}
});
}
};