gpt4 book ai didi

android - 无法实例化接收者没有零参数构造函数

转载 作者:行者123 更新时间:2023-12-02 18:29:57 26 4
gpt4 key购买 nike

我在使用 BroadCastReceiver 时遇到一些问题。这里是 AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.zhang.notificationtest">

<uses-permission android:name="android.permission.RECEIVE_SMS"/>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NotificationActivity"></activity>
<receiver android:name=".NotificationActivity$SMSReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>

</manifest>

以及我的部分代码

公共(public)类NotificationActivity扩展了AppCompatActivity{

public TextView textViewFrom, textViewContent;
public IntentFilter intentFilter;
public SMSReceiver smsReceiver;

@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(smsReceiver);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);

textViewContent = (TextView)findViewById(R.id.textViewContent);
textViewFrom = (TextView)findViewById(R.id.textViewFrom);

intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
smsReceiver = new SMSReceiver();

registerReceiver(smsReceiver,intentFilter);
}

public class SMSReceiver extends BroadcastReceiver{

public SMSReceiver(){
}

@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] smsMessages = new SmsMessage[pdus.length];
for (int i = 0; i < smsMessages.length; i++)
smsMessages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
String from = smsMessages[0].getOriginatingAddress();
StringBuilder content = new StringBuilder("");
for (SmsMessage element: smsMessages)
content.append(element.getMessageBody());
textViewFrom.setText(from);
textViewContent.setText(content.toString());
}
}

}谁能给我一些帮助并告诉我为什么会发生这种情况?非常感谢!

最佳答案

您的SMSReceiver是一个非静态实例类。这意味着它只能在持有类 NotificationActivity 的上下文中构造。这很好,但您无法在 list 中注册它,因为系统需要构造一个 NotificationActivity 才能实例化您的接收器来处理广播。

顺便说一句,要么在 list 中注册接收器,要么在您的 Activity 中注册它,但不能同时注册。

关于android - 无法实例化接收者没有零参数构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39605408/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com