您好我正在开发一个Android短信应用程序,我在活动中使用广播接收器,参考以下链接,
SMS Delivery Report in Android
我试过这段代码
public class Myapp extends Activity
{
BroadcastReceiver sendBroadcastReceiver= new sentReceiver();
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activtiy_main);
}
public void onClick(View v)
{
if(v.getId()==sendmsg.getId())
{
sendSMS(phoneNumber,message);
}
@Override
protected void onDestroy()
{
super.onDestroy();
try
{
unregisterReceiver(sendBroadcastReceiver);
}
catch (Exception e)
{
e.printStackTrace();
}
}
//unregistering Receiver even in onPause()
private void sendSMS(String phoneNumber, String message)
{
String SENT = "SMS_SENT";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
registerReceiver(sendBroadcastReceiver, new IntentFilter(SENT));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, null);
}
class sentReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent arg1)
{
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "sms_sent", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Myapp.this, Sm.class));
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",Toast.LENGTH_SHORT).show();
Log.e("No service","");
break;
}
}
}
}
但我收到警告
java.lang.IllegalArgumentException: Receiver not registered: com.example.Myapp$Receiver@40593ab8
我不知道如何在清单中注册接收器。请建议。谢谢!
答案 0 :(得分:0)
1。您正在使用
以编程方式注册接收方registerReceiver(sendBroadcastReceiver, new IntentFilter(SENT));
所以没有必要将它添加到Manifest中。
2. 您有一个名为“sentReceiver”的自定义BroadcastReceiver类,因此在实例化时应使用此objecttype。
所以你需要改变
BroadcastReceiver sendBroadcastReceiver= new sentReceiver();
到
SentReceiver sendBroadcastReceiver = new sentReceiver();
3。我认为你是在错误地命令你的东西。这样接收器就不应该准备好听了。
答案 1 :(得分:0)
您需要在活动的oncreate方法中实例化sendBroadcastReceiver。这将允许在调用ondestroy方法并且接收器未被您的代码注册后“重新注册”。正如Bofredo所说,使用自定义calss进行实例化。