我正在开发可检测传出短信并保存到房间数据库的android应用。我的目标是从API 22到28的新android版本。 对于传入的短信,我使用的是receiver(RECEIVE_SMS)。但是对于传出的短信,我尝试使用ContentResolver类。但是并不能保证这项工作。有时不起作用。
我从mainActivity运行它:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!hasReadSmsPermission()) {
showRequestPermissionsInfoAlertDialog();
}
ContentResolver contentResolver = getContentResolver();
contentResolver.registerContentObserver(Uri.parse("content://sms"), true, new SmsObserver(new Handler(), getApplicationContext()));
SetAlarmPeriodically.schedulePeriodic();
}
并使用onbootreceiver重新启动ContentResolver
public class OnBootReceiver extends BroadcastReceiver {
@SuppressLint("UnsafeProtectedBroadcastReceiver")
@Override
public void onReceive(Context context, Intent intent) {
JobManager.create(context).addJobCreator(new MyJobCreator());
SetAlarmPeriodically.schedulePeriodic();
}
}
onRunJob
@NonNull
@Override
protected Result onRunJob(@NonNull Job.Params params) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
ContentResolver contentResolver = getContext().getContentResolver();
contentResolver.registerContentObserver(Uri.parse("content://sms"), true, new SmsObserver(new Handler(), getContext()));
}
});
return Result.SUCCESS;
}
但重启电话后无法使用。应用安装后如何每次都收听所有传出的短信?有保证的解决方案吗?