我写了一个程序,当收到短信时它会响起。但是它仅在程序运行时有效,而在程序关闭时则无效。
我该怎么办?
public class MainActivity : Activity
{
SampleReceiver receiver;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
receiver = new SampleReceiver();
IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
intentFilter.Priority = 1000;
RegisterReceiver(receiver, intentFilter);
// Code omitted for clarity
}
}
[BroadcastReceiver(Enabled = true, Exported = true)]
public class SampleReceiver : WakefulBroadcastReceiver
{
private const string IntentAction = "android.provider.Telephony.SMS_RECEIVED";
public override void OnReceive(Context context, Intent intent)
{
try
{
Android.Net.Uri uri = RingtoneManager.GetDefaultUri(RingtoneType.Ringtone);
Ringtone ringtone = RingtoneManager.GetRingtone(context, uri);
ringtone.Play();
if (intent.HasExtra("pdus"))
{
var smsArray = (Java.Lang.Object[])intent.Extras.Get("pdus");
foreach (var item in smsArray)
{
var sms = SmsMessage.CreateFromPdu((byte[])item);
string address = sms.OriginatingAddress;
string smsText = sms.MessageBody;
Toast.MakeText(context, "Massage from : " + address + " Says : " + smsText, ToastLength.Long).Show();
}
}
}
catch (System.Exception ex)
{
//Toast.MakeText(context, ex.Message, ToastLength.Long).Show();
}
}
}
Tnx