Search code examples
androidfileobserver

Context for an inherited service


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.


Solution

  • 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");