Stop a service after time - android

I want to stop my Service after a user defined time (choosen in a activity).
Now I want to start the timer in the service, but I cant use static timer because I have to stop the service (stopService(), stopSelf() are non-static methods.
Is there a simple way to do it?
(Now I used a handler with a runnable which checks if a variable is set to true and then starts the timer)

Use AlarmManager. Call set() on an AlarmManager, supplying the time when you want your service to stop and a getService() PendingIntent that will send a command to your service. In onStartCommand(), when you receive the Intent command from the PendingIntent, call stopSelf().

Related

run an IntentService at most once

I have an IntentService and I want for the startCommand to be called only if it's not already running.
The reason for this is this service is processing all existing rows in database. It can be called to start several times but if it's already running it shouldn't be started again. And similar to IntentService after there are no rows to be processed, it should close itself.
Is this achievable? Maybe with PendingIntent and FLAG_NO_CREATE ?
I could create this with a Service and a separate thread instead of a IntentService but IntentService already has the thread implemented.
Maybe with PendingIntent and FLAG_NO_CREATE ?
That flag refers to creating the PendingIntent, not the service.
Is this achievable?
Off the cuff:
Step #1: In your service, add an AtomicBoolean field (here called isRunning), initially set to false.
Step #2: Override onStartCommand(). If isRunning is false, set it to true and chain to super.onStartCommand() to inherit normal IntentService behavior. If isRunning is true, do not chain to super.onStartCommand().
Step #3: In onHandleIntent(), wrap all your work in a try/finally block, where you set isRunning to false in finally.
Net: a startService() invocation will only go through normal IntentService processing if onHandleIntent() is not already running.

Android : which is the best way to periodically call a function?

I have to do a particolar function one time Every 2 seconds, and I have to stop it when a certain broadcast message arrive then I have to restart it when other message arrives. I use handler postdelayed(runnable,time) and inside the runnable function i have called postdelayed(this,2000). But i can't stop it.. And when I restart the runnable I have different runnable started at the same time.
I call handler.removecallback
You can use the AlarmManager for scheduling repeat events, you can cancel the alarm using the cancel() method.
E.g. alarmManager.cancel(pendingIntent);

Sending message from Activity to intentService

My question is as follows:
I started my intentService from my main Activity. This intentService does some audio processing with audioRecord.
However, when I need to start another activity in my application (recording video in this case), i need to stop the intentService in the background (because it is hogging the audio resource).
Is there a way to stop the intentService from the main activity?
You can use stopService() from your main activity like this:
stopService(new Intent(yourMainActivity.this,yourIntentService.class));
use the same pre-declared intent which you used to start the IntentService and call
stopService(intent);
if you create a new intent and use it to stop the service, the service will not respond to it until its finishes processing the previous intent.
but it should be noted that this will not immediately stop the service. So a workaround to this is to have a Global boolean variable. When its set to true the processing within the service will carry out, and when you want to end it set the boolean variable to false from your activity. and then you can stop the service from within itself by calling
stopSelf();

how to contact a service's method from a notification?

I am implementing a music player. The notifications allow the user to pause or skip a song.
I use
Intent i = new Intent("com.package.app");
mExpandedView.setOnClickPendingIntent(R.id.next_song, PendingIntent.getBroadcast(this, 0, i, 0));
In order to transmit this click to the MusicService that hosts the MediaPlayer and all the associated methods. I would like to directly call a method part of this service (playNextSong() for example) but getService() seems to only allow me to launch a new service, not to call a method in the service, or get some data. I don't even need to launch the service, since the music is playing, it is already running.
So is there a way to do this that I am not aware of ?, or is :
Notification broadcasts to BroadcastReceiver, then BroadcastReceiver broadcasts to the service the recommended way do accomplish this action ?
It looks like a convoluted way to do something simple...
Create PendingIntent for notification as broadcast message, custom one (use your own string like com.my.custom.broadcast.message.action). Create and register in AndroidManifest new broadcast receiver that will be fired by this custom action. OnReceive method of the Broadcast receiver, start your service with custom arguments/action or whatever, based on class of Service and context arguments passed into onReceive method.
Probably you can try to directly start service by creating PendingIntent for that, but I think it is better do it through middle-step: BroadcastReceiver
From the Notification you can start an Activity. That activity would do "bindService" and call the appropriate method in the service, then finish(). The activity doesn't need to have a UI, so the user won't see it. But that's even more code than a Broadcastreceiver.

Display status bar notification from service in android

Hi
i've got a kind of a dumb problem. Im trying to display a notification from a service. When an activity starts i call the startService like so:
Intent myIntent = new Intent(getApplicationContext(),notif_service.class);
startService(myIntent);
the service calculates something and should display the notification and then stop. the code is as follows:
if (limit_time_value == 2 && start >= 6300000 && notif_past)
{
notif_past=false;
showNotification();
stopSelf();
}
There are two ways that this service can be stopped, ether from itself with stopSelf() or from a button in my activity with
Intent myIntent = new Intent(getApplicationContext(),notif_service.class);
stopService(myIntent);
the problem is that even when i stop the service the notification is shown after the specified time passes. I tried to stop the setvice with Binding it and than calling onDestroy() in which I cancel the notification and again call stopSelf(). Again the notification is shown.
What am I doing wrong? Do I misunderstand how notifications or services work?
You do not indicate precisely where you are performing the work shown in your second code snippet above.
If that work is being done in onStart() or onStartCommand(), that work is being performed on the main application thread, and therefore once it starts it blocks all other main application thread work, such as stopService() and onDestroy().
If that work is being done on a background thread you create, unless you are terminating that background thread, that thread will continue to completion, regardless of whether the service is destroyed. You will need to arrange to terminate the thread yourself.
Call the instance of the NotificationManager class which you have called inside the showNotification() function.
For example, I have used:
NotificationManager nm=(NotificationManager)this.getSystemService(this.NOTIFICATION_SERVICE);
nm.notify(1,builder.build());
If you have done something like this to create your notification, use the same instance to cancel it by calling cancel() function and passing the notificationId (in this case 1).
For example:
nm.cancel(1);
Here 1 denotes the notificationID which you have provided while creating it.

Categories

Resources