java - 应用程序强制关闭。短信广播接收器

标签 java android broadcastreceiver

我是 Android Studio 新手。当我在单个 Activity 上运行它时,它运行正常,但是当我有多个 Activity 时,它会强制关闭。

错误

 02-12 00:18:42.578 5092-5092/com.example.driveassist E/AndroidRuntime: FATAL EXCEPTION: main
        Process: com.example.driveassist, PID: 5092
        java.lang.RuntimeException: Error receiving broadcast Intent { act=android.provider.Telephony.SMS_RECEIVED flg=0x8000010 (has extras) } in com.example.driveassist.firstPage$1@30b6fb57
            at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:876)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
         Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
            at com.example.driveassist.firstPage$1.onReceive(firstPage.java:77)
            at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:866)
            at android.os.Handler.handleCallback(Handler.java:739) 
            at android.os.Handler.dispatchMessage(Handler.java:95) 
            at android.os.Looper.loop(Looper.java:135) 
            at android.app.ActivityThread.main(ActivityThread.java:5254) 
            at java.lang.reflect.Method.invoke(Native Method) 
            at java.lang.reflect.Method.invoke(Method.java:372) 
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

my activity codes are

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.speech.tts.TextToSpeech;
import android.telephony.SmsMessage;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;

public class firstPage extends AppCompatActivity {
    private Button button,btbutton,acbutton;
    private final int CHECK_CODE = 0x1;
    private final int LONG_DURATION = 2000;
    private final int SHORT_DURATION = 1200;

    private Speaker speaker;

    private ToggleButton toggle;
    private CompoundButton.OnCheckedChangeListener toggleListener;

    private TextView smsText;
    private TextView smsSender;

    private BroadcastReceiver smsReceiver;
    private String address;

    private void checkTTS(){
        Intent check = new Intent();
        check.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(check, CHECK_CODE);
    }
    @SuppressLint("MissingSuperCall")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == CHECK_CODE){
            if(resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS){
                speaker = new Speaker(this);
            }else {
                Intent install = new Intent();
                install.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(install);
            }
        }
    }
    private void initializeSMSReceiver(){
        smsReceiver = new BroadcastReceiver(){
            @Override
            public void onReceive(Context context, Intent intent) {

                Bundle bundle = intent.getExtras();
                if(bundle!=null){
                    Object[] pdus = (Object[])bundle.get("pdus");
                    for(int i=0;i<pdus.length;i++){
                        byte[] pdu = (byte[])pdus[i];
                        SmsMessage message = SmsMessage.createFromPdu((byte[]) pdus[0]);
                        String text = message.getDisplayMessageBody();
                        address = message.getOriginatingAddress();
                        String sender = getContactName(message.getOriginatingAddress());
                        speaker.pause(LONG_DURATION);
                        speaker.speak("You have a new message from" + sender + "!");
                        speaker.pause(SHORT_DURATION);
                        speaker.speak(text);
                        smsSender.setText("Message from " + sender);
                        smsText.setText(text);

                    }
                }

            }
        };
    }
    private String getContactName(String phone){
        Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
        String projection[] = new String[]{ContactsContract.Data.DISPLAY_NAME};
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if(cursor.moveToFirst()){
            return cursor.getString(0);
        }else {
            return address;
        }
    }

    private void registerSMSReceiver() {
        IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
        registerReceiver(smsReceiver, intentFilter);
    }


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

        toggle = (ToggleButton)findViewById(R.id.speechToggle);
        //smsText = (TextView)findViewById(R.id.sms_text);
        smsSender = (TextView)findViewById(R.id.senderView);

        toggleListener = new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton view, boolean isChecked) {
                if(isChecked){
                    speaker.allow(true);
                    speaker.speak(getString(R.string.start_speaking));
                }else{
                    speaker.speak(getString(R.string.stop_speaking));
                    speaker.allow(false);
                }
            }
        };
        toggle.setOnCheckedChangeListener(toggleListener);

        checkTTS();
        initializeSMSReceiver();
        registerSMSReceiver();


    button =(Button) findViewById(R.id.settingsButton);
            button.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View V) {
                    openActivity3();

                }
            });
            btbutton =(Button) findViewById(R.id.btsettingsButton);
            btbutton.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View V) {
                    btActivity();

                }
            });
            acbutton = (Button) findViewById(R.id.acceptButton);
            acbutton.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View V) {
                    readActivity();

                }
            });
        }
        public void openActivity3() {
            Intent intent = new Intent(this,editMessage.class);
            startActivity(intent);
        }
        public void btActivity() {
            Intent intent1 = new Intent(this,btConnectivity.class);
            startActivity(intent1);
        }
        public void readActivity() {
            Intent intent2 = new Intent(this,readMessage.class);
            startActivity(intent2);
        }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(smsReceiver);
        speaker.destroy();
    }

    }

最佳答案

以下错误消息意味着尝试调用 setText 方法时发生了对 null 的 TextView 类型引用的取消引用。当您收到广播 Intent 时,它会导致错误消息。

     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.driveassist.firstPage$1.onReceive(firstPage.java:77)

您的 onReceive 实现中有一个值得关注的问题。 接收时 -> smsText.setText(文本); <- smsText 尚未分配。因为行注释

创建时 ->//smsText = (TextView)findViewById(R.id.sms_text);

关于java - 应用程序强制关闭。短信广播接收器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60173490/

相关文章:

java - 依赖注入(inject) servlet 监听器

android - Android : Application or Service for asynchronous updates? 中的 MVC

android - 在广播接收器中优先接听电话

java - 如果响应与帖子类不同,如何从帖子请求中获得响应

java - 是否可以使用字符串内容作为绘画的图像修饰符?

java - IntelliJ 和 Maven - 无法创建 Maven 项目

java - 接收和输出 JSON 错误消息 Android

java - Google Play 服务更新到版本 13 后,出现错误

android - 广播接收器在应用程序被杀死时不调用服务

java - Android - 其他应用窃取我的 Intent 接收器?