我正在创建一个应用程序,只要设备收到传入的短信,就会发出一个toast消息,即使应用程序在后台运行它也应该显示一个Toast消息。
我在Marshmallow 6.0设备(Moto M)上测试我的应用程序。 使用Android Studio进行开发api 23 marshmallow。
MainActivity.java:
package android.broadcastreceiversms;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
使用广播接收器在同一目录中的IncomingSMS.java类文件:
package android.broadcastreceiversms;
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.util.Log;
import android.widget.Toast;
/**
* Created by Mahesh on 09-01-2017.
*/
public class IncomingSms extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Bundle myBundle = intent.getExtras();
SmsMessage[] messages = null;
String strMessage = "";
if (myBundle != null) {
Object[] pdus = (Object[]) myBundle.get("pdus");
messages = new SmsMessage[pdus.length];
for (int i = 0; i < messages.length; i++) {
String format = myBundle.getString("format");
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i], format);
strMessage += "SMS From: " + messages[i].getOriginatingAddress();
strMessage += " : ";
strMessage += messages[i].getMessageBody();
strMessage += "\n";
}
Log.v("SMS", strMessage);
Toast.makeText(context, strMessage, Toast.LENGTH_SHORT).show();
}
}
}
的AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="android.broadcastreceiversms">
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
<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>
<receiver android:name=".IncomingSms">
<intent-filter android:priority="500">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</activity>
</application>
</manifest>