Sms broadcastreceiver не работает в моем фрагменте

Я создал проект, где приложение может получать sms. Все прошло хорошо, но когда я попытался реализовать его в своем основном проекте» это не сработало. Я пытаюсь реализовать broadcastreceiver в своем фрагменте. Я попробовал google и различные форумы большинство из них сказали, что это были разрешения, но мой уже установлен: (. Очень надеюсь, что я смогу получить некоторую ясность в этом.

Об этом говорится в моем журнале ошибок.

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

I created a project where the app can receive sms. It went well but when i tried to implement it to my Main project" it wouldn't work. I'm trying to implement the broadcastreceiver to my fragment. I tried google and different forums most of them said it was the permissions, but mine is already set :(. Really hope i can get some clarity in this.

My error log says this.

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) 

My android manifest.

<manifest 
    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>

My fragment

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);

    }
}

Thank you all in advance!

@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

I created a project where the app can receive sms. It went well but when i tried to implement it to my Main project" it wouldn't work. I'm trying to implement the broadcastreceiver to my fragment. I tried google and different forums most of them said it was the permissions, but mine is already set :(. Really hope i can get some clarity in this.

My error log says this.

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) 

My android manifest.

<manifest 
    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>

My fragment

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);

    }
}

Thank you all in advance!

.onReceive(ThirdFragment.java:55)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:778)
at android.os.Handler.handleCallback(Handler.java:733)&nbsp;
at android.os.Handler.dispatchMessage(Handler.java:95)&nbsp;
at android.os.Looper.loop(Looper.java:136)&nbsp;
at android.app.ActivityThread.main(ActivityThread.java:5103)&nbsp;
at java.lang.reflect.Method.invokeNative(Native Method)&nbsp;
at java.lang.reflect.Method.invoke(Method.java:515)&nbsp;
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:788)&nbsp;
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:604)&nbsp;
at dalvik.system.NativeStart.main(Native Method)&nbsp;

Мой Android манифест.

<manifest 
    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);

    }
}

Спасибо всем заранее!

1 ответ

  1. Решение было в том, что код должен был быть в моей основной активности.Ява. I think broadcastreceiver only can be » called from MainActivity and not in the fragment.Ява. Я положил код на моем onResume, и это сработало :D. мой textview (где sms Я загрузил) находится в 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);
    
    
    
        }