1

嗨,我正在开发一个 android SMS 应用程序,我在引用以下链接的活动中使用广播接收器,

Android 中的 SMS 发送报告

我试过这段代码

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

不确定我需要如何在清单中注册接收器。请建议。谢谢!

4

2 回答 2

0

您需要在活动的 oncreate 方法中实例化 sendBroadcastReceiver。这将允许在调用 ondestroy 方法并且接收者被您的代码取消注册后“重新注册”。正如 Bofredo 所指出的,使用您的自定义 calss 来实例化。

于 2013-09-06T14:43:21.987 回答
0

1.您正在以编程方式注册您的接收器

registerReceiver(sendBroadcastReceiver, new IntentFilter(SENT));

所以也没有必要将它添加到 Manifest 中。

2.您有一个名为“sentReceiver”的自定义BroadcastReceiver 类,因此在实例化它时应该使用此对象类型。

所以你需要改变

BroadcastReceiver sendBroadcastReceiver= new sentReceiver();

SentReceiver sendBroadcastReceiver = new sentReceiver();

3.我认为你以错误的顺序调用你的东西。这样接收器就没有准备好在应该收听的时候收听。

于 2013-09-03T09:19:18.437 回答