Android SMS BroadcastReceiver NullPointer

Android SMS BroadcastReceiver NullPointer

我正在尝试开发一个基本的 SMS 应用程序,但我遇到了 NullPointerException 问题。 嗯,有代码:

MainActivity.java

public class MainActivity extends AppCompatActivity {

Button btnSendSMS;
EditText txtPhoneNo;
EditText txtMessage;
sendSMS sendSMS=new sendSMS();



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
    txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
    txtMessage = (EditText) findViewById(R.id.txtMessage);
    ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.SEND_SMS},1);

    btnSendSMS.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View v)
        {
            String phoneNo = txtPhoneNo.getText().toString();
            String message = txtMessage.getText().toString();
            if (phoneNo.length()>0 && message.length()>0) {
                sendSMS.sendSMS(phoneNo, message,getApplicationContext());

            }
            else
                Toast.makeText(getApplicationContext(),
                        "Please enter both phone number and message.",
                        Toast.LENGTH_SHORT).show();
        }
    });
}}

还有 sendSMS class:

public class sendSMS  extends Activity {

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
}


//---sends an SMS message to another device---
public void sendSMS(String phoneNumber, String message,Context context)
{
    String SENT = "SMS_SENT";
    String DELIVERED = "SMS_DELIVERED";

    PendingIntent sentPI = PendingIntent.getBroadcast(context, 0,
            new Intent(SENT), 0);

    PendingIntent deliveredPI = PendingIntent.getBroadcast(context, 0,
            new Intent(DELIVERED), 0);

    //---when the SMS has been sent---
    registerReceiver(new BroadcastReceiver(){
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            switch (getResultCode())
            {
                case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS sent",
                            Toast.LENGTH_SHORT).show();
                    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();
                    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;
            }
        }
    }, new IntentFilter(SENT));

    //---when the SMS has been delivered---
    registerReceiver(new BroadcastReceiver(){
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            switch (getResultCode())
            {
                case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS delivered",
                            Toast.LENGTH_SHORT).show();
                    break;
                case Activity.RESULT_CANCELED:
                    Toast.makeText(getBaseContext(), "SMS not delivered",
                            Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }, new IntentFilter(DELIVERED));

    SmsManager sms = SmsManager.getDefault();
    sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}}

还有关于错误的日志:

FATAL EXCEPTION: main
              Process: com.example.lcssgml.appsmsmms, PID: 5861
              java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Intent android.content.Context.registerReceiver(android.content.BroadcastReceiver, android.content.IntentFilter)' on a null object reference
                  at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:586)
                  at com.example.lcssgml.appsmsmms.sendSMS.sendSMS(sendSMS.java:41)
                  at com.example.lcssgml.appsmsmms.MainActivity.onClick(MainActivity.java:46)
                  at android.view.View.performClick(View.java:5610)
                  at android.view.View$PerformClick.run(View.java:22260)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6077)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

我想不通这个问题。我希望你能帮帮我!谢谢

您已将 sendSMS class 设为 Activity subclass,大概是为了让 registerReceiver() 方法能够解析。您无法使用 new 实例化 Activity 并使其正常工作。它保留的 Context 成员永远不会被正确初始化,这就是为什么你得到 NullPointerException.

您已经将 Context 传递给 sendSMS() 方法,因此您只需调用 registerReceiver() 即可。

context.registerReceiver(...);

此外,sendSMS class 不应该是 Activity subclass,所以你应该删除 extends ActivityonCreate() 覆盖。此外,sendSMS() 方法现在可以是 static,因此您无需创建 class 的实例即可使用它,直接在 [= 上调用该方法即可45=]。我还要提到 Java 中的 class 名称应以大写字母开头。

public class SendSMS {

    public static void sendSMS(...) {
        ...
    }
    ...
}

调用它:

SendSMS.sendSMS(...);

建议在使用完接收器后使用 Context#unregisterReceiver() 注销接收器。您可能会发现不使用匿名 BroadcastReceiver 实例更容易做到这一点。

我还应该指出,如果您发送的消息超过了您正在使用的字母表中单部分消息的字符限制,SmsManager#sendTextMessage() 方法通常会无提示地失败。