我正在尝试开发基本的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类:

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$1.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类设置为Activity子类,以使registerReceiver()方法可以解析。您无法使用Activity实例化new并使它正常工作。它保留的Context成员将永远不会正确初始化,这就是为什么要获取NullPointerException的原因。

您已经将Context传递给sendSMS()方法,因此您可以在其上调用registerReceiver()

context.registerReceiver(...);


此外,sendSMS类不应是Activity子类,因此应删除extends ActivityonCreate()替代。而且,sendSMS()方法现在可以是static,因此您无需创建类的实例即可使用它,而可以直接在类上调用该方法。我还要提到Java中的类名应以大写字母开头。

public class SendSMS {

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


调用它:

SendSMS.sendSMS(...);


建议您在使用完接收器后,使用Context#unregisterReceiver()取消注册接收器。通过不使用匿名BroadcastReceiver实例,您可能会发现这样做更容易。

我还应该指出,如果您发送的消息超出了所用字母中单部分消息的字符数限制,则SmsManager#sendTextMessage()方法通常会静默失败。

10-05 17:41