我正在开发一个简单的应用程序,当从任何应用程序修改 SMS 时通知用户我正在使用内容观察器问题是我想运行它,即使我的应用程序已关闭,所以如果我的应用程序已关闭并且某些用户将 SMS 标记为阅读他应该收到 1 条短信已修改的通知
这是我的代码
public class SMSObserver extends ContentObserver
{
SMSLogger smsLogger;
Context context;
public SMSObserver(SMSLogger smsLogger, Context context) {
super(new Handler());
this.context=context;
this.smsLogger = smsLogger;
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
smsLogger.querySMS(context);
}
}
public class SMSLogger {
protected void querySMS(Context context) {
Uri uriSMS = Uri.parse("content://sms/");
Cursor cur = context.getContentResolver().query(uriSMS, null, null, null, null);
/* cur.moveToNext(); // this will make it point to the first record, which is the last SMS sent
String body = cur.getString(cur.getColumnIndex("body")); //content of sms
String add = cur.getString(cur.getColumnIndex("address")); //phone num
String time = cur.getString(cur.getColumnIndex("date")); //date
String protocol = cur.getString(cur.getColumnIndex("protocol")); //protocol*/
Toast.makeText(context, "Data Changed CHECK SMS" , Toast.LENGTH_SHORT).show();
/*logging action HERE...*/
}
}
这是注册码
知道在哪里添加这些代码行,以便在任何 SMS 更新时始终通知用户吗?
Toast.makeText(this.getBaseContext(), "Data Changed CHECK SMS", Toast.LENGTH_SHORT).show();
final Uri SMS_STATUS_URI = Uri.parse("content://sms");
SMSLogger sl= new SMSLogger();
SMSObserver smsSentObserver = new SMSObserver(sl, this.getBaseContext());
getContentResolver().registerContentObserver(SMS_STATUS_URI, true, smsSentObserver);