我是android编程的新手。
我在接收短信时已经阅读了很多关于做任何代码的内容,但所有代码都没有与我合作
请帮忙!
我想要做的是在收到短信时做一个祝酒词
这是我的AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.salkhuzayyim.toastwhenreceivesms">
<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=".SmsListener"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
这里是SmsListner.java
package com.salkhuzayyim.toastwhenreceivesms;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class SmsListener extends BroadcastReceiver {
public SmsListener() {
}
private SharedPreferences preferences;
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
Bundle bundle = intent.getExtras(); //---get the SMS message passed in---
SmsMessage[] msgs = null;
String msg_from;
if (bundle != null){
//---retrieve the SMS message received---
try{
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();
String msgBody = msgs[i].getMessageBody();
Toast.makeText(context, "SMS Received", Toast.LENGTH_SHORT).show();
}
}catch(Exception e){
// Log.d("Exception caught",e.getMessage());
}
}
}
}
}
我正在使用android studio,模拟器是(Nexus_5X_API_25)
有什么我应该和你们分享的事情让事情变得更容易吗?
提前致谢
答案 0 :(得分:1)
@sulaiman
根据您的评论:不,以下行不会向您提供阅读短信所需的权限。
dangerous
你仍然需要那条线。所以不要删除它。
这就是Android称之为“运行时权限”的原因。自API 23(6.0及更高版本)起,您需要明确要求获得INPUT_SELECT2
级别的所有权限的许可。
请阅读更多内容并了解其工作原理here。
至于解决此问题,您需要在首次打开应用时请求权限。请查看Request Permission
部分。