Libgdx + android.app.Service, how to? - java

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.

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.

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.

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.

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

android service performing a task continuously at specif intervals

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

Categories

Resources