【问题标题】:How to check which ContentObserver triggers the onChange method?如何检查哪个 ContentObserver 触发了 onChange 方法?
【发布时间】:2012-09-16 14:04:31
【问题描述】:

我想要做的是注册一个Service 和多个ContentObserver,并检查哪个ContentObserver 触发onChange() 进行特定反应。我不知道我是否只需要在onchange() 中包含一个 if/else,或者在每个 ContentObserver 中包含一个 Overwrite,无论哪种情况我都不知道该怎么做。提前感谢您的帮助。

public class SmsObserverService extends Service {

private String BABAS = "babas";
@Override
public void onCreate() {

    Handler handler = new Handler();

    this.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, new SmsObserver(handler));

    //Second observer
    this.getContentResolver().registerContentObserver(Uri.parse("CallLog.Calls.CONTENT_URI"), true, new SmsObserver(handler));

}


@Override
public IBinder onBind(Intent intent) {
    // TODO Put your code here
    return null;
}


public class SmsObserver extends ContentObserver{

    public SmsObserver(Handler handler) {
        super(handler);


    }
    @Override
    public void onChange(boolean selfChange) {          
        super.onChange(selfChange);

        //Where I should check somehow which ContentObserver triggers the onChange


        //This code to the sms log stuff, the call log part will be included
        //when I find out how to check whic observer trigerred the onChange
        Uri uri = Uri.parse("content://sms/");
        Cursor cursor = getApplicationContext().getContentResolver().query( uri, null, null, null, null);
        cursor.moveToNext();


        String body = cursor.getString(cursor.getColumnIndex("body"));
        String add = cursor.getString(cursor.getColumnIndex("address"));
        String time = cursor.getString(cursor.getColumnIndex("date"));


        String protocol = cursor.getString(cursor.getColumnIndex("protocol"));

        if(protocol == null){
            Toast.makeText(getApplicationContext(), "Enviada para: " +add + ", Hora: "+time +" - "+body, Toast.LENGTH_SHORT).show();
            Log.i(BABAS, "Enviada para: "+add +" " +"Time: "+time +" - "+body);
        }else{
            Toast.makeText(getApplicationContext(), "Recebida de: "+add + ", Hora: "+time +" - "+body, Toast.LENGTH_SHORT).show();
            Log.i(BABAS, "Recebida de: "+add +" " +"Time: "+time +" - "+body);
        }

    }

}

}

【问题讨论】:

  • 看看我的答案。

标签: android android-contentprovider onchange contentobserver


【解决方案1】:

我只需扩展 ContentObserver 并添加我在那里缺少的任何内容。

【讨论】:

  • 这就是我想做的,但我不知道怎么做。
【解决方案2】:
mObserver = new ContentObserver(new Handler(Looper.getMainLooper())) {

                @Override
                public void onChange(boolean selfChange, Uri uri) {
                    super.onChange(selfChange, uri);

                    }
                }
            };

你可以用上面的方法检查uri

【讨论】:

    猜你喜欢
    • 2012-02-25
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 2014-02-18
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多