2011-06-13 65 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。