我创建了一个可以接收短信的应用程序。我已经使用后台服务中的广播接收器创建了此应用。现在,由于不存在来自android oreo的后台服务,因此如何在android oreo中接收短信。请帮助我。
答案 0 :(得分:0)
首先,您应该请求权限:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
并在您的代码中应用;
第二,使用短信内容提供商:
Uri SMS_INBOX = Uri.parse("content://sms/");
ContentResolver cr = getContentResolver();
String[] projection = new String[] { "body" };//"_id", "address", "person",, "date","type
String where = "";// your condition
Cursor cur = cr.query(SMS_INBOX, projection, where, null, "date desc");
if (null == cur)
return;
while(cur.moveToNext()) {
// your code
}
最后,实现您的功能;
答案 1 :(得分:0)
步骤1: 所需权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
步骤2:
制作一个名为SmsReceiver
的接收器类,并将其添加到Mainifest.xml文件中。
<receiver android:name=".SmsReceiver" android:enabled="true" android:exported="true">
<intent-filter android:priority="2147483647">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
步骤3: 实现接收器类
public class SmsReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
public static final String SMS_BUNDLE = "pdus";
String smsReceiveNumber, smsReceivedBody;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(SMS_RECEIVED)) {
Bundle intentExtras = intent.getExtras();
if (intentExtras != null) {
Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
String smsMessageStr = "";
for (int i = 0; i < sms.length; ++i) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);
String smsBody = smsMessage.getMessageBody().toString();
String address = smsMessage.getOriginatingAddress();
smsMessageStr += "SMS From: " + address + "\n";
smsMessageStr += smsBody + "\n";
smsReceiveNumber = address;
smsReceivedBody = smsBody;
}
}
}
}
}
第4步: 在主要活动中添加运行时权限
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!havePermission()) {
havePermission();
}
}
public boolean havePermission() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(Manifest.permission.RECEIVE_SMS) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECEIVE_SMS}, 1);
return false;
}
} else {
return true;
}
}
}