How to put delay for out going calls - java

Is there any option to put a delay to make a call in Android?
Once the user clicks the call button below method is called.
public class DialBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.v("DileBroadCastReceiver","In onReceive()");
if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Log.v("DialBroadcast Receiver","Number is: "+number);
}
}
}
Then opponent user receiving call.
What I need is when user clicks the call button I should put delay for a second or two second, Is there any option to do like that.
I am a new developer. Can you please help me?

try {
//set time in mili
Thread.sleep(3000);
}catch (Exception e){
e.printStackTrace();
}
or
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//do something
}
}, 3000//time in milisecond
);

Inside your onReceive function
Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable(){
#Override
public void run() {
if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Log.v("DialBroadcast Receiver","Number is: "+number);
}
}
}, 2000); // 2000 for two seconds in milis

Related

How can i run a button automatically every second until de if condition be true?

I need that a button can run automatically every 1-2 seconds, and, when the if condition (that i have in the method which is used by the button) is fulfilled, this function must be stopped.
I've tried this but it wasn't what i wanted because with this code the button only runs one time:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Consulta.performClick();
}
}, 1000);
onClick of my button:
public void consultaBD(View view)
{
DB db = new DB(getApplicationContext(),null,null,1);
String buscar = text_view.getText().toString();
String[] datos;
datos=db.buscar_reg(buscar.trim());
db.infraccion(buscar.trim());
if(datos[2] =="Encontrado")
{
App.matricula=buscar;
startActivity(new Intent(getApplicationContext(), MatriculasActivity.class));
Toast.makeText(getApplicationContext(),datos[2],Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),datos[2],Toast.LENGTH_SHORT).show();
}
}
Another method would be to use Timers to initiate the button click every x seconds. However, in this answer I'll stick with the method you're using. Your handler appears to be incorrect, try something like this instead:
Replace your handler with:
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
#Override
public void run() {
Consulta.performClick();
handler.postDelayed(this, 1000);
}
};
And initiate it with: (where 1000 is the time (in milliseconds) between each execution)
handler.postDelayed(runnable, 1000);
UPDATE:
You have also requested that the event is fired when the text inside of a textbox is changed. To do this, you need to create a new event listener (make sure you replace field1 with the actual reference to your textbox):
field1.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
/* Add the Handler Call here */
handler.postDelayed(runnable, 1000);
}
});
whatever context I understood, here is the raw code which may help you.
Handler handler = new Handler();
//initialize this method once by either clicking on button or as the activity starts
void checkAndPerformClick(boolean conditionFulfilled) {
if (conditionFulfilled) {
handler.removeCallbacksAndMessages(null);
return;
}
handler.postDelayed(new Runnable() {
#Override
public void run() {
Consulta.performClick();
checkAndPerformClick(datosEqualsEncontrado());
}
}, 1000);
}
boolean datosEqualsEncontrado() {
// apply your logic here as the name suggests
return false;
}

Start And Stop Method Automatically

