Android 单击“后退”按钮时,广播接收器停止
我正在开发一个Android短信应用程序。下面的代码是我用来发送短信的Android 单击“后退”按钮时,广播接收器停止,android,sms,android-contentprovider,Android,Sms,Android Contentprovider,我正在开发一个Android短信应用程序。下面的代码是我用来发送短信的 public void sendSms(final String phoneNumber, final String message){ String SENT = "SMS_SENT"; String DELIVERED = "SMS_DELIVERED"; PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, ne
public void sendSms(final String phoneNumber, final String message){
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED),0);
//--- When the SMS has been sent --
sendBroadcastReceiver=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
ContentValues values = new ContentValues();
values.put("address", phoneNumber);
values.put("body", message);
getContentResolver().insert(Uri.parse("content://sms/sent"), values);
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
ContentValues values1 = new ContentValues();
values1.put("address", phoneNumber);
values1.put("body", message);
getContentResolver().insert(Uri.parse("content://sms/queued"), values1);
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
default:
break;
}
context.unregisterReceiver(this);
}
};
SmsManager sms = SmsManager.getDefault();
registerReceiver(sendBroadcastReceiver , new IntentFilter(SENT));
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
当我保持屏幕直到短信发送时,它工作正常。它会将短信息写入内容/sms/sent或queued取决于发送的报告。但如果我在发送短信息时按back按钮,它会发送短信息,但不会写入内容/sms/sent或queued,也不会注销广播
请帮我解决我的问题。当按下back键时,您基本上是在退出应用程序。因此,为了控制按下back时的行为,请重写onBackPressed()。在这里,您可以确保内容已写入,并且需要在此处注销广播 我通过使用服务解决了我的问题。使用startservice()和stopservice()我可以管理注册。谢谢朋友们的建议。
@Vikki…你的回答给了我答案。…你能再补充一点细节吗。。发送短信后,有时只按后退按钮,有时不发送短信,有时在发送时按。让服务处理广播我一定是看错了问题,尝试将广播接收器设置为静态或将其移到自己的类文件中。@vikki…谢谢你…你对这个问题有什么想法吗。。。