Running application while idle for Android - java

I was wondering if there is a way to keep running my application (which basically just refreshes a URL every X seconds) even when the phone idles/locks? (when the screen turns off). I'm currently using a WebView to load the URL, and a Runnable to reload it.
When I tried using a service, it keeps giving me a problem - webview cannot be resolved. I looked it up, and I couldn't get it fixed.
I would also like to know if there is a way to browse a URL in the background. Basically, browsing a URL without showing the browser :D
Any help would be much appreciated!!!
Sorry if these questions are dumb, I've only started Android programming for a few days.

You do not need a webview to poke web server, unless you like to display results imeediately.
You can use built in http client for this purpose ( works from service and does not vae user interfce)

I think Timer task will solve your problem.
Timer timer=new Timer();
timer.schedule(new DelayedTask(),1, 1000);// it will repeat within 1000ms
private class DelayedTask extends TimerTask
{
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
webview.loadUrl(url);
}
});
}
}
#Override
public void onDestroy()
{
super.onDestroy();
timer.cancel();
}

Related

A method besides onPause?

I have an app that has three activities, the user will be constantly tabbing between these three activities. Right before the user closes the app, my code downloads the current time from the internet and stores it. The problem is that i have my code for downloading the time in the onPause() method. This causes the data to be downloaded over and over each time the user switches activities. I tried using onDestroy() but the download would never start. is there a method that is called when the user minimizes or closes the app altogether instead of one that is called on an activity switch?
Thank you very much, any help is appreciated!
We can achieve this using the Application class. There we can implement the ActivityLifecycleCallbacks to identify when our app goes to the background and based on that result we can perform our required task. Here, a sample code:
public class MyApplication extends Application implements ActivityLifecycleCallbacks {
private Handler mHandler;
#Override
public void onCreate() {
super.onCreate();
mHandler = new Handler();
}
...
#Override
public void onActivityResumed(Activity activity) {
Log.i("Activity Resumed", activity.getLocalClassName());
// cancel scheduled download operation (if any)
mHandler.cancelCallbacksAndMessages(null);
}
#Override
public void onActivityPaused(Activity activity) {
Log.i("Activity Paused", activity.getLocalClassName());
// schedule a download operation after 5 seconds
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
performDownloadOperation()
}
}, 5000);
}
... // other lifecycle callbacks
private void performDownloadOperation() {
// perform download operation here
}
}
In the above code, we are basically giving the user [and the system] a grace time of 5 seconds to switch from one activity to another. Otherwise, we note that the app went to background and do our stuff there. So, even if the user switches to a different app for 4 seconds and then come back, we'd still not download the data, which should be fine in most cases.
Note that to use the above class, you need to provide the class reference to the android:name property as android:name=".MyApplication" under the <application> tag in the manifest file.
You can make use of Activity::isFinishing(). This will return false when you (1) launch another activity or when (2) the app is put on background, but it will return true when (3) the back button is pressed or if (4) somebody calls finish on the activity.
If it is important to distinguish between (1) and (2), then you can always keep a flag that you can switch every time you launch an activity and reset it in onPause.

Android: run animation while loading stuff

I'm reading a lot of files from the network. This takes quite a long time. Because of this i want to run a little animation (like a progress animation). But the animation only starts when the other stuff is finished. How can i run the animation on the UI Thread (in a Dialog!)?
AnimationDrawable animation = (AnimationDrawable) ivAnimation.getBackground();
animation.start();
Your main thread cannot be simultaneously downloading data and running an animation, also you cannot modify the UI from a background thread. As a result, you cannot "run an animation in the background", your animations and all UI tasks must be executed on the main thread while your data is downloading on a background thread.
Android, fortunately, has AsyncTask just for this purpose...
new AsyncTask<String, Integer, List<MyData>>() {
#Override public void onPreExecute() {
startMyAnimation();
}
#Override public List<MyData> doInBackground(String... urls) {
List<MyData> data = new ArrayList<>();
int counter = 0;
publishProgress(counter);
for(String url : urls) {
data.add(getMyDataFromNetwork(url));
publishProgress(++counter);
}
return data;
}
#Override public void onPostExecute(List<MyData> result) {
stopMyAnimation();
updateMyUiWithData(result);
}
#Override public void onProgressUpdate(Integer filesDownloaded) {
updateUiWithFileCount(filesDownloaded);
}
}.execute(url1, url2, url3, etc);
Check out Volley framework for performing long running network related operation. It's easy to use and very good, built exactly for networking in the background.
A general rule in Android (or any other GUI applications) is to never run long running operation on the UI thread. In android this will get you ANR's and will kill your app.
In general here's what U should do:
Start the download using Volley or an AsyncTask or something else (Will run in background).
Create and show a progress dialog to display to user (On UI thread).
Once an answer/response is received, call dialog.dismiss() on the progress dialog.
Hope this helps
Use Asynchronous task for this. Asynchronous task in android
In onPreExecute() method of Asynchronous task show animation, progress bar or anything whatever you want to show. Used doInBackground for downloading the stuffs.

How to keep service running in background when app is closed but stop/disable it when the app is in foreground?