So I am trying to start my sensor reading method after 10 seconds and stop it after say 5 minutes. This is the code for the same.
case R.id.btn_pos_poll_side: {
final Handler handler = new Handler();
//Delay Runner Here
handler.postDelayed(new Runnable() {
#Override
public void run() {
side_output.setText("Delayed Data Collection");
//Start reading LIGHT SENSOR Data, Handle Null Light Sensor Data
if (LightSensor != null || mProximity != null || mAccelerometer != null || mGyroscope != null) {
//listen to light sensor.
mySensorManager.registerListener(
MultiSensorListener,
LightSensor,
SensorManager.SENSOR_DELAY_NORMAL);
//listen to proximity sensor.
mySensorManager.registerListener(
MultiSensorListener,
mProximity,
SensorManager.SENSOR_DELAY_NORMAL);
//listen accelerometer, note this has 3-axes.
mySensorManager.registerListener(
MultiSensorListener,
mAccelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
//listen gyroscope, note this has 3-axes.
mySensorManager.registerListener(
MultiSensorListener,
mGyroscope,
SensorManager.SENSOR_DELAY_NORMAL);
//print output text
side_output.setText(Html.fromHtml("<h3> ----- Data Collection Session Starts Here -----</h3>"));
} else {
side_output.setText("No Sensor Found!");
}
}
}, 10000);
final Handler closeHandler = new Handler();
//Data Sender Runner Here
closeHandler.postDelayed(new Runnable() {
#Override
public void run() {
Button stopCollection = (Button) findViewById(R.id.btn_stop_poll_side);
stopCollection.performClick();
}
}, 120000);
break;
}
However this never works and even the data collected is somewhat corrupt (new data is concatenated to previous data).
What am I doing wrong?
Thanks.
Edit: Some more details. I want to start it after 10 seconds from when I have pressed the button and stop it after say 2 minutes. This happens only once unless I press the button again.
Added: Stop Button Logic
case R.id.btn_stop_poll_side: {
// remove sensor listener
mySensorManager.unregisterListener(MultiSensorListener,
LightSensor);
mySensorManager.unregisterListener(MultiSensorListener,
mProximity);
mySensorManager.unregisterListener(MultiSensorListener,
mAccelerometer);
mySensorManager.unregisterListener(MultiSensorListener,
mGyroscope);
side_output.append("\n" + sensorReading);
/*
Reading data and writing to Dropbox!
*/
new DropboxTask(side_output, "Back Pocket Data Reading", sensorReading).execute();
break;
}
When user presses the button the first time:
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
// Do what you need to do
}
}
handler.postDelayed(runnable, 10_000 /* Wait 10 seconds */);
When the user presses the button the second time:
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
// Stop what you want to stop
}
}
handler.postDelayed(runnable, 2*60*1000 /* Wait 2 minutes */);
This has to be done in the onClick of your button:
First define a private boolean like called isButtonAlreadyClicked = false.
Now:
yourButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if(!isButtonAlreadyClicked) {
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
// Do what you need to do
}
}
handler.postDelayed(runnable, 10_000 /* Wait 10 seconds */);
isButtonAlreadyClicked = true;
} else {
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
// Stop what you want to stop
}
}
handler.postDelayed(runnable, 2*60*1000 /* Wait 2 minutes */);
isButtonAlreadyClicked = false;
}
});
EDIT:
If you want to prevent the runnable to be run while it is waiting, just make sure to declare the handler and your runnables outside of your method (inside your class), so that you can do (for example):
mHandler.removeCallbacks(firstRunnable);
mHandler.removeCallbacks(secondRunnable);
In that way it won't run the Runnables anymore.

How Can I Stop Runnable Into 2 different Acivity with in Android?

I need to delete a value from SharedPreferences after 5 minutes or when the user finished to do something . So when I add that value I start this:
Activity A
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mySharedPreferences.removeValue(mContext, Utils.MY_VALUE);
}
}, Utils.TIME_BEFORE_DELETE);
and in the case users finished all I do this:
Activity B
mySharedPrefernces.removeValue(mContext, Utils.MY_VALUE);
But how can I stop the Handle into second activity?? Or is there another way to do it??
you can you boolean variable if you want to cancel this.
create public static boolean to check if the task is cancelled or not.
public static boolean isCanceled = false;
Use this in run() method
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (!isCanceled)
mySharedPreferences.removeValue(mContext, Utils.MY_VALUE);
}
}, Utils.TIME_BEFORE_DELETE);
if you want to cancel then set:
isCanceled = true;
Runnable run = new Runnable() {
#Override
public void run() {
mySharedPreferences.removeValue(mContext, Utils.MY_VALUE);
}
};
Handler handler = new Handler();
handler.postDelayed(run, Utils.TIME_BEFORE_DELETE);
//to dismiss pending runnable
handler.removeCallbacks(run);
A better way to do: Example code
publc static final Handler handler = new Handler();
public static final Runnable runnable = new Runnable() {
public void run() {
try {
Log.d("Runnable","Handler is working");
if(i == 5){ // just remove call backs
handler.removeCallbacks(this);
Log.d("Runnable","ok");
} else { // post again
i++;
handler.postDelayed(this, 5000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
//now somewhere in a method
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
handler.removeCallbacks(runnable);
handler.postDelayed(runnable, 5000);
}
});
You can use handler.removeCallbacksAndMessages(null);. More information link
In this case you can use service with sticky flags. So you start service with intent "start_handler" and start handler also. When you need cancel handler you send the intent to stop handler and service. Or when time is passed and handler calls your code you should also stop service.
Using service with sticky flag provides possibility restoring handler. Also you need add some logic saving time when handler was run for correct restoring handler.
For that you can't use direct Runnable inside handler, you need to take one instance of it then you can do this like below,
Runnable myRunnable = new Runnable(){};
Then assign this in handler
handler.postDelayed(myRunnable);
And on no need use below line
handler.removeCallbacks(myRunnable);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
//add your code hare
finish();
}
}, 10000);
by using this way you can stop your runnable in a fix time

In run(), how can I call a method without my app crashing (Java/Android)?

