I want to receive notification when the messages arrives with using Broadcast Receiver. I wrote this code but it doesnt work;
I added this code in my AndroidManifest class;
<receiver android:name=".receiver.SMSReceiver" >
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
And my SMSReceiver class;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class SMSReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle pudsBundle = intent.getExtras();
Object[] pdus = (Object[]) pudsBundle.get("pdus");
SmsMessage messages = SmsMessage.createFromPdu((byte[]) pdus[0]);
Toast.makeText(context, "New SMS: " + messages.getMessageBody(),
Toast.LENGTH_LONG).show();
Log.d(getClass().getName().toString(), "SMS Arrived");
}
}
This code must show me a Toast Message when SMS arrived. How can i fix this problem? Thank you.
You must have the permissions:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
If you want to send sms you will need permission :
<uses-permission android:name="android.permission.SEND_SMS" />
I think you need to register your broadcast receiver. Hope for help.
@Override
public void onResume() {
super.onResume();
// Register mMessageReceiver to receive messages.
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("my-event"));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.