I am having difficulties trying to handle service behaviour in such case.
Basically I have a service running on a separate process that needs to issue httprequests every certain time whenever the app is closed, then write something into preferences or throw a notification.
The logic works fine. The problem I'm having is that I cannot find a way to properly stop/disable that service whenever the app is running, aswell as start it again when the app is being finished or put into background.
I've tried stopping it at #onResume()/#onStart() callbacks of my activities aswell as starting it at #onStop()/#onDestroy() but behaviour doesnt run as expected in any case...
I'll paste here some code snippets of what i've tried so far:
I start/stop services using:
stopService(new Intent(this,NotificationService.class));
startService(new Intent(this, NotificationService.class));
Random activity from my app (all implement this in their callbacks):
#Override
protected void onResume() {
if (Utility.isMyServiceRunning(this)){
Utility.serviceClose(this);
}
super.onResume();
}
#Override
protected void onStop() {
if (!Utility.isMyServiceRunning(this)){
startService(new Intent(this, NotificationService.class));
}
super.onStop();
}
This somehow doesnt work or brings unexpected behaviour since the app moves from many activities, and service ends up being alive when the app is running or stopped when the app is in background/finished.
I've also tried to toggle on/off service logic on service timertask every cicle by asking:
#Override
public void run() {
ActivityManager activityManager = (ActivityManager) getBaseContext().getSystemService( ACTIVITY_SERVICE );
List<RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
for(int i = 0; i < procInfos.size(); i++){
if(procInfos.get(i).processName.equals("com.example.myapp")) {
return;
}
}
//service http request logic here
}
But that doesnt work either because process "com.example.myapp" never gets killed (and of course I cannot/want to force finish that), so it never issues any httprequest.
Any Ideas on how to implement this? Any help would be very welcome.
Thanks in advance.
How about binding to your service and then communicating directly with it? Implement a simple on/off boolean, expose a getter/setter on the binding, and then make sure the service checks the boolean before it does any work. That way you can disable it while the app is running without having to actually start/stop the service repeatedly.
http://developer.android.com/guide/components/bound-services.html
Solved with better handling of onStop() onResume() callbacks.

JavaFx WebView not updating XmlHttpRrequest background data

I'm trying to display website with dynamic XHR (push) data in JavaFx WebView for example:
http://finance.yahoo.com/q?s=^gdaxi
http://www.boerse-frankfurt.de/en/start (data in header)
and many others. Probably not only stock exchange websites.
Each of these websites after first rendering is not updating. I checked in Wireshark and some new data are sending from the server for all the time, but without any changes in view.
I was trying to compile and run in new Java 8 but sill the same.
Any ideas?
Maybe u know some other good Web Browsers written in Java?
You haven't posted your code, but are you doing the your
webView.getEngine().load( ... );
inside Platform.runLater, e.g.?:
Platform.runLater(new Runnable() {
#Override
public void run() {
//Update here
webView.getEngine().load( ... );
}
});

android thread does not run in standby

In my program, I'd like to check for a new version (getting data from HTTP).
The function works perfectly, but I want to have it running in background every X (configurable, one hour, one day, and so on).
So I wrote this code:
Timer mTimer1 = new Timer();
PowerManager pm = (PowerManager) this.main.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = this.pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, MainActivity.PROGRAM);
PowerManager.WakeLock wl.acquire();
TimerTask mTt1 = new TimerTask()
{
public void run()
{
mTimerHandler.post(new Runnable()
{
public void run()
{
// Do the check...
}
});
}
};
(since this function is in a separate class NOT deriving from Activity, I passed to the constructor the parent class this.main, so that I can call getSystemService. This Variable is declared as private MainActivity main).
Well, when I start the Timer it checks for new version, then, after an hour (so my settings), I check in the Logs and I see that the thread did not run...
I searched in Internet and I found, that I have to use the PARTIAL_WAKE_LOCK, and I do that...
Any idea, why I have this problem?
Thanks a lot!
Luca Bertoncello
Here is a SO answer that can help you with this using a handler and postDelayed().
However, if you want to run this even when the app isn't open then you will want to use an AlarmManger.You create a PendingIntent and create a Calendar instance to set the time you want it to check then use setRepeating() on the AlarmManger. This will have it check even when not in the app. You can also register it in the manifest as Boot_Completed so it will start running again after reboot when the device is turned off
Here is a good example to get you started with AlarmManager
If you are using a Timer, did you remember to schedule your TimerTask?
Try
mTimer1.schedule(mTt1, delay, interval);
And if you want to stop that, do mTimer1.cancel();
and mTimer1.purge(); to clear the schedule queue.
When the phone goes to sleep, execution will be paused for your activity and thus your timer will never fire. Using PARTIAL_WAKE_LOCK is probably not a good idea as it will consume battery the entire time your phone sleeps.
I would suggest taking a look at AlarmManager and specifically setInexactRepeating
Use this code
Timer timer = new Timer();
timer.scheduleAtFixedRate(
new java.util.TimerTask() {
#Override
public void run() {
// Your code
}},
1000, 5000
);
Where 1000 is a post delay , if you want delay for first time , if you don't want than put it 0
5000 is a iteration time

Categories

Resources