I'm trying to make a simple little program that will increment a number once a second. In this case, I'm implementing a thread that should loop once per second and add 1 to "potato" each time it loops. This works fine until it gets back to the display method potatoDisp(). For some reason this causes my app to crash. Removing potatoDisp() from run() fixes the problem, but the display is not updated as "potato" increases.
public int potato = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
potatoDisp();
start();
}
public void potatoDisp() {
TextView text = (TextView) findViewById(R.id.textView1);
text.setText("You currently have " + potato + " potatoes");
}
public void start() {
Thread thread = new Thread(this);
thread.start();
}
#Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return;
}
potato++;
potatoDisp();
}
}
I'm doing this for an Android app, if that helps. I've tried searching for an answer but I'm pretty lost when it comes to the proper way to work threads.
You need a runnable / handler like this:
private Runnable potatoRun = new Runnable() {
#Override
public void run () {
potatoDisp();
}
};
then change
potatoDisp();
to:
runOnUiThread(potatoRun);
You can't update the views when you're not on the UI thread.
You are probably getting an exception for updating the UI in the background. Since, potatoDisp(); is called from a background Thread but that function updates the UI it will give you problems. You need to call it with runOnUiThread().
#Override
public void run() {
while (true) {
try
{
Thread.sleep(1000);
} catch (InterruptedException e) {
return;
}
potato++;
runOnUiThread(new Runnable()
{
#Override
public void run()
{
potatoDisp();
}
});
}
}
Something like this should work.
The issue is that you are trying to update the UI (calling text.setText(...)) on a thread other than the main UI thread.
While I would suggest using a TimerTask instead of calling Thread.sleep(...), there are two main ways to edit your current code to work as expected.
-- Use a Handler
Define a Handler class that will accept messages and update your UI as needed. For example:
private final String POTATO_COUNT = "num_potatoes";
Handler handler = new Handler() {
public void handleMessage(Message msg) {
int numPotatoes = msg.getData.getInt(POTATO_COUNT);
mText.setText("You currently have " + numPotatoes + " potatoes");
}
}
Then in your code where you want to call your handler to update your text view, whether or not you are on the main UI thread, do the following:
Bundle bundle = new Bundle();
bundle.putInt(POTATO_COUNT, potato);
Message msg = new Message();
msg.setData(bundle);
handler.sendMessage(msg);
-- Call runOnUiThread(...)
#Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return;
}
potato++;
runOnUiThread(new Runnable()
{
public void run()
{
potatoDisp();
}
}
}
}
I think you should be using Async Task to update the UI from a thread: http://developer.android.com/reference/android/os/AsyncTask.html

Splashscreen is only showed sometimes

I defined a splashscreen the following way:
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ExceptionHandler.register(this);
setFullscreen();
splashScreen();
}
private void splashScreen() {
runOnUiThread(new Runnable() {
#Override
public void run() {
setContentView(R.layout.splashscreen);
splash = (ImageView) findViewById(R.id.splashscreenLayer);
startSplashTime = new Date();
}
});
new LoadingThread().start();
}
private class LoadingThread extends Thread {
#Override
public void run() {
checkNetwork();
}
}
Somewhere at specific conditions in the checkNetwork() method, the stopSplash method is called:
public void stopSplash() {
Message msg = new Message();
msg.what = STOPSPLASH;
Date endSplashTime = new Date();
long time = endSplashTime.getTime() - startSplashTime.getTime();
System.out.println("Time Splashscreen was displayed: " + time);
if (time < SPLASH_MIN_TIME) {
long delay = SPLASH_MIN_TIME - time;
System.out.println("Delay Splashscreen for: " + delay);
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
splashHandler.sendMessage(msg);
} else {
System.out.print("Show Splashscreen now");
splashHandler.sendMessage(msg);
}
}
private Handler splashHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case STOPSPLASH:
splash.setVisibility(View.GONE);
break;
}
super.handleMessage(msg);
}
};
The problem is, sometimes (maybe 1 of 10) if I started the app directly from Eclipse, the Splashscreen isn't showed, but instead just a black screen.
Other problem: if i restart the app, e.g. after onDestroy() was called after clicking the back button on the device, the Splashscreen is almost never shown.
Any hints why?
My assumption: could it be, that the LoadingThread starts "faster" than the Runnable, and so the network staff is done before the Splashscreen is set?
You might try using a CountdownTimer in your implementation. On your first activity, start a CountdownTimer that checks in onTick() every so often for a synchronized boolean finishedLoading with some kind of timeout in onFinish() (15 seconds or something), while your loading is done in another thread that sets finishedLoading to true when it is finished.
Maybe the splash screen isnt being terminated before the v=next activity starts.. just a thought..

Categories

Resources