Location update in background in android - android

i build app which give Location update to server in background using service and broadcastreceiver.i put timer(Run every X Minute) which run method of location.it include fatch lattitude,longitude and update to server with API Call.
I have a problem and quastions . there is a list of this.
1.my timer goes sleep when device is in standby mode or sleep mode
2.i have to update location if user last location and current location distance 500m or greater.
3.I want to know how much minute or second tack device for going sleep mode?
4.my timer run perfactly in running devoce mode than why stop or sleep in device sleep mode?
my timertask
class TimeDisplayTimerTask extends TimerTask {
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
location();
notifyUser2();
Log.d("timeeeeeeee22222222", "time22222222");
// display toast
}
});
}
//in oncreate
if (mTimer != null) {
mTimer.cancel();
} else {
// recreate new
mTimer = new Timer();
}
// schedule task
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
Is the currect Way to timer run? if yes than Why it Sleep while device in standby mode or sleep mode?
Help me i searched lots of sites but can't get it.
Thanks in advance

Related

Doze not restricting service

I have a Service that shows a toast every 10s, but I'd expect Doze to slow it to every 15 minutes when it's in the background as the app is not whitelisted. Here's my service:
#Override
public void onCreate() {
super.onCreate();
if (mTimer != null)
mTimer = null;
// Create new Timer
mTimer = new Timer();
// Required to Schedule DisplayToastTimerTask for repeated execution with an interval of `2 min`
mTimer.scheduleAtFixedRate(new DisplayToastTimerTask(), TIMER_DELAY, TIMER_INTERVAL);
}
...
private class DisplayToastTimerTask extends TimerTask {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Hello world", Toast.LENGTH_SHORT).show();
}
});
}
}
What I'm getting in the emulator is that the toast is shown every 10s even when I'm at the home screen. Doesn't Doze restrict all non-whitelisted background services/apps to 15 min waking time?
Doze occurs only when the screen is off, and has been for some minimum amount of time. It has nothing to do with just backgrounding.
In addition, Timers or Threads set by the service wouldn't automatically be canceled, as 1)the OS doesn't know about them and 2)There's no way to know if its safe to do so, or if doing so would cause deadlock or other errors. They may be delayed to the Doze allowed rate of execution, but would not be stopped.

[Wifi Direct Demo]Running the same code multiple times at interval[Android]

I am following https://android.googlesource.com/platform/development/+/master/samples/WiFiDirectDemo.
Due to my own requirements ,I just want to run this following code multiple times.
When we click on the search button (cicled in red),The app starts searching for the available wifi peers as shown in the below image
I just want to automate this process every 2 seconds whether it has found some peer or not.
In the code of this Activity:
case R.id.atn_direct_discover:
if (!isWifiP2pEnabled) {
Toast.makeText(WiFiDirectActivity.this, R.string.p2p_off_warning,
Toast.LENGTH_SHORT).show();
return true;
}
final DeviceListFragment fragment = (DeviceListFragment) getFragmentManager()
.findFragmentById(R.id.frag_list);
fragment.onInitiateDiscovery();
manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(WiFiDirectActivity.this, "Discovery Initiated",
Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int reasonCode) {
Toast.makeText(WiFiDirectActivity.this, "Discovery Failed : " + reasonCode,
Toast.LENGTH_SHORT).show();
}
});
return true;
This is the code.
One thing I tried is put everthing in a while(true) loop but i always crash the app.
Then I used a stop button and a flag.This button sets flag to false but it still is not working.
I tried the solution of this :How to automatically Click a Button in Android after a 5 second delay
It does not crash the app but the button only works when i manually click it.
Any suggestions Please ??
What I understood from your problem is you want the task to run without any user intervention to detect new peers and update your UI accordingly.
Run a Handler every 5 seconds when your app is in foreground to start a bound service for searching any new peer, the service will communicate the information back to the activity if it has found anything new or not. When you get the message on your Activity, stop the service and unbind it.
Please see the details about bound service here - https://developer.android.com/guide/components/bound-services.html
You can use Timer class & schedule it to run every 5 seconds. The idea is the timer task doesn't simulate button pressed, but it should does exactly same thing as when the button is pressed.
Assume your Activity class is named MyActivity. Place this in onCreate() of MyActivity class.
Timer myTimer = new Timer();
// schedule to run every 5000 milli seconds
myTimer.schedule(new TimerTask() {
#Override
public void run() {
MyActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// any code that update UI goes here
// Eg: displaying progress indicator, show "finding Peers" text
....
}
});
// the rest of "discover" logic goes here
}
}, 0, 5000);

