-1

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

当 NotificationCompat 类发生事件时,我正在尝试从服务创建通知。

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

问题是对象“this”是一个 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
        }

任何帮助表示赞赏。非常感谢。

4

2 回答 2

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

insideonEvent方法因此this不会指向Service对象,因此您必须编写

  NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext())
                                         .setSmallIcon(R.drawable.ic_launcher)
                                         .setContentTitle("My Notification Title")
                                         .setContentText("Something interesting happened");
于 2014-12-17T09:05:55.647 回答
1

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

于 2014-12-17T09:22:05.493 回答