Main Activity 中的 OnDestroy 异常使用 Android 片段

OnDestroy exception in Main Activity using Android fragment

我在使用片段的应用程序的 OnDestroy 方法中有一个 "Receiver no registered exception"。

我有一个 MainActiviy class,我在其中检查用户是否注册了帐户。 如果没有创建帐户,我加载注册帐户 class 片段以允许用户创建帐户。 用户创建帐户后单击按钮我重新启动 MainActivity class.

我只需要在用户创建帐户后注册广播接收器。

但是,在从 Frgamnent Class 重新启动 MainActivity class 后,我收到一个异常,即接收器未在 Main Activity 的 OnDestroy 事件中注册。

任何解决问题的帮助将不胜感激。

提前致谢,路易斯

我的主要Activity Class

public class MainActivity extends Activity {

    // if run on phone, isSinglePane = true
    // if run on tablet, isSinglePane = false
    static boolean isSinglePane;
    private GcmUtil gcmUtil;

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

        View v = findViewById(R.id.phone_container);
            if (!AccountRegisterCreated()){
                //this fragmment register an account to user, and save in Preferences 
                RegisterFragment myListFragment= new RegisterFragment();
                FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
                fragmentTransaction.add(R.id.phone_container, myListFragment);
                fragmentTransaction.commit();
                return;
            }
            registerReceiver(registrationStatusReceiver, new IntentFilter(Common.ACTION_REGISTER));
      }

      private BroadcastReceiver registrationStatusReceiver = new  BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null && Common.ACTION_REGISTER.equals(intent.getAction())) {
                switch (intent.getIntExtra(Common.EXTRA_STATUS, 100)) {
                    case Common.STATUS_SUCCESS:
                        getActionBar().setSubtitle("online");
                        break;
                    case Common.STATUS_FAILED:
                        getActionBar().setSubtitle("offline");
                        break;
                }
            }
        }
    };

@Override
protected void onPause() {
    ContentValues values = new ContentValues(1);
    super.onPause();
}

@Override
protected void onDestroy() {
     unregisterReceiver(registrationStatusReceiver);
 super.onDestroy();
}

private boolean AccountRegisterCreated(){
    SharedPreferences prefs;
    prefs= PreferenceManager.getDefaultSharedPreferences(this);
    String fullname = prefs.getString(DataProvider.COL_EMAIL,"");
    if (!fullname.isEmpty()) {
        return true;
    }
    return false;
}

}

我的片段Class:

public class RegisterFragment extends Fragment {
    private static SharedPreferences prefs;
    static final String TAG = "pushabout";
    TextView name;
    TextView email;
    TextView password;


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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.register, null);
        name = (TextView) view.findViewById(R.id.reg_fullname);
        email = (TextView) view.findViewById(R.id.reg_email);
        password = (TextView) view.findViewById(R.id.reg_password);

        if (email.getText().toString().isEmpty()){
            email.setText(Common.getPreferredEmail());
        }
        Button mButton = (Button) view.findViewById(R.id.btnRegister);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //checa email e reg e salva pref e registra gcm
                prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
                SharedPreferences.Editor editor = prefs.edit();
                editor.putString(DataProvider.COL_NAME, sname);
                editor.putString(DataProvider.COL_EMAIL, semail);
                editor.putString(DataProvider.COL_PWD, spassword);
                editor.commit();
                Intent intent = new Intent(getActivity(), MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
        return view;
    }
}

问题不在于片段。它是您 Activity.

中的 BroadcastReceiver

尝试将 BroadcastReceiver 声明为 class 字段:

public class MainActivity extends Activity {
    ...
    BroadcastReceiver mBroadcastReceiver;
    ...

然后,您应该更改创建和注册接收器的方式。我的做法是在 activity 的 onResume 而不是 onCreate() 期间注册。如果这样做,您还需要在 onPause() 而不是 onDestroy() 期间注销。它看起来像这样:

@Override
public void onResume() {
    super.onResume();

    // Create and register your receiver here.

    if (AccountRegisterCreated) {
        mBroadcastReceiver = new  BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                ....
            }
        }
        registerReceiver(mBroadcastReceiver, new IntentFilter(Common.ACTION_REGISTER));
    }

    ...
}

@Override
public void onPause() {
    super.onPause();

    // Unregister your receiver here

    if (mBroadcastReceiver != null) {
        unregisterReceiver(mBroadcastReceiver);
    }
}

声明一个boolean类型的成员变量即可。当您注册 BroadcastReceiver 时,将该变量设置为 true。在 onDestroy() 中,仅当变量为 true.

时才调用 unregisterReceiver()