2011-06-13 60 views
2

我使用的是contentObserver监视sms content provider的内容多了,我已经把Log.d()标签进行调试,并在logcat标签是被视为不止一次意味着onchange() id被多次调用,我如何防止这种情况发生。我已经在后台运行的服务中实现了观察者。 这里是平变化函数被调用一次


回答

0

我使用的是内容的观察者观看传出短信,发现该代码

package com.messageHider; 

import android.app.Service; 
import android.content.ContentResolver; 
import android.content.Intent; 
import android.database.ContentObserver; 
import android.database.Cursor; 
import android.net.Uri; 
import android.os.Handler; 
import android.os.IBinder; 
import android.util.Log; 
import android.widget.Toast; 

public class smsSentService extends Service { 
ContentResolver contentResolver; 
Uri uri=Uri.parse("content://sms/"); 
Handler handler; 
@Override 
public IBinder onBind(Intent arg0) { 
    return null; 
} 
@Override 
public void onCreate() { 
    contentResolver=getContentResolver(); 
    contentResolver.registerContentObserver(uri, true, new contentObserver(handler)); 
    Log.d("SENTSERVICE", "Service created"); 
    super.onCreate(); 
} 
@Override 
public void onStart(Intent intent, int startId) { 
    Log.d("SENTSERVICE", "Service started"); 
    super.onStart(intent, startId); 
} 
@Override 
public void onDestroy() { 
    super.onDestroy(); 
} 
public class contentObserver extends ContentObserver 
{ 
    public contentObserver(Handler handler) { 
     super(handler); 

    } 
    @Override 
    public void onChange(boolean selfChange) { 
     Cursor cursor=contentResolver.query(uri, null, null, null, null); 
     cursor.moveToFirst(); 
     String type=cursor.getString(cursor.getColumnIndex("type")); 
     Log.d("THEMESSAGE", type); 
     super.onChange(selfChange); 
    } 
} 

},如果你试图从模拟器发送外发SMS,你居然看到它的3个实例,因为它试图重新发送文本,但失败。你是否也看到了入站文本消息?

如果只是出站SMS消息,请查看SMS状态字段。 -1值表示失败。

0

您需要覆盖deliverSelfNotifications()以返回true。

class contentObserver extends ContentObserver { private Context mContext; 

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

    } 

    @Override 
    public void onChange(boolean selfChange) { 
     Cursor cursor=contentResolver.query(uri, null, null, null, null); 
     cursor.moveToFirst(); 
     String type=cursor.getString(cursor.getColumnIndex("type")); 
     Log.d("THEMESSAGE", type); 
     super.onChange(selfChange); 
    } 

    @Override 
    public boolean deliverSelfNotifications() { 
     return true; 
    } 
} 
+0

我重写deliverSelfNotifications()然后onChange()被调用两次。 – 2012-03-09 05:55:44

1

只是一个建议:注册上的onResume方法的内容观察者和注销其上的onPause。