我的 onReceive 永远不会被执行。我尝试了以下在线指南,包括来自官方网站的指南。我正在虚拟 API 28 设备上进行测试。我知道一些GUI
-related 代码可能是错误的,但我至少应该得到一个日志输出对吗?我错过了什么?
显现:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.receivesms">
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".SMSReceiver"
android:enabled="true"
android:exported="true"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter android:priority="100">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
接收者,第一个 Log.D 甚至没有执行:
public class SMSReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("MESS", intent.getAction());
Bundle bundle = intent.getExtras();
if (bundle != null) {
SmsMessage[] msgs;
String message;
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], bundle.getString("format"));
message = msgs[i].getMessageBody();
Log.d("MESS", message);
((EditText) LayoutInflater.from(context).inflate(R.layout.activity_main, null)
.findViewById(R.id.editText)).append(msgs[i].getDisplayOriginatingAddress()
+ "\n" + message + "\n");
}
abortBroadcast();
}
}
}
主要的:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestSmsPermission();
}
private void requestSmsPermission() {
String permission = Manifest.permission.READ_SMS;
int grant = ContextCompat.checkSelfPermission(this, permission);
if (grant != PackageManager.PERMISSION_GRANTED) {
String[] permission_list = new String[1];
permission_list[0] = permission;
ActivityCompat.requestPermissions(this, permission_list, 1);
} else {
Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
Log.d("", "Permission granted");
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
requestSmsPermission();
} else {
Toast.makeText(this, "permission not granted", Toast.LENGTH_SHORT).show();
}
}
}
}