Context for an inherited service

84 views Asked by At

Maybe my question is a bit dumb but I searched how to do this and I figured it out how can I solve this and I can't.

I'm trying to create a Notification from a service when an event occur with the NotificationCompat class.

NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                                     .setSmallIcon(R.drawable.ic_launcher)
                                     .setContentTitle("My Notification Title")
                                     .setContentText("Something interesting happened");

The problem is that object "this" is a FileObserver class and I don't know how to get context from it to initialize notifications. To sum up, Can I get context inside that event listener?

public abstract class DBAbstractService extends Service {
    .....
}

public class FileModificationService extends DBAbstractService {

    public FileModificationService() {
    }

    @Override
    public void onCreate(){
       ......
       ......
       public void onEvent(int event, String file) {
            if((FileObserver.CLOSE_WRITE & event) != 0){
                if(file.substring(0,3).equals("RVE")) {
                    try {
                         if (aux[2].equals("D")){
                                Log.i("INFO:", "Modificación no realizada");

                                NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                                                .setSmallIcon(R.drawable.ic_launcher)
                                                .setContentTitle("My Notification Title")
                                                .setContentText("Something interesting happened");
            //More code
        }

Any help is appreciated. Thank you very much.

2

There are 2 answers

0
J.K On BEST ANSWER
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                                     .setSmallIcon(R.drawable.ic_launcher)
                                     .setContentTitle("My Notification Title")
                                     .setContentText("Something interesting happened");

inside onEvent method hence this will not point to Service object so you have to write

  NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext())
                                         .setSmallIcon(R.drawable.ic_launcher)
                                         .setContentTitle("My Notification Title")
                                         .setContentText("Something interesting happened");
0
Mahmoud Hashim On

In fact a Service is a Context, that is why you reference it by this keyword to pass the required Context object, and you may reference it from an inner class by typing FileModificationService.this and that would accomplish the task.