I have an android app which sends likes to the server.
What i want to do is not to send a like to server immediately but send after 2 secs if user still likes the post.
My like void;
public void rotationAnimation(ImageView button, int source1, int source2){
if(isLikeClicked){
button.setImageResource(source1);
button.startAnimation(rotate_backward);
isLikeClicked = false;
}else{
button.setImageResource(source2);
button.startAnimation(rotate_forward);
isLikeClicked = true;
}
ChangeLikeCount();
if(isReadyToPost)
if(!isLikeClicked){
Like like = new Like();
like.execute(ServerCons.HOST + "unlike");
}else{
Like like = new Like();
like.execute(ServerCons.HOST + "like");
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// I thought the solution could be there
}
}, 2000);
}
Do it using isReadyToPost flag:
if(isReadyToPost){
isReadyToPost=false;
}else{
// try after 2 secs for next like
}
and in Handler. postDelayed change isReadyToPost to true after 2 secs:
#Override
public void run() {
isReadyToPost=true;
}
isReadyToPost default value is true.
Try this approach:
boolean isReadyToPost= false;
boolean liked = false;//control like click (witch)
public void onLikePressed() {
if (liked && isReadyToPost) {
sendLikeToServer();//send to server after 2 secs
return;
}
this.isReadyToPost= false;
Toast.makeText(this, "waiting for any dislike... in 2 secs", Toast.LENGTH_SHORT).show();
if (liked){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
isReadyToPost=true;
onLikePressed();
}
}, 2000);
}//end if
} //end onlikepress
You can try to create a thread that sleeps for 2 sec and after that it checks if user still likes the post then update your database
Related
I implemented video call in Android using WebRTC.
Call will be made if two users come to same room as their will.
What I want to achieve now, is someone be able to enter a user ID and "Call" him and the other user's phone ring (So there is no problem with webRTC implementation, I just want to implement Ringing behavior).
What I have done so far using Firebase's Realtime database, is that I defined a branch called 'calls', consisting of childs named room name by two user id combination. (so if user1 calls user2, room name will be user1user2).
If user1 calls user2, it sets reqId to 1, and then as user2 listens to any change. he understands that user1 is calling him (and I show incoming call screen) and then it responses by setting reqId to 2, this conversation continues until user2 accepts or cancels the call.
I'm searching for a better solution to achieve this, cause it doesn't seem such a good method and has many problems.
i found the solution.
as if anyone have same question.
for every user, i created a branch called 'call' which is responsible for incoming calls.
and this two functions are what i implemented to perform, or listen for a call:
performCall function:
private DatabaseReference mDatabase;
private static int count = 0;
private void performCall(String s) {
if(count>0)return;
mDatabase = FirebaseDatabase.getInstance().getReference().child("users/"+"USERIDTOCALL"+"/call");
mDatabase.child("roomName").setValue(s);
mDatabase.child("answer").setValue("none");
mDatabase.child("answer").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
switch (Objects.requireNonNull(dataSnapshot.getValue()).toString()){
case "none":
break;
case "yes":
t.cancel();
t.purge();
count =0;
//The Call Should Begin...
break;
case "no":
t.cancel();
t.purge();
count =0;
//RejectedCall
break;
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
//Declare the timer
t = new Timer();
count =0;
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
mDatabase.child("signal").setValue(new Random().nextInt());
count++;
if(count >= 20){
t.cancel();
t.purge();
count =0;
}
}
}, 0, 2000);
}
and listenForCalls function:
private int count =-1;
private boolean isCalling = false;
Runnable runnable = null;
private boolean callingScreenShowed;
AlertDialog alertDialog;
private void listenForCalls() {
mDatabase = FirebaseDatabase.getInstance().getReference().child("users/"+GlobalVars.userName+"/call");
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String answer = dataSnapshot.child("answer").getValue().toString();
if(answer == "yes" || answer =="no") return;
count++;
if(count >= 1){
isCalling = true;
}
if(count == 1 ){
callingScreenShowed= false;
//every 5 seconds check if signaling is active
final int interval = 5000;
Handler handler = new Handler();
runnable = () -> {
if(isCalling){
if(!callingScreenShowed){
//Show A dialog for calling
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setMessage("user with id" + dataSnapshot.child("roomName").getValue() + " Is Calling");
dialog.setTitle("Incoming Call");
dialog.setPositiveButton("YES",
(dialog1, which) -> {
mDatabase.child("answer").setValue("yes");
callingScreenShowed =false;
isCalling = false;
count = -1;
handler.removeCallbacks(runnable);
//Start VideoCall
}
);
dialog.setNegativeButton("cancel", (dialog12, which) -> {
mDatabase.child("answer").setValue("no");
callingScreenShowed =false;
isCalling = false;
count = -1;
handler.removeCallbacks(runnable);
//Clling Rejected
});
alertDialog=dialog.create();
alertDialog.show();
callingScreenShowed = true;
}
}
else {
if(callingScreenShowed){
alertDialog.hide();
}
Log.e("Called","Call Request Ended");
count = -1;
handler.removeCallbacks(runnable);
return;
//Hide Calling Screen
}
isCalling = false;
handler.postDelayed(runnable, interval);
};
runnable.run();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
my_text.setText("Dave");
//Small pause...
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
my_text.setText("Bob");
I want to change my textView, pause 1 second, then change it again. When I run the program, it doesn't refresh after first change. It just shows the second change after returning. How can I force the refresh on the first change to the textview?
Try use Handler like below code
my_text.setText("Dave");
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
my_text.setText("Bob");
}
});
}
}, 1000);
Try below for the edited question
Keep your all 20 names in any collection array or list.
int position = 0;
String names [] = {"0","1","20"};
Handler handler = new Handler(getMainLooper());
Runnable runnable = new Runnable() {
public void run() {
my_text.setText(names[position++]);
if (position < names.length) {
handler.postDelayed(this, 1000);
}
}
};
handler.postDelayed(runnable, 1000);
first of all, I'm a beginner to android world so please apologize me if it is stupid question..
I'm trying to do following:
Enable Mobile Data
Wait for 10 seconds
a. check if Mobile got IP address (data connected sucessfully)
b. if Not connected,Disable Data
c. Go to step 1
And these steps 1 to 3 are getting executed in For loop for User Given number of retries.
Now my problem is: I'm stuck at step No. 2. I'm unable to make waitfor(int seconds) function. I tried using Runnable PostDelayed method but it is not giving me required output.
for(retry = UserChoice; retry > 0 && !isDataAvailable ; retry -- ){
enableInternet()
delay(10)
isDataAvailable = GetInternetAvailibility()
if(!isDataAvailable){
disableInternet()
}
}
I tried to put isDataAvailable = GetInternetAvailibility() statement in postDelayed of handler but it is causing enableInternet() disableInternet() to execute at the same time while isDataAvailable = GetInternetAvailibility() gets executed after delay.
I can see from logs, that enableInternet() executes for UserChoice number of times without any delay.
Thread.sleep(10000) just freezes the UI for 10 seconds... How do I achieve this?
EDIT : Let me clear :
public void onClick(View v) {
// Perform action on click
for(i=0; i<3; i++ ){
System.out.println("Before..");
delay(5);
System.out.println("after..");
}
}
public void delay(int seconds){
milliseconds = seconds * 1000;
runOnUiThread(new Runnable() {
#Override
public void run() {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
System.out.println("XXX"); //add your code here
}
}, milliseconds);
}
});
}
Now whenever I click button I can see in logs that System.out prints message as:
Before
afterBefore
afterBefore
after
XXXXXXXXX
But I want:
Before
XXX
After.Before
XXX
After.Before
XXX
After.
try this:
public void check() {
isDataAvailable = GetInternetAvailibility()
if (!isDataAvailable) {
disableInternet();
enableInternet();
if (retry > 0) {
retry--;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
check();
}
}, 10000);
}
}
}
This way may help you.
http://developer.android.com/reference/android/os/CountDownTimer.html
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
Try Below code.Hope that it will help
int i = 0;
int j = 3;
method() {
if (i < j) {
System.out.println("Before..");
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
System.out.println("XXXXXX");
i++;
System.out.println("after");
method();
}
}, 1000);
}
}
I tried to put isDataAvailable = GetInternetAvailibility() statement
in postDelayed of handler but it is causing enableInternet()
disableInternet() to execute at the same time while isDataAvailable =
GetInternetAvailibility() gets executed after delay.
Put the if statement and disableInternet() in the postDelayed. enableInternet will get called, 10 seconds later it will check to see if the internet is available, if not it will disableInternet.
In my application, I have a button that starts an AsyncTask that downloads data with coordinates for google maps, then draws a marker on the map at the following coordinates. I want to run this every 10 seconds until the user presses the button again.
Here's my code for the handler:
class handleMap{
Handler mHandler = new Handler();
Runnable mTask = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while(btnRefreshPressed == false){
try{
new getGoogleMap().execute();
mHandler.postDelayed(mTask, INTERVAL);
Thread.sleep(INTERVAL);
} catch(Exception e){
System.out.println(e.toString());
}
}
}
};
public void starReapetingClass (){
hMap.starReapetingClass();
}
public void stopDoing(){
mHandler.stopDoing();
}
}
And in the menubutton where it is called:
case R.id.id_Refresh:
handleMap hMap = new handleMap();
if(btnRefreshPressed == true){
menuItem = item;
menuItem.setActionView(R.layout.progressbar);
menuItem.expandActionView();
fRun += 1;
btnRefreshPressed = false;
hMap.run();
}else if(btnRefreshPressed == false){
if(fRun > 0){
menuItem.collapseActionView();
menuItem.setActionView(null);
}
btnRefreshPressed = true;
hMap.stopHandler();
}
This currently causes the application to freeze, and the system outputs a dialog saying that the app isn't responding, and asking if I want to close or wait.
I suspect it has to with the while statement, but I don't get any errors in logcat.
Thanks in advance.
Just use:
private int mSampleDurationTime = 10000;
private boolean continueToRun = true;
mHandler.postDelayed(mRunnable, mSampleDurationTime);
where mRunnable is your task:
private final Runnable mRunnable = new Runnable() {
//...
public void run() {
...
if(continueToRun == true){
mHandler.postDelayed(mRunnable, mSampleDurationTime);
}
}
...
};
First time you call postDelayed and invoke new Runnable(). After, if you want to continue,
call the same method into run()
I am scheduling a simple task that should update a text field in 4 seconds.
However everytime this is called the activity pauses and does not show the value in the text field until I restart the activity.
private void showDelayedValue() {
Runnable longRunningTask = new Runnable() {
public void run() {
int randomVal = randomNumberGenerator.nextInt(30 - -10) - 10; //random number between -10 and 30
String randomValStr = Integer.toString(randomVal);
Log.i(this.getClass().getSimpleName(),
"FIRED startScheduler: " + randomValStr);
theFieldOnScreenTV.setText(randomTempStr);
}
};
//show the value in 2 seconds
scheduledTaskExecutor.schedule(longRunningTask, 4, TimeUnit.SECONDS);
}
The log shows:
FIRED startScheduler: 4
but does not update the TextView theFieldOnScreenTV
Instead onPause is called right after Fired startScheduler: is displayed in LogCat.
Many thanks!
EDIT:
This worked for me following Alex' approach:
private void showDelayedValue() {
int randomX = randomNumberGenerator.nextInt(30 - -10) - 10;
final String randomXStr = Integer.toString(randomX);
final Runnable updateFieldR = new Runnable() {
public void run() {
theFieldOnScreenTV.setText(randomXStr);
}
};
Runnable longRunningTask = new Runnable() {
public void run() {
theFieldOnScreenTV.post(updateFieldR);
}
};
scheduledTaskExecutor.schedule(longRunningTask, 4, TimeUnit.SECONDS);
}
instead of
theFieldOnScreenTV.setText(randomTempStr);
try
theFieldOnScreenTV.post(new Runnable() { theFieldOnScreenTV.setText(randomTempStr); } );
Have a try using Handlers.
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
theFieldOnScreenTV.setText(randomTempStr);
}
});