Android IntentService in foreground - android

Hi I have got problems with launching IntentService as a foreground service. Unfortunatelly the official tutorial does not tell me much as some of methods does not exists, some are deprecated and moreover it's not said where to place the code, that they provide.
I created my own IntentService and I have overridden onCreate method. It looks following:
#Override
public void onCreate(){
super.onCreate();
Intent notificationIntent = new Intent(this, Settings.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new Notification.Builder(this)
.setContentTitle(getText(R.string.serviceName))
.setContentText(getText(R.string.serviceDescription))
.setSmallIcon(R.mipmap.ic_launcher)
.setOngoing(true)
.setContentIntent(pendingIntent)
.build();
startForeground(101, notification);
I know it's not debugging site, but surely there is something obvious, that I am missing. Settings class is my Activity class, from which startService was called, I have also set all needed things to the notification and called startForeground with nonzero first argument. Still no notification appears, although I am pretty sure, that service is working in the background.
Any help would be appreciated (btw. I have already searched for different topics on SO woth service in foreground, but with no help.)

If you use a Service instead of IntentService, you can put the code you wrote to build the notification & startForeground() in onStartCommand :
public class SettingsService extends Service {
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
public SettingsService getService() {
return SettingsService.this;
}
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
stopForeground(true);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent notificationIntent = new Intent(this, SettingsService.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new Notification.Builder(this)
.setContentTitle("myService")
.setContentText("this is an example")
.setSmallIcon(R.mipmap.ic_launcher)
.setOngoing(true)
.setContentIntent(pendingIntent)
.build();
startForeground(101, notification);
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
}
Additionnaly, in onStartCommand, return START_NOT_STICKY if you dont want the service to be recreated when it is killed otherwise return START_STICKY

Related

Same notification for multiple foregorund services, and keep the notification if any of them is stopped

I'm creating an app that uses two foreground services:
One for getting the Location
The other to updload it to a server (every 30secs)
I'm currently testing my app with a device running Nougat but I'd like to make it Oreo-ready.
First I was using a different Notification for each foreground service, but then I wanted to try using the same notification for both, as in this SO answer.
If I stop any of those services by calling stopService(intent) then the notification disappears even if the other foregroundService is still running.
Is there a way to keep the notification even after stopping one of the services?
Then, when both services are down I will manually remove the notification
EDIT added code as requested
This is how my services looks like (they are basically identical):
public class TrackingService extends Service{
#Override
public void onCreate() {
startForeground(getNotificationId(), getNotification(this));
// Some other tracking/server stuff
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Some other tracking/server stuff
return START_STICKY;
}
#Override
public void onDestroy() {
stopForeground(false);
}
I'm starting them with:
Intent intent = new Intent(getApplicationContext(), TrackingService.class);
startService(intent);
And then stopping with:
Intent intent = new Intent(getApplicationContext(), TrackingService.class);
stopService(intent);
I've read that calling stopService(intent) will also remove that service from the foreground. So the calling to stopForeground(false) is redundant, but I leave it anyway.
And the singleton for the Notification is:
public abstract class SingleNotificacion {
private static final int NOTIFICATION_ID = 1999;
private static Notification notification;
public static Notification getNotification(Context context) {
if(notification == null) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "default")
.setSmallIcon(R.drawable.ic_stat_notify)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setCategory(Notification.CATEGORY_SERVICE)
.setContentTitle(context.getString(R.string.settings_status_on_summary))
.setColor(ContextCompat.getColor(context, R.color.colorPrimaryDark));
notification = builder.build();
}
return notification;
}
public static int getNotificationId() {
return NOTIFICATION_ID;
}
public static void cancelNotification(Context context){
((NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE)).cancel(NOTIFICATION_ID);
}
}
I've also try setting onGoing(true) and 'autoCancel(false)' when creating the Notification with no luck

Check server for notifications for app and display them if present

I am creating an application on Android which has a MySql server. I want a notification if there is any data present in the File (The User has the job to remove it all but after verifying them). So, I need a good background worker which activates after one hour, checks if any data is there, send a notification, close itself and then again activate after one hour. The time one hour can be changed. I use a AsyncTask for downloading(Unavoidable). I am good at sending notifications and using AsyncTask.
I am a bit lazy so have not done any experiment before verifying that it will complete my task.
I think it may use the Service class. Please provide detailed information. Please give a whole tutorial when telling to use any Github Library cause I am new to Github.
Thank You,
Yours Respectfully,
India's youngest android application developer
I found out the solution Myself and so decided to help out any other new Programmer. Here it is-
AlarmReceiverLifeLog.java
public class AlarmReceiverLifeLog extends BroadcastReceiver {
private static final String TAG = "LL24";
static Context context;
#Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "Alarm for LifeLog...");
Intent serviceIntent = new Intent(context,MyReciever.class);
context.startService(serviceIntent);
}
}
MyReciever.java
public class MyReciever extends Service {
int mStartMode;
IBinder mBinder;
boolean mAllowRebind;
#Override
public void onCreate() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Your Method to get Data from Server
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public boolean onUnbind(Intent intent) {
return mAllowRebind;
}
#Override
public void onRebind(Intent intent) {
}
#Override
public void onDestroy() {
}
//method to show notification to be called when you finally decide that you have to notify the user
public void showNotification(String title,String message){
Log.d("Service","Going to show notification");
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.app_icon)
.setContentTitle(title)
.setContentText(message);
Intent notificationIntent = new Intent(this, NavigationActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
}
Add this in your AndroidManifest.xml
<receiver android:name=".AlarmReceiverLifeLog" >
</receiver>
<service android:name=".MyReciever" />
Activating the reciever
Intent ll24 = new Intent(this, AlarmReceiverLifeLog.class);
PendingIntent recurringLl24 = PendingIntent.getBroadcast(this, 0, ll24, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarms.setRepeating(AlarmManager.RTC_WAKEUP, 0, AlarmManager.INTERVAL_HALF_DAY, recurringLl24);//For waking it after each 12hrs.

Why in IntentService super.OnCreate delete a notification startForeground()

I'm continuing in the Android studies and i've a questions.
I'have this intentService:
public class SystemService extends IntentService{
public SystemService() {
super("SystemService");
}
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, startId, startId);
return(START_NOT_STICKY);
}
#Override
public void onCreate(){
super.onCreate();
startForeground();
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void startForeground(){
Intent notificationIntent = new Intent(this, DashboardActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification noti = new Notification.Builder(getApplicationContext())
.setContentTitle("Foregroundservice")
.setContentText("foreground is active")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent).build();
startForeground(1337, noti);
}
}
Why, in onCreate() function, if I put the function startForeground() so, ne initializing foregroundservice before the super.onCreate(), the foreground notify disappear But if a put after seem work?

Service never gets garbage collected

My application has a button : "Foreground". By clicking on the foreground button, a notification appears attached to a foreground service (started at the time of click). Clicking on my notification is supposed to stop my service (with a PendingIntent) to be able to be garbage collected, however, this is not the case. Android Studio tells me, that there is a reference to my Service held by a NotificationManager. The weird thing is that it only happens if I click on my notification after I closed the main activity.
My service code:
public class TestService extends IntentService {
public static final String ACTION_GO_FOREGROUND = "GO_FOREGROUND";
public static final String ACTION_DESTROY = "DESTROY";
private NotificationManagerCompat notificationManager;
public TestService() {
super("Name");
}
#Override
public void onCreate() {
super.onCreate();
notificationManager = NotificationManagerCompat.from(this);
}
#Override
public void onDestroy() {
super.onDestroy();
notificationManager.cancelAll();
notificationManager = null;
}
#Override
protected void onHandleIntent(Intent intent) {
}
#Override
public int onStartCommand(Intent intent, int flags, final int startId) {
switch (intent.getAction()) {
case ACTION_GO_FOREGROUND:
fg();
break;
case ACTION_DESTROY:
destruct();
break;
}
return START_STICKY;
}
private void destruct() {
stopForeground(true);
stopSelf();
}
private void fg() {
Intent intent = new Intent(this, TestService.class);
intent.setAction(ACTION_DESTROY);
// Create the notification.
android.support.v7.app.NotificationCompat.Builder notificationBuilder = new android.support.v7.app.NotificationCompat.Builder(this);
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
notificationBuilder.setTicker("Ticker");
notificationBuilder.setContentTitle("Title");
notificationBuilder.setContentText("Content text");
notificationBuilder.setContentIntent(PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
startForeground(1, notificationBuilder.build());
}
I know the code is messy, but it's just a sample. So why is there a reference to my service, but only if you close the activity and try to destroy the service?
Try removing the code from OnDestroy -
notificationManager.cancelAll();
notificationManager = null;
and place it in destruct() before calling stopSelf()

Android - Cancel Notification

I have a simple app that downloads a file from the internet using a service showing the progress in a progress dialog and also in an ongoing notification.
My problem is how to remove the notification when the user stops the download by force closing the app (for example by long pressing the home button and by clearing all the recent apps list).
I tried with this:
#Override
protected void onDestroy() {
Toast.makeText(getApplicationContext(), "ADDIO", Toast.LENGTH_SHORT).show();
NotificationManager nm =(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancelAll();
super.onDestroy();
}
but it doesn't work.
Please help
You could start a service from your activity.
Step 1 create a service that kills
Simple one. It just kills a notification on create and has his special Binder.
public class KillNotificationsService extends Service {
public class KillBinder extends Binder {
public final Service service;
public KillBinder(Service service) {
this.service = service;
}
}
public static int NOTIFICATION_ID = 666;
private NotificationManager mNM;
private final IBinder mBinder = new KillBinder(this);
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
#Override
public void onCreate() {
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNM.cancel(NOTIFICATION_ID);
}
}
Step2: Add it to your manifest:
Add it somewhere inbetween your <application> tags.
<service android:name="KillNotificationsService"></service>
Step3: Always create the Service before firing the notification, and use the static notificationid.
ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder binder) {
((KillBinder) binder).service.startService(new Intent(
MainActivity.this, KillNotificationsService.class));
Notification notification = new Notification(
R.drawable.ic_launcher, "Text",
System.currentTimeMillis());
Intent notificationIntent = new Intent(MainActivity.this,
Place.class);
PendingIntent contentIntent = PendingIntent.getActivity(
MainActivity.this, 0, notificationIntent, 0);
notification.setLatestEventInfo(getApplicationContext(),
"Text", "Text", contentIntent);
NotificationManager mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNM.notify(KillNotificationsService.NOTIFICATION_ID,
notification);
}
public void onServiceDisconnected(ComponentName className) {
}
};
bindService(new Intent(MainActivity.this,
KillNotificationsService.class), mConnection,
Context.BIND_AUTO_CREATE);
It might take a little time until service is restarted (1-5 sec), but it will eventually start and kill the notification.

Categories

Resources