我在使用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>
和我的部分代码
公共类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());
}
}
} 谁能给我一些帮助并告诉我它为什么会发生?非常感谢!
答案 0 :(得分:6)
您的SMSReceiver
是非静态实例类。这意味着它只能在持有类NotificationActivity
的上下文中构建。这很好,但你不能在你的清单中注册它,因为系统需要构建一个NotificationActivity
来实例化你的接收器来处理广播。
答案 1 :(得分:4)
SMSReceiver
是非静态内部类,如果要将接收器保留在清单中,请将其设置为静态或将其移出NotificationActivity
。
当您将BroadcastReciever添加到清单时,您声明它始终是已注册的(因此您不需要注册并在活动中取消注册)
如果您确实希望将其保留在清单中,则Activity和BroadcastReceiver的生命周期会有所不同,因此访问textViewFrom
正如您目前所做的那样危险。
如果您希望仅在活动“活着”时触发接收器,请将其从清单中删除