Hasaan Ahmed
Hasaan Ahmed

Reputation: 69

Android service doesn't send notifications on app exit

I have created a background service that checks for value changes in my Firebase Database and sends a Notification if there are any changes. The service notifies for value changes as long as the app is running. When I close the app, I stop receiving notifications. My onStartCommand contains a new thread comprising of a firebase value event listener. As the value changes

I call sendNotification method. Here's my complete service class:

public class NotifyService extends Service {

Firebase mRef;

@Override
public IBinder onBind(Intent p1)
{
    // TODO: Implement this method
    return null;
}


@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    Toast.makeText(this,"service started",Toast.LENGTH_LONG).show();
    Firebase.setAndroidContext(this);
    mRef= new Firebase(myURL);
    Runnable run = new Runnable(){
        @Override
        public void run(){
            mRef.child("politics").child("story1").child("title").addValueEventListener(new ValueEventListener(){
                    @Override
                    public void onDataChange(DataSnapshot p1)
                    {
                        // TODO: Implement this method
                        String data = (String)p1.getValue();
                        sendNotification(data);
                    } 

                    @Override
                    public void onCancelled(FirebaseError p1)
                    {
                        // TODO: Implement this method
                    }
                });

            mRef.child("sports").child("story1").child("title").addValueEventListener(new ValueEventListener(){
                    @Override
                    public void onDataChange(DataSnapshot p1)
                    {
                        // TODO: Implement this method
                        String data = (String)p1.getValue();
                        sendNotification(data);
                    } 

                    @Override
                    public void onCancelled(FirebaseError p1)
                    {
                        // TODO: Implement this method
                    }
                });

            mRef.child("science").child("story1").child("title").addValueEventListener(new ValueEventListener(){
                    @Override
                    public void onDataChange(DataSnapshot p1)
                    {
                        // TODO: Implement this method
                        String data = (String)p1.getValue();
                        sendNotification(data);
                    } 

                    @Override
                    public void onCancelled(FirebaseError p1)
                    {
                        // TODO: Implement this method
                    }
                });

            mRef.child("gossip").child("story1").child("title").addValueEventListener(new ValueEventListener(){
                    @Override
                    public void onDataChange(DataSnapshot p1)
                    {
                        // TODO: Implement this method
                        String data = (String)p1.getValue();
                        sendNotification(data);
                    } 

                    @Override
                    public void onCancelled(FirebaseError p1)
                    {
                        // TODO: Implement this method
                    }
                });
        }};
    Thread serviceThread = new Thread(run);
    serviceThread.start();
    return Service.START_STICKY;
}
@Override
public void onDestroy() 
{
    Toast.makeText(this, "activity destroyed", Toast.LENGTH_LONG).show();
}

public void sendNotification(String title){
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(NotifyService.this);
    mBuilder.setSmallIcon(R.drawable.nicon); 
    mBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.nlicon));
    mBuilder.setAutoCancel(true);
    mBuilder.setContentTitle("New Story")   
    .setContentText(title);
    Intent resultIntent = new Intent(this, MainActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(NotifyService.this);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( 
        0,           
        PendingIntent.FLAG_UPDATE_CURRENT      
    );
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify((int)System.currentTimeMillis(), mBuilder.build());
}
}

I call it with

Intent i = new Intent(this, NotifyService.class);
startService(i);

What is it that doesn't let the notifications appear after app exit. I suspect it is something wrong with the notification method.

Upvotes: 3

Views: 872

Answers (1)

Hasaan Ahmed
Hasaan Ahmed

Reputation: 69

My service was apparently running in settings, but it was actually getting killed after the app was killed.

To keep your service running, instead of

startService(new Intent(this, MyService.class));

use this:

Intent serviceintent =new Intent(this, MyService.class);
    PendingIntent pendingintent =PendingIntent.getService(this,0, serviceintent,0);
    AlarmManager alarm =(AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarm.cancel(pendingintent);  
    alarm.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),5000, pendingintent);

This ensures your service keeps using AlarmManager every 5 seconds, so no matter what happens, the service will keep running.

Upvotes: 1

Related Questions