Create alarm automatically everytime Database gets new data

I need to create an alarm every time new data is inserted on the Database(the database has the values of date and time of every alarm that is going to be created), without any interaction with the user, the app has to do it automatically.
How do I know when new data is inserted? checking every x minutes using a timer?
How to create an alarm automatically when that happens?
Typically for something like this, you would want to use something more like Firebase that will live update your data.
But to do a timer, first extend TimerTask:
public class Progress extends TimerTask {
#Override
public void run(){
//this item runs on a separate thread
runOnUiThread(new Runnable() {
#Override
public void run() {
seconds += 0.1;
//this item runs on the main thread
}
});
}
}
And then to run this task:
Timer timer;
Progress progress;
timer.schedule(progress, 100, 100);
This will run the timer every .1 seconds.

Timer should run One time but with different Intervals

I have a button on which I want to set the timer for 5 seconds for the first time and it should perform some task after completing 5 seconds. Also if user click button 2 times it should start timer for 10 seconds and after 10 seconds it should perform specific task. and if user click 3rd time it should stop all running timers. so I have do not know How to implement timer for one time
what I have search is this. But in this link it is continuously repeating after specific period of time, whereas I want to run once.
Now what I want
To start timer with first click (of 5 seconds)and if meanwhile user click 2nd time it should set timer with with new time period and if user click third time it cancels out all timers.
I do not want to use Thread timer using sleep method.
I want same behavior as there is in camera app in android 5.0 v.
So please tell me how to do this any code and source code would be appreciated.
In the link you provided you will find the answer if you try little harder.
For a repeating task:
new Timer().scheduleAtFixedRate(task, after, interval);
For a single run of a task:
new Timer().schedule(task, after);
So what you need to do is to maintain temporary variable to keep track of number of clicks and you can use second method like
For a repeating task:
new Timer().scheduleAtFixedRate(task, after, interval);
For a single run of a task:
new Timer().schedule(task, after * numberOfTimeBtnClked);
You have to pass the TimerTask method instead of task in that method.
**For updating your textview use below code and forget about whatever I have written above **
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//run in an interval of 1000ms
timer.schedule(timerTask, 0, 1000); //
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
timerSince++; //global integer variable with default value 0
if(timerSince == 5 * numberOfBtnClick){
//call your method
timer.cancel;
timerSince = 0;
}else{
//textView.setText(((5 * numberOfBtnClick)-timerSince)+" second left");
}
});
}
};
}
}
On event start button click call:
startTimer();

Android - Controlling a task with Timer and TimerTask?

I am currently trying to set up a WiFi Scan in my Android application that scans for WiFi access points every 30 seconds.
I have used Timer and TimerTask to get the scan running correctly at the intervals which I require.
However I want to be able to stop and start the scanning when the user presses a button and I am currently having trouble stopping and then restarting the Timer and TimerTask.
Here is my code
TimerTask scanTask;
final Handler handler = new Handler();
Timer t = new Timer();
public void doWifiScan(){
scanTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
wifiManager.scan(context);
Log.d("TIMER", "Timer set off");
}
});
}};
t.schedule(scanTask, 300, 30000);
}
public void stopScan(){
if(scanTask!=null){
Log.d("TIMER", "timer canceled");
scanTask.cancel();
}
}
So the Timer and Task start fine and the scan happens every 30 seconds however I cant get it to stop, I can stop the Timer but the task still occurs and scanTask.cancel() doesn't seem to work either.
Is there a better way to do this? Or am I missing something in the Timer/TimerTask classes?
You might consider:
Examining the boolean result from calling cancel() on your task, as it should indicate if your request succeeds or fails
Try purge() or cancel() on the Timer instead of the TimerTask
If you do not necessarily need Timer and TimerTask, you can always use postDelayed() (available on Handler and on any View). This will schedule a Runnable to be executed on the UI thread after a delay. To have it recur, simply have it schedule itself again after doing your periodic bit of work. You can then monitor a boolean flag to indicate when this process should end. For example:
private Runnable onEverySecond=new Runnable() {
public void run() {
// do real work here
if (!isPaused) {
someLikelyWidget.postDelayed(onEverySecond, 1000);
}
}
};
using your code, instead of
scanTask.cancel();
the correct way is to cancel your timer (not timerTask):
t.cancel();
The Android documentation says that cancel() Cancels the Timer and all scheduled tasks. If there is a currently running task it is not affected. No more tasks may be scheduled on this Timer. Subsequent calls do nothing. Which explains the issue.

Categories

Resources