继承服务的上下文

时间:2014-12-17 08:57:46

标签: android fileobserver

也许我的问题有点愚蠢,但我搜索了如何做到这一点,我想出了如何解决这个问题,我无法解决。

我尝试使用NotificationCompat类在事件发生时从服务创建通知。

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

问题在于对象"这个"是一个FileObserver类,我不知道如何从中获取上下文来初始化通知。总结一下,我可以在该事件监听器中获取上下文吗?

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
        }

感谢任何帮助。非常感谢你。

2 个答案:

答案 0 :(得分:2)

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

onEvent方法内,因此this不会指向Service对象 所以你必须写

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

答案 1 :(得分:1)

实际上ServiceContext,这就是为什么您通过this关键字引用它来传递所需的Context对象,您可以从中引用它内部类通过键入FileModificationService.this来完成任务。