我每次都用Broadcast Receiver
触发incoming messages
。应用程序在Android O
中是否正常运行,是否关闭。但是在Android P
中,只有当应用程序处于活动状态并且关闭应用程序时,它才可以工作。在Android P
中,无论应用关闭还是关闭,它都应该始终可以工作。我遵循了此link和其他许多规则,但问题仍然存在。
清单上的收件人注册
<receiver
android:name=".Broadcast.SmsListener"
android:enabled="true"
android:exported="true"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter android:priority="999">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
<action android:name="android.provider.Telephony.SMS_DELIVER" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
广播接收器类别
package com.techndev.payu.Broadcast;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Telephony;
import androidx.annotation.RequiresApi;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
import com.techndev.payu.Service.BackgroundService;
import java.io.File;
public class SmsListener extends BroadcastReceiver {
SmsMessage[] msgs;
String msg_from;
String msgBody;
Context context;
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Into onReceive()", Toast.LENGTH_SHORT).show();
Log.d("Resulted12", "Into onReceive()");
trimCache(context);
this.context = context;
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
msg_from = msgs[i].getOriginatingAddress();
msgBody = msgs[i].getMessageBody();
}
Uri uriSMSURI = Uri.parse("content://sms/inbox");
ContentValues contentValue = new ContentValues();
contentValue.put(Telephony.Sms.ADDRESS, msg_from);
contentValue.put(Telephony.Sms.BODY, msgBody);
context.getContentResolver().insert(Telephony.Sms.CONTENT_URI, contentValue);
}
}
还有其他我想念的东西吗?
这是由于从Android 8.0开始的新的Android Broadcast Receiver限制。在大多数情况下,您需要使用上下文注册的接收器而不是清单声明的。官方文档在这里:https://developer.android.com/guide/components/broadcasts