android service performing a task continuously at specif intervals - java

After a long search I'm still confused about it although I found some related posts but they were not answering what I was looking for. in my scenario I want to send user's lat long at fixed intervals like every 5 minutes to a server. to do this I used a service with its own process so that it doesn't get killed when Activity destroyed and in service method onStartCommand I used a while loop having condition of always true and in that loop I update location to server and give delay by thread.sleep like shown below
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
While(true)
{
Location currentLocation = getLocation();
updateLocationToServer(currentLocation);
try
{
Thread.sleep(300000)
}
catch(Exception e)
{
e.printStackTrace()
}
}
return Service.START_STICKY;
here I cannot understand the return statement is unreachable then how can the service will be restarted automatically when it is destroyed and secondly using thread.sleep causing ANR (Application Not Responding) while service is a background process and I found that its directly running in UI thread these information are confusing me and in this case what is the best way to get desired functionality.

You should use and AlertManager instead!
AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context, OnAlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), PERIOD, pi);
http://justcallmebrian.com/?p=129

secondly using thread.sleep causing ANR (Application Not Responding) while service is a background process
from
http://developer.android.com/reference/android/app/Service.html
Note that services, like other application objects, run in the main thread of their hosting process.

Try using Alarm Manager instead, see this example of how to set it to repeat every 5 minutes

Related

Android: Run an app when it's definitively closed

I noted that when I close my app definitively, the method runInBackGround of the class MultiplyTask stops working. It works when the activity is in the phase STOP or PAUSE, but when I close my app, the method finishes ( it's a loop created with a cycle while(true) {...} ).
How can for example Whatsapp send notifications though it's closed? I want to create a similar thing. Thanks!
When the app is closed, all code will stop running. If you are looking to execute while the app is open and continue executing code while the app is closed, you will want to look into using a Service.
Take a thorough look at the Service documentation and it will hopefully be what you are looking for.
Services are also killed when your app is closed, but using the START_STICKY return value you can make sure your service is restarted upon termination.
EDIT WITH MORE INFORMATION:
<service
android:name="MyService" />
Add the above to your AndroidManifest.xml
public class MyService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// This is where you would place your code that you want in the background
// Putting your while loop here will make sure it runs when the app is closed
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
}
Create a new class with the above code.
Intent i= new Intent(context, MyService.class);
startService(i);
Call this code from your launcher Activity to start the service when the app is launched.
Hope this helps!
Asynctask is ideal for short operation which are needed to be performed in the background. Usually Asyntask is implemented as sub class of activity which is destroyed when app is close. Also It communicates with the UI thread at some points ... so It needs the activity to be in memory... For long running operation, Service is better. Some Apps notify user even when they are not running. In fact they have one or more services running in background. You can see those in your phone setting->apps menu.
Study this for more information about services.

Libgdx + android.app.Service, how to?

So i want to do certain things always run in background. I've read that to do that i need to use android.app.Service, so i could not find anything that explain how to do this with libgdx so i did this.
on the AndroidLauncher I added this line
startService(new Intent(getBaseContext(),MyServices.class));
MyServices.class extends Service and on onStartCommand() i added a new thread that has a infinite loop, like this:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(){
private long startTime;
public void run() {
while(true){
if(System.currentTimeMillis() - startTime >= 1000){
startTime = System.currentTimeMillis();
System.out.println("running");
}
}
};
}.start();
return START_STICKY;
}
The app keeps printing "running" every second even when the app is not running, but I feel like this is not the correct way to do this, can someone please enlighten me? Thanks
Same for me, I am trying to implement :
this is what you are looking for, Bound Service
Edit:
Add service to your Androidmanifest.xml file
Bind Service to Activity or Start service
bind service mean if activity stop also service stop, example a music player,
starting service, will not stop, like a service where it give notifications even if application is not running.
There is also a permission for on boot, you need to implement so that the service start when your phone boot up.
happy coding.

Android service stops after less than 5 minutes

I am creating an Android application that needs to constantly send UDP packets to a server.
The problem is that after 2-5 minutes, after the screen is off, the service stops sending data, until I turn the screen back on (can also confirm on the server side).
Here is the service start command:
startService(new Intent(getBaseContext(), Service.class));
The onStartCommand:
#Override
public int onStartCommand(Intent intent, int flags, int startId){
Toast.makeText(this, "Armed!", Toast.LENGTH_LONG).show();
(new Thread(new App())).start();
return START_REDELIVER_INTENT;
}
And the run method, from the App thread:
public void run(){
Vibrator alarm = (Vibrator) MainActivity.getAppContext().getSystemService(Context.VIBRATOR_SERVICE);
String IP = getWiFiIP(MainActivity.getAppContext());
while(true){
while (IP.equals(wifiAddr)){ //Confirm presence on local network, with host
//Unlocked door
System.out.println("Started locally!");
sendData(KEY, hostAddrLocal);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
IP = getWiFiIP(MainActivity.getAppContext());
}
}
}
I am positive that I am not running out of memory, I have no other applications up, running on Galaxy S4, with Lollipop 5.0
Is it because I am interacting with the main activity, to get the context
MainActivity.getAppContext() ?
I tried many things, including STICKY_SERVICE.
The problem is that after 2-5 minutes, after the screen is off, the service stops sending data, until I turn the screen back on (can also confirm on the server side).
The CPU has powered down, as has the WiFi radio, in all likelihood. You would need to acquire a WakeLock and a WifiLock to keep both powered on. For ordinary users with ordinary hardware, keeping the CPU and WiFi radio on all the time will be very unpopular due to battery drain.
Android is programmed to fall asleep after inactivity. When that happens, it powers down the processor and doesn't allow any app to process. To be an exception to this rule, you need to hold a partial wakelock. Doing so will cause you to use more battery though so try not to hold it longer than needed.

Service crashing and restarting

There are several questions about it but I always read the same thing: "the service will be killed if the system need resources" or "you can't build an service that runs forever because the more it runs in background, more susceptible it is to the system kills it" and etc.
The problem I'm facing is: My service runs fine and as it is expected, if I run my app then exit it my service is still running, but when I kill my app (by going to the "recent apps" and swype it away) the service stops. In this moment, if I go to the Settings >> aplications >> running I'll see that the service is restarting. After a while, it goes back and my Service run with no problem.
I google it and I find some things I could do but lets see my code first:
I start my service by this way (after a button click):
Intent intent = new Intent (MainActivity.this, MyService.class);
startService(intent);
I also have 3 Integers I put in extra, so I have something like this:
final Integer i, i2, i3;
i = 5; //for example
i2 = 10; //for example
i3 = 15; //for example
final Intent intent = new Intent (MainActivity.this, MyService.class);
intent.putExtra("INTEGER1", i);
intent.putExtra("INTEGER2", i2);
intent.putExtra("INTEGER3", i3);
startService(intent);
In MyService I have the folloywing:
public class MyService extends Service
{
AlarmManager am;
BroadcastReceiver br;
PendingIntent pi;
Integer i, i2, i3;
#Override
public void onCreate()
{
super.onCreate();
am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
pi = PendingIntent.getBroadcast(this, 0, new Intent("anyany"); 0) //Why those zeros?
br = new BroadcastReceiver ()
{
public void onReceive (Context context, Intent i) {
new thread(new Runnable()
{
public void run()
{
//do something
}
}).start();
}
};
}
#Override
public void onStartCommand(Intent intent, int flags, int startId)
{
super.onStartCommand(intent, flags, startId);
try
{
i = intent.getIntExtra("INTENT1", 0) // I don't understant yet why this zero are here
i2 = intent.getIntExtra("INTENT2", 0)
i3 = intent.getIntExtra("INTENT3", 0);
}
catch(NullPointerException e) {}
this.registerReceiver(br, new IntentFilter("anyany"));
new thread(new Runnable()
{
public void run()
{
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock. elapsedRealtime() + i*1000, i2*1000, pi);
}
}).start();
return START_REDELIVER_INTENT; //so I can get my Extra even with my Activity closed
}
My onDestroy:
#Override
public void onDestroy()
{
unregisterReceiver(br);
super.onDestroy();
}
I also have onBind() method (without #Override), but it returns null.
I google a lot and I tried to run the service in foreground, so I did this (inside de onStartCommand):
Notification n = new Notification(R.drawable.ic_laucher), getText(R.string.app_name), System.currentTimeMillis());
PendingIntent npi = PendingIntent.getActivity(this, MainActivity.class);
n.setLatestEventInfo(this, getText(R.string.notification_title), getText(R.string.notification_message), npi);
startForeground(3563, n);
My notification appears and when I click on it my app runs, but the problem with my service wasn't fixed (I believe it still not run on foreground). The notification is restarted too.
I also deleted the Try catch and I define a value for the integers (so I didn't use the getIntExtra() method), but nothing changed
After several tests I tried to see the logs, when I kill my App I have the following message: Scheduling restart of crashed service.
So, for some reason my service crash when my MainActivity dies, why? The intention here is not to transform the service in a god that can not be killed (I don't think it is impossible at all, the WhatsApp are running for 105 hours !) but prevent my Service to not being crashed after my App dies.
I don't know if this'll help but this is what I add on my Manifest.xml
<Activity android:name = ".MyService"/>
<service android:name ="Myservice" android:enabled="true" android: exported="false"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
Min API = 9, target API = 17.
Size of the Service when running: about 3MB.
Hope I was clear and sorry for my English.
PS: the entire code are running as expected, so if you see any sintax error fell free to edit it.
EDIT
If I add android:isolatedProcess="true" in the <service> in AndroidManifest.xml I receive this error in logCat: java.lang.RuntimeException: Unable to create a service in com.mycompany.myapp.myservice: java.lang.SecurityException: Isolated process not allow ed to call getIntentSender
When I start my service using this, the MainActivity does not show any erros, only the service crashes.
I finally found the solution ! I removed the AlarmManager from the Service and the service does not cashed anymore, but I have to use it
The problem is the service crash after the user swype away the app from Recent App, so what I did was prevent the app to appear in that window. Add the following to your AndroidManifest.xml as a child of <activity>
android:excludeFromRecents="true"
Now when the user exit from your app it wil not appear in the recent apps window, what means the system kills the Activity right after you exit it, so it'll not waste any resources.
PS: don't forget to set the service to run in a separate process, add the following to your AndroidManifest.xml, as a child of <service>
android:process=":remote"
EDIT - REAL SOLUTION FOUND
After a lot of research and study (months of study) I took a deep look at android APIs and here is what a found, this is na expected behaviour that occours only at API 16+, a change at android arquiteture changed the way that PendingIntents are broadcasted by the system, so Google added the flag FLAG_RECEIVER_FOREGROUND, you must pass this flag to the intent you are using as a parameter on the PendingIntent.getBroadcast(), here is na example:
if(Build.VERSION.SDK_INT >= 16) //The flag we used here was only added at API 16
myIntent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
//use myIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); if you want to add more than one flag to this intent;
PendingIntent pi = PendingIntent.getBroadcast(context, 1, myIntent, 0); // the requestCode must be different from 0, in this case I used 1;
Android versions older than API 16 will work as expected, the service won't crash if you swype away the app from Recent Apps page.
As the documentation says, a Service runs in the main thread of its callee, that usually is the UI Thread. So what is happening is that when you kill your application, you kill your application process and thus the service is killed too.
You can workaround this behavior by creating your Service in a different process by using android:process in your <service> tag in the Manifest.xml file.
Usually, though, you start a Service in its own process if the Service needs to be independent from the callee and if it may be used by different application. If your Service is for your own application use only, then stick with the default behavior and simply don't kill you application.
EDIT 1:
The documentation for android:isolatedProcess says:
If set to true, this service will run under a special process that is
isolated from the rest of the system and has no permissions of its
own. The only communication with it is through the Service API
(binding and starting).
From another SO answer (Link), this is the expected behavior. But surely, someone here will have a workaround or a solution.
Your questions from code:
pi = PendingIntent.getBroadcast(this, 0, new Intent("anyany"); 0)
//Why those zeros?
The first zero you see is mentioned as a requesCode and decribed as not being used presently:
requestCode: Private request code for the sender (currently not used).
The second zero should actually be one of the flags given (here).
i = intent.getIntExtra("INTENT1", 0) // I don't understant yet why
this zero are here
The getIntExtra(String, int) method of Intent doesn't need to have 0 as its second argument: it can be any integer. getIntExtra(String, int) returns an integer corresponding to the String key you provide. In the event that this key no long exists(or never did), getIntExtra(String, int) returns the integer we pass as the second argument. It is the default value when the key fails.

Starting an update checker thread, checking for new entries in a database

I need some suggestions for approaches to take...
Here's some background info:
Right now I have an Android app and a separate java program running on my server.
The java program continuously go out and gets information from different sites and stores them in 14 different entries in an SQL database on the server.
The Android app then queries the databases to retrieve the info to be displayed.
My goal:
I need suggestions on how to have the app handle checking for updates from the database, and then letting the user know that there is new information.
My first thought is that maybe I need to start a separate thread that queries the database for a time modified. Then if it finds updates, it would pop up on the screen that there is new information.
I'm not too well educated with the way threads or services work, so I guess I'm looking for how to implement this, or whether there is a completely different way to go about update checking that would be better.
Thanks in advance, I appreciate any feedback, input, or suggestions.
Hi Ryan I have also implemented a similar thing in my android app and surprisingly I also had 14 tables in my PostgreSQL Server. First of all, you would want to poll the server periodically even when the app is not in the foreground. For that you need to run a background Service - here you will have to manually create a thread in the service, because Service by default runs on the UI thread OR use an IntentService - you don't have to create a separate thread. Whatever code you write in the intent service will be handled in a different thread automatically
Now you have to make this service execute periodically. For that use an AlarmManager and use the setRepeating()function. In the arguments you have to give a PendingIntent to your Service or IntentService. But don't use an alarm manager if you are going to poll the server for every less than 1 minute. Because the battery will be wasted a lot.
Here is some code that might give you an idea :
function setalarm()
{
Intent intent = new Intent(getBaseContext(), Intent_Service.class);
PendingIntent sender = PendingIntent.getBroadcast(getBaseContext(), 192837, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Random randomGenerator = new Random();
long interval=60000; //1 minute in milliseconds
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC, cal.getTimeInMillis(),interval,sender);
}
This is Intent_Service of type IntentService :
public class BackService extends IntentService
{
Context context=this;
//public Timer t=null;
public BackService()
{
super("myintentservice");
}
#Override
protected void onHandleIntent(Intent intent)
{
try
{
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();
//..CPU will remain on during this section..
//make our network connections, poll the server and retrive updates
//Provide a notification if you want
wl.release();//Release the powerlock
}
}
}
But if you want instantaneous updates, then use Google Cloud Messaging Services. To know more about how it works see this
Hope this helps you.

Categories

Resources