【问题标题】:Sms broadcastreceiver isn't working in my fragment短信广播接收器在我的片段中不起作用
【发布时间】:2016-09-29 23:26:48
【问题描述】:

我创建了一个应用程序可以接收短信的项目。它进展顺利,但是当我尝试将它实施到我的主项目时“它不起作用。我正在尝试将广播接收器实施到我的片段。我尝试了谷歌和不同的论坛,其中大多数人说这是权限,但我的已经设置好了:(。真的希望我能弄清楚这一点。

我的错误日志是这样写的。

FATAL EXCEPTION: main
                                                                  Process: c.timno.smsgsm20, PID: 23636
                                                                  java.lang.RuntimeException: Error receiving broadcast Intent { act=android.provider.Telephony.SMS_RECEIVED flg=0x8000010 (has extras) } in c.timno.smsgsm20.ThirdFragment$1@423ff210
                                                                      at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:788)
                                                                      at android.os.Handler.handleCallback(Handler.java:733)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                      at android.os.Looper.loop(Looper.java:136)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:5103)
                                                                      at java.lang.reflect.Method.invokeNative(Native Method)
                                                                      at java.lang.reflect.Method.invoke(Method.java:515)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:788)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:604)
                                                                      at dalvik.system.NativeStart.main(Native Method)
                                                                   Caused by: java.lang.NullPointerException
                                                                      at c.timno.smsgsm20.ThirdFragment.processReceive(ThirdFragment.java:75)
                                                                      at c.timno.smsgsm20.ThirdFragment$1.onReceive(ThirdFragment.java:55)
                                                                      at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:778)
                                                                      at android.os.Handler.handleCallback(Handler.java:733) 
                                                                      at android.os.Handler.dispatchMessage(Handler.java:95) 
                                                                      at android.os.Looper.loop(Looper.java:136) 
                                                                      at android.app.ActivityThread.main(ActivityThread.java:5103) 
                                                                      at java.lang.reflect.Method.invokeNative(Native Method) 
                                                                      at java.lang.reflect.Method.invoke(Method.java:515) 
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:788) 
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:604) 
                                                                      at dalvik.system.NativeStart.main(Native Method) 

我的安卓清单。

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="c.timno.smsgsm20">


    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.READ_SMS" />



    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_heicon"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".Splash"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>




        <activity android:name=".MainActivity"

            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
            <meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".MainActivity"/>

</activity>





        <!--
 ATTENTION: This was auto-generated to add Google Play services to your project for
     App Indexing.  See https://g.co/AppIndexing/AndroidStudio for more information.
        -->
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />


        <activity
            android:name=".SettingsActivity"
            android:label="@string/title_activity_settings"></activity>
    </application>

</manifest>

我的片段

package c.timno.smsgsm20;

import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Created by TimNo on 2016-09-09.
 */
public class ThirdFragment extends Fragment{




    private View view ;


   View myView;
    BroadcastReceiver receiver=null;
    @SuppressWarnings("ResourceType")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.third_layout, container, false);
        return inflater.inflate(R.layout.third_layout, container, false);


    }



    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        view = getActivity().findViewById(R.id.content_frame);


        IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context arr0, Intent arr1) {
                processReceive (arr0, arr1);


            }
        };
        getActivity().registerReceiver(receiver,filter);


    }

    public void onDestroy() {

        super.onDestroy();
        getActivity().unregisterReceiver(receiver);

    }

    public void processReceive (Context context, Intent intent){

        Toast.makeText(context, "You got a message",Toast.LENGTH_LONG).show();
        TextView lbs = (TextView)view.findViewById(R.id.textvview);


        Bundle bundle = intent.getExtras();
        Object[] objArr= (Object[])bundle.get("pdus");
        String sms ="";

        for (int i=0;i<objArr.length;i++){
            SmsMessage smsMsg = SmsMessage.createFromPdu((byte[])objArr[i]);
            String smsBody = smsMsg.getMessageBody();
            String senderNumber = smsMsg.getDisplayOriginatingAddress();
            sms +="From: " + senderNumber+"\nContent: "+smsBody+"\n";
        }
        lbs.setText(sms);

    }
}

提前谢谢大家!

【问题讨论】:

  • NullPointerException at ...(ThirdFragment.java:75) - 查看 ThirdFragment 类中的第 75 行。看起来view 为空。
  • 我想你的应用在前台收到短信但在屏幕外时会引发 NPE,对吗?

标签: java android android-studio android-fragments android-broadcast


【解决方案1】:

解决方案是代码应该在我的 MainActivity.java 中。我认为广播接收器只能“从 MainActivity 调用,而不是在 fragment.java 中调用。我把代码放在我的 onResume 上,它工作了:D。我的 textview(我加载的短信)在片段 xml 文件中。

BroadcastReceiver receiver=null;
   @Override
    protected void onResume() {
       super.onResume();
   


       IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
       receiver = new BroadcastReceiver() {
           @Override
           public void onReceive(Context arr0, Intent arr1) {
               processReceive (arr0, arr1);


           }
       };
       registerReceiver(receiver,filter);


   }

    public void onDestroy() {

        super.onDestroy();
        unregisterReceiver(receiver);

    }

    public void processReceive (Context context, Intent intent){

        Toast.makeText(context, "You got a message",Toast.LENGTH_LONG).show();
        TextView lbs = (TextView)findViewById(R.id.textvviewtsmsruta);


        Bundle bundle = intent.getExtras();
        Object[] objArr= (Object[])bundle.get("pdus");
        String sms ="";

        for (int i=0;i<objArr.length;i++){
            SmsMessage smsMsg = SmsMessage.createFromPdu((byte[])objArr[i]);
            String smsBody = smsMsg.getMessageBody();
            String senderNumber = smsMsg.getDisplayOriginatingAddress();
            sms +="From: " + senderNumber+"\nContent: "+smsBody+"\n";
        }
        lbs.setText(sms);



    }

【讨论】:

    猜你喜欢
    • 2014-06-21
    • 1970-01-01
    • 2012-11-14
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多