我有一个MainActivity.java和一个SmsReceiver.java 我希望在手机收到任何邮件时启动MainActivity。
MainActivity.java - >
public class MainActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String sms = getIntent().getStringExtra("message");
}
}
SmsReceiver.java - >
public class SmsReceiver extends BroadcastReceiver{
String str = "";
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
SmsMessage msgs = null;
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdus.length; i++) {
msgs = SmsMessage.createFromPdu((byte[]) pdus[i]);
str += msgs.getMessageBody().toString();
}
sendToMain(context,intent);
}
}
public void sendToMain(Context context,Intent intent){
Toast.makeText(context,"Message received", Toast.LENGTH_SHORT).show();
Intent i = new Intent(context,MainActivity.class);
i.putExtra("message",str);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_SINGLE_TOP);
context.startActivity(i);
}
}
和AndroidManifest.xml包含 - &gt;
<receiver android:name=".SmsReceiver"
android:exported="true">
<intent-filter>
<action android:name=
"android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
并且还给出了权限 - &gt;
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
但是当收到任何新消息时,没有任何反应......
请在此处说明是否有任何问题。