我正在尝试构建一个简单的应用程序,可以通知是否有短信传入。只是让广播公司工作,但是当我收到短信时我的应用程序崩溃,然后下次收到短信时没有任何反应。我没有任何错误信息可以追踪或显示。
清单
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.studerande.upg62_b">
<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>
<receiver
android:name=".IncomingSmsBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
我的广播类扩展了BroadcastReceiver。请原谅我的Toast,但我只是想看看它是否正在运行,但事实并非如此......
package com.example.studerande.upg62_b;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
/**
* Created by Studerande on 2017-03-18.
*/
public class IncomingSmsBroadcastReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
@Override
public void onReceive(final Context context, final Intent intent) {
if (intent != null && SMS_RECEIVED.equals(intent.getAction())) {
final SmsMessage smsMessage = extractSmsMessage(intent);
processMessage(context, smsMessage);
}
Toast.makeText(context, "yo", Toast.LENGTH_SHORT).show();
}
private SmsMessage extractSmsMessage(final Intent intent) {
final Bundle pudsBundle = intent.getExtras();
final Object[] pdus = (Object[]) pudsBundle.get("pdus");
String format = pudsBundle.getString("format");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[0], format);
return smsMessage;
}
else {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[0]);
return smsMessage;
}
}
private void processMessage(final Context context, final SmsMessage smsMessage) {
// Do something interesting here
Toast.makeText(context, "yo", Toast.LENGTH_SHORT).show();
}
}
MainActivity。如果我理解正确的话,你不需要在这里做任何事情吗?
package com.example.studerande.upg62_b;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
答案 0 :(得分:0)
我意识到问题是因为API版本。广播公司使用API 22或更低版本的手机,但由于引入了新的权限处理,因此不在更高版本中使用。所以我需要先获得许可才能阅读短信。 https://developer.android.com/training/permissions/requesting.html