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.
Related
My Android application is activating a service that call an 'Activity.
On mainActivity:
startService(new Intent(getBaseContext(),MyService.class));
And then on service:
public int onStartCommand(Intent intent,int flage,int startId){
// Toast.makeText(this, "Yes please", Toast.LENGTH_LONG).show();
Intent mIntent=new Intent(MyService.this,trackingActivity.class);
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(mIntent);
return START_STICKY; }
At the end of trackingActivity this line is written (Again):
startService(new Intent(getBaseContext(),MyService.class));
That's creates a lot of Services. Is there a better way to create a background service that repeats itself always without creating each time a new Service ?
I tried to do a while loop inside the Activity :
while(true){
Actions on activity
}
But with no success.
Context.startService(Intent) does not create a new Service for each call.
If there is already a matching service running, it passes the intent to that running service, but does not create a new one each time.
See the Android Developer Docs for Context.startService(Intent):
If this service is not already running, it will be instantiated and
started (creating a process for it if needed); if it is running then
it remains running.
Every call to this method will result in a corresponding call to the target service's onStartCommand(Intent, int, int) method, with the intent given here.
There is similar information in the Android Developer Docs about Starting a Service:
[When starting a service using an intent] the startService() method returns immediately and the Android system
calls the service's onStartCommand() method. If the service is not
already running, the system first calls onCreate(), then calls
onStartCommand().
...
Multiple requests to start the service result in multiple
corresponding calls to the service's onStartCommand(). However, only
one request to stop the service (with stopSelf() or stopService()) is
required to stop it.
I want to call
onDestroy()
method of Service in android.
I already searched a lot on internet and many answers are like if
service force stop or somehow its onDestroy() will never call.
But I really need to know when service is stop.
My project is about music player.
So it uses service and there is an ongoing notification.
I need to find out when the service stop? and need to stop the music and remove the notification.
But it never shows any log of onDestroy().
Can anyone help me what is the alternative for it? if not onDestroy() then which method and how?
Edit:
I don't want to call onDestroy() explicitly. I want to remove notification when I remove my app from the device menu of running applications. Because when I stop my application, onDestroy() don't call and my notification remains in the status bar.
I have started my service with this code.
Intent playin = new Intent(this, MusicService.class);
startService(playin);
From within the Service class, call:
stopSelf();
From within another class, like your MainActivity for example:
Intent i = new Intent(this, ServiceName.class);
stopService(i);
Both of these will stop your service. Make sure you are returning START_NOT_STICKY so that the service doesn't start back up again.
When you want to stop your service then simply fire an intent to stop the service as shown below.
Intent intent = new Intent();
intent.setClass(getApplicationContext(), YourService.class);
stopService(intent);
This is to stop service forcefully.When you stop service in this manner it's guaranteed that onDestroy method is called by android framework.
Hope this helps to solve you issue.
I want to call onDestroy() method of Service in android.
Do not call this method directly
public void onDestroy ()
Called by the system to notify a Service that it is no longer used and
is being removed. The service should clean up any resources it holds
(threads, registered receivers, etc) at this point. Upon return, there
will be no more calls in to this Service object and it is effectively
dead. Do not call this method directly.
However you can check if the service is running or not.
I need to find out when service stop? and need to stop music and
remove notification.
Use the following way -
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
Then call it using - isMyServiceRunning(MyService.class).
Reference:
1) Service onDestroy().
2) how-to-check-if-a-service-is-running-in-android.
You should use Foreground service. In your case, I think it would be the best choice.
Foreground services show a status bar notification, so that users are actively aware that your app is performing a task in the foreground and is consuming system resources. The notification cannot be dismissed unless the service is either stopped or removed from the foreground.
To work with foreground service you first need to declare permission <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/> in your manifest. It is a normal permission so doesn't requires user action.
then, you can start the service for you Activity or other component using applicationContext.startForgroundService(intent). this is to tell the system that this will be a foreground service.
You need to start the foreground service from within your service(usually in onStartCommand()) using startForeground(int, Notification) and stop the service foreground service using stopForeground(boolean)(it takes a boolean asking whether you want to remove the notification or not)
after starting foreground service, if you close your app or the service stops itself, the notification will be remove too.
Note: when you manually want to stop the service, you should call stopSelf() or stopService() as calling stopForeground() is not enough, it merely remove the notification from the status bar.
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();
When I start a service (IntentService) it will call the onHandleIntent() which is the service function. While it is running, if I call startService() again, it caches the invoke, and calls the onHandleIntent() again. Actually what I want to do is, pass some new data to the current running service instance, without creating an additional. (Like signaling in threads or a listener).
How do I do it?
In my onHandleIntent() I want to use while(true){....} , so it will run forever.
Extend the normal Service class. On the first onStartCommand() that you receive, start a background thread that has your "while(true) {...}" code. On the onStartCommand() calls thereafter, check for the existence of your worker thread and when it exists, signal it.
Without knowing what you are going to use this Service for it is hard to give you any better advice. However, some things to think about:
- Check out the Looper/Handler classes that are also used by the IntentService.. They may give you some nice way to code your "while(true)" loop, including signalling.
- Remember that the onStartCommand() method should return within a few seconds (it is running on the main thread) so if you want to hand off new work (that is received through the Intent passed in onStartCommand) you should make sure this hand-off doesn't take too long. The Looper/Handler classes may help you here as well.
Check whether your service is already started, if not start it:
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("com.example.Service".equals(service.service.getClassName())) {
return true;
}
}
return false;
}
If I understand it correctly,
bindService() with BIND_AUTO_CREATE will start a service and will not die until all bindings are all unbinded.
But if I bindService(BIND_AUTO_CREATE) at onCreate() and hit back button to close the
activity, the service calls onDestroy() and dies also.
I don't call unbind() at anytime.
So is that mean when the Activity got destroyed, the binding got destroyed also and the service gets destroyed also?
What if I want the service to be always running, at the same time when the activity starts
I want to bind it so that I can access the service?
If I call StartService() and then bindService() at onCreate(), it will restart the service at every launch of Activity. (Which I don't want).
So I could I start service once and then bind next time I launch the activity?
You need to use startService so that the service is not stopped when the activity that binds to it is destroyed.
startService will make sure that the service is running even if your activity is destroyed (unless it is stopped because of memory constraints). When you call startService, the onStart method is called on the service. It doesn't restart (terminate and start again) the service. So it depends on how you implement the onStart method on the Service. The Service's onCreate, however, is only called once, so you may want to initialize things there.
I found a solution!
The problem is when you close your activity and your service is not configured as a foreground service, android system will recognize it as unused and close it.
here's an example where I added a notification :
void setUpAsForeground(String text) {
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0,
new Intent(getApplicationContext(), MainActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT);
mNotification = new Notification();
mNotification.tickerText = text;
mNotification.icon = R.drawable.muplayer;
mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
mNotification.setLatestEventInfo(getApplicationContext(), "MusicPlayer",
text, pi);
startForeground(NOTIFICATION_ID, mNotification);
}
(A foreground service is a service that's doing something the user is actively aware of (such as playing music), and must appear to the user as a notification. That's why we create the notification here)
you can do it with BroadcastReceivers. you'll find a lot on google how to use them