我有以下ContentObserver
接收和编写短信的实现,但它被多次调用。
代码:
public class SMSObserverActivity extends Activity {
protected MyContentObserver observer = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String url = "content://mms-sms/";
Uri uri = Uri.parse(url);
observer = new MyContentObserver(new Handler());
getContentResolver().registerContentObserver(uri, true, observer);
}
@Override
protected void onDestroy(){
super.onDestroy();
getContentResolver().unregisterContentObserver(observer);
}
class MyContentObserver extends ContentObserver {
ContentValues values = new ContentValues();
Handler handler;
public MyContentObserver(Handler handler){
super(handler);
this.handler = handler;
}
@Override
public boolean deliverSelfNotifications(){
return false;
}
@Override
public void onChange(boolean arg0){
super.onChange(arg0);
Log.v("SMS", "Notification on SMS observer");
values.put("status", 5);
Message msg = new Message();
msg.obj = "xxxxxxxxxx";
int threadId = 0;
handler.sendMessage(msg);
Uri uriSMSURI = Uri.parse("content://sms/");
Cursor cur =
getContentResolver().query(uriSMSURI, null, null, null,
null);
cur.moveToNext();
Log.e("sms", cur.getString(4)+" "+cur.getString(11));
}
}
}
显现:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.READ_SMS"></uses-permission>
<uses-permission android:name="android.permission.WRITE_SMS"></uses-permission>
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".SMSObserverActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
为什么会被多次调用?
编辑:
有人认为问题是由缺少引起的unregisterContentObserver
,但这没有什么区别。