I'd like to run a service in background but after I read the docs I'm a bit confused.
(I'm targeting SdkVersion 27, which means I can't start a BroadcastReceiver from the AndroidManifest.xml and need to do these tasks within the Application class, afaik.)
Before I was starting the IntentService within a BroadcastReceiver, which I started by using a PendingIntent, which was triggered by an AlarmManager. It felt a bit too much, so I started the service directly on the onCreate() of the Application.
It's working, but I'm not sure if that's a good practice.
The service is supposed to run forever and fire it's own threads for operations that can take up to one minute and run again as soon as they are finished (+ 5 seconds).
Pseudocode of the services purpose
MyService // starts on Application creation an runs "forever"
threads = []
itemIds = []
async loop manageThreads // start / kill
itemIds = getItemIdsFromDatabase()
loop itemIds vs threads
if noThreadRunningForCurrentItemId
threads.push(new ItemThread(itemId).start())
loop threads vs itemIds
if threadRunsForNoneExistingItemId
threads[currentItemId].kill()
sleep(20000) // manage threads every 20 seconds
ItemThread(int itemId)
doSomething()
sleep(5000)
ItemThread(itemId) // restart thread every 5 seconds
I'd like to avoid that the service get's killed by Android, blocks other Threads or leads to memory leaks.
What's the best practise for this use-case, any idea?
I don't think my question is opinion-based, because I guess that a pattern exists, which I'm not aware of yet.
App.java
public class App extends Application {
#Override
public void onCreate() {
super.onCreate();
// Start MyService to run in the background
Intent service = new Intent(this, MyService.class);
this.startService(service);
}
}
MyService.java
public class MyService extends IntentService {
public MyService() {
super("MyService")
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
try {
int i = 0;
while(true) {
Log.d("MyService", "i = " + String.valueOf(i));
i++;
Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Related
I want to make a app which starts a foreground service to check which are other app are running at any time.
started services and running some logic part in different thread. Created notification and a timer (loop ) which check running apps at every 100 millisecond.
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
new Thread() {
public void run() {
startInForeground();
}
}.start();
return START_STICKY;
}
private void startInForeground() {
createNotification();
startTimer();
}
startTimer() function is below, which is checking any app is running in background. Everything is fine, i am able to detect which app is running.
public void startTimer() {
ScheduledExecutorService scheduler = Executors
.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
checkAnyAppOpen();
}
}, 0, 100, TimeUnit.MILLISECONDS);
}
My concern is- I have to run checkAnyAppOpen() function again and again for infinite period of time. So is it good ? or is there any other way to handle it.
What is impact of this method?.
My second question is- I am able to stop my service but still timer(scheduler) is running continuously. How can i stop it ?. How can it affect if it not stopped as i have to again restart my service after some period of time which may run 5 hour to 24 hour. I have to again do stop and restart.
Thanks
I believe for your use-case it is applicable. Just make sure there are no leaks and the service is closed properly.
Use scheduler.shutdown() to stop executor.
I am trying to make background service that will run 15 sec after user closes tha app, I have done service that runs 15 sec (loop with Logs), bud when I close tha app, then it stopes
and another problem is, when I try to stop it from main activity by stopService(intent); then the onDestroy method is called, but thread with loop continues
.. please can someone help me?
*sorry for my english - no native :D
public class NotificationService extends Service {
final private class MyThread implements Runnable {
int service_id;
MyThread(int service_id) {
this.service_id = service_id;
}
#Override
public void run() {
synchronized (this) {
for (int i = 0; i < 15; i++) {
try {
wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.e("onStartCommand", "loop:" + i);
}
stopSelf(service_id);
}
}
}
Thread thread;
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "onCreate", Toast.LENGTH_SHORT).show();
}
#Override
public int onStartCommand(#Nullable Intent intent, int flags, int startId) {
Log.e("onStartCommand", "started");
Toast.makeText(this, "onStartCommand", Toast.LENGTH_SHORT).show();
thread = new Thread(new MyThread(startId));
thread.start();
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
Log.e("onDestroy", "onDestroy");
Toast.makeText(this, "onDestroy", Toast.LENGTH_SHORT).show();
super.onDestroy();
}
}
I am trying to make background service that will run 15 sec after user closes tha app, I have done service that runs 15 sec (loop with Logs), bud when I close tha app, then it stopes
Your code only starts the loop thread when startService(yourNotificationService)is called on the Activity or Broadcast Receiverthat is responsible for calling it does so. It then kills itself with stopSelf(service_id).
If, after you have returned from onStartCommand(), you immediately kill the app without calling stopSelf(service_id) (i.e. your 15 seconds is not up), then your Service will MOST LIKELY restart itself given the START_STICKY return value. However, after you call stopSelf(service_id) you are telling the Service to kill itself; after you close your app, there is nothing to tell your Service to restart through the onStartCommand() call.
and another proble is, when I try to stop it from main activity by stopService(intent); then the onDestroy method is called, but thred with loop continues
A Service is an Android component; it is not another process or thread, it runs in the same process and thread as the main UI thread unless you specify otherwise, as seen here.
Note that services, like other application objects, run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work. More information on this can be found in Processes and Threads. The IntentService class is available as a standard implementation of Service that has its own thread where it schedules its work to be done.
In your case, calling stopService(intent) tells the Service to stop itself, which it does. It does not stop the Thread you started (the MyThread instance). To do that, you must first make your Thread interruptible; see here to do that. Once you do that, you need to change your onDestroy() code to actually interrupt the MyThread instance, as here
#Override
public void onDestroy() {
Log.e("onDestroy", "onDestroy");
Toast.makeText(this, "onDestroy", Toast.LENGTH_SHORT).show();
thread.interrupt();
super.onDestroy();
}
I've posted about this project before, I'm trying to create a service, from a Home Activity, that constantly checks if the screen is locked or not (ScreenLockService is the IntentService's name). If so, it creates another service to "listen" (Listener is the IntentService's name) for sound. If not, it stops the existing Listener service if one is running.
So to do so, I've created a Thread within the onHandleIntent method of SLS that should always be checking if the screen is locked or not. Here is how that's implemented so far:
(Sorry for the wall of code, I'll try to make it look pretty)
Thread checkScreen = new Thread(
new Runnable() {
#Override
public void run() {
Boolean lockInput = false;
while(!Thread.interrupted()) {
//The first time the screen becomes locked is special, it should start the whole process from there
KeyguardManager firstKeyManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
if (firstKeyManager.inKeyguardRestrictedInputMode()) {
lockInput = true;
}
//If the screen has been locked for the first time:
while(lockInput) {
//Put a timer here do slow the app down and figure out what's going wrong
new Timer().schedule(
new TimerTask() {
#Override
public void run() {
//if the screen is locked start listener service else stop listener service (METHODS WITHIN THIS SERVICE HANDLE THIS)
KeyguardManager secondKeyManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
if (secondKeyManager.inKeyguardRestrictedInputMode()) {
startListener();
}
else if (!secondKeyManager.inKeyguardRestrictedInputMode()) {
stopListener();
}
}
}, 10000 //10 seconds
);
}
}
}
}
);
//Might be relevant to the problem, if the thread dies I need it to start back up again.
//This is part of the onHandleIntent method, at the very bottom, and not inside the thread.
checkScreen.setName("checkScreen");
Log.d(TAG, "Starting SLS thread");
checkScreen.start();
checkScreenAlive = true;
while(checkScreenAlive){
if(!checkScreen.isAlive()){
Log.d(TAG, "Restarting check screen!");
checkScreen.start();
}
}
Now, I have Log messages all over the place so I can see what state the app is in (starting services, stopping services, checking the screen, listening, etc). When I debug it and lock the screen for the first time, nothing will be logged until 10 seconds later it spams Listener Service already running about 20 times then the service dies.
Maybe I don't fully understand how the timer works in java, but I have no clue why the service is dying. I probably don't even need to do this in a thread, or maybe not even use an IntentService and use a regular Service instead. I've read about the differences and I think what I have is right.
If I should post more code I can, don't hesitate to ask. I'm trying to make this as straightforward as possible, this is my first app and I'm still easily confused by some of this stuff.
You have while(lockInput) { which never gets set to false and will generate a lot of Timer().schedule events.
This schedule will be kicked after 10seconds which is where you are seeing the delay.
I would start by changing
while(lockInput) {
...
}
to
if(lockInput) {
lockInput = false; //Only want this called once per check
//Put a timer here do slow the app down and figure out what's going wrong
new Timer().schedule(
new TimerTask() {
#Override
public void run() {
//if the screen is locked start listener service else stop listener service (METHODS WITHIN THIS SERVICE HANDLE THIS)
KeyguardManager secondKeyManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
if (secondKeyManager.inKeyguardRestrictedInputMode()) {
startListener();
}
else if (!secondKeyManager.inKeyguardRestrictedInputMode()) {
stopListener();
}
}
}, 100 //Fire of the check almost instantly
);
}
Thread.sleep(10000); //So we are yeilding to the system, don't want an essential while(true) loop
I know that pausing a thread can easily lockup the UI, and it is generally a bad idea. However it was my understanding that if something is running as a service that will not cause any issues, because the service will pause and the main app will continue running.
With that in mind, I am either doing something wrong, or just misunderstood the use of a service for a MediaPlayer.
I create the object
public AudioService AudioService;
public boolean AudioServiceBound = false;
and then in my SurfaceView's onStart event I bind it:
public void onStart() {
Intent intent = new Intent(gameContext, AudioService.class);
gameContext.bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
}
throughout the rest of the class I run methods that pause and resume the AudioService based on the onResume and onPause events.
I have tried to introduce a new ability to my service. Within my main update loop I run the function HalfOverSwitch() seen below:
public void HalfOverSwitch()
{
if (( ((float)player.getCurrentPosition()) / ((float)player.getDuration()) > 0.5) && !transitioning)
{
transitioning = true;
MediaPlayer temp = MediaPlayer.create(this, R.raw.dumped);
temp.setVolume(0, 0);
temp.setLooping(true);
temp.start();
for (int i = 0; i < 100; i++)
{
player.setVolume(100-i, 100-i);
temp.setVolume(i, i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
player = temp;
player.setVolume(100,100);
transitioning = false;
}
}
Because that function doesn't return anything and is running in a different thread, it was my understanding that the main activity would not pause. It does however. That brings up the question, what is the best way to do something like that, and what is the point of making my AudioService a service at all (and not just a class)?
Service runs in the same thread in which service is created.
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. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work. "
I have a service that needs to compare previous and current html code.
I have configured it to do its work every 1 hour, but it actually does it in weird unlinear intervals. I have added to the code a command to write a log file in order to see whenever the work is done. The result is weird: sometimes the interval is less than an hour, sometimes much more (2-3 hours), and sometimes really 1 hour... edit: when the interval is shorter (1 minute) it operates normally here's my code:
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleWithFixedDelay(new Runnable() {
public void run() {
try {
if (isNetworkAvailable()) {
doServiceWork();
check("SLeEPING!!!", c);
}
else {
check ("NO INTERNET", c);
}
}
catch (Exception e) {check("78", c);}
}
}, 1, 3600, TimeUnit.SECONDS);
}
Use AlarmManager. You are making the thread sleep which I am not sure Android guarantees it will work that way. Something like this should help you. This will start the service every hour:
PendingIntent serviceIntent= PendingIntent.getService(context,
0, new Intent(context, MyService.class), 0);
long firstTime = SystemClock.elapsedRealtime();
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
long currenciesIntervalInSec = 3600;
if (automaticCurrencies)
am.setRepeating(AlarmManager.ELAPSED_REALTIME, firstTime, currenciesIntervalInSec*1000, serviceIntent);
Edit:
You should extend IntentService. It takes care of the threads and everything is done in the background (Its particulary useful if you need to do things in the background and you don't need several threads at the same time). Whatever you put in HandleIntent will be executed when you start the service. Internally it will keep a list of the queue.
For example this is a simple service class(You NEED to create both constructors):
public class MyService extends IntentService {
public MyService() {
super("MyService");
}
public MyService(String name) {
super(name);
}
#Override
protected void onHandleIntent(Intent arg0) {
if (isNetworkAvailable()) {
doServiceWork();
check("SLeEPING!!!", c);
}
else {
check ("NO INTERNET", c);
}
}
}
Also, you need to add this in your manifest (Of course with your own package):
<service android:name="com.services.MyService"/>
Maybe you activity is destroyed by the Android task Manager and it is not shutdown by the timer. This is why you are getting shorter values. And this is why, when setting a very low value, you don't get that.
You should read about how Android handles the Processes and applications here.