1
\$\begingroup\$

I have implemented Google cloud messaging in my mobile app following the Google docs. It seems I have a lot going on in my MainActivity class at this point. I'm just wondering if there is a more efficient or better way to handle all the GCM tasks.

public class MainActivity extends AppCompatActivity {
    private static final int WELCOME_SEQUENCE_REQUEST_CODE = 1234;
    private static final int ACCOUNT_PICKER_REQUEST_CODE = 4321;
    public static final int REQUEST_CODE_ASK_PERMISSIONS = 3;
    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    private BroadcastReceiver mRegistrationBroadcastReceiver;
    private boolean isReceiverRegistered;

    // -------------------------------------------------
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //First check to see if G Services is available, bail otherwise
        if (googlePlayServicesIsValid()) {
            // Start IntentService to register this application with GCM.
            Intent intent = new Intent(this, GcmRegistrationHandlerService.class);
            startService(intent);
        }


        //Need to figure out something useful to do with this
        mRegistrationBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
                boolean sentToken = sharedPreferences.getBoolean(GcmConstants.SENT_TOKEN_TO_SERVER, false);
                if (sentToken) {
                    //mInformationTextView.setText(getString(R.string.gcm_send_message));
                } else {
                    //mInformationTextView.setText(getString(R.string.token_error_message));
                }
            }
        };


        //Register GCM Receiver
        registerReceiver();


        //Finally, create appropriate User View or launch first run sequence for new user
        if (userProfileIsValid()) {

            //Load a specific fragment as response to push notification
            //This is set up in utilities > gcm > GcmDataHandlerService
            Bundle b = getIntent().getExtras();
            String targetUserMode = "";
            if(b != null) {
                targetUserMode = b.getString("targetUserMode", "");
                NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                manager.cancel(getIntent().getIntExtra("NOTIFICATION_ID", -1));
            }

            if (targetUserMode.equalsIgnoreCase("buyer") || PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("userMode", "").equalsIgnoreCase("buyer")) {
                setContentView(R.layout.activity_buyer);
            } else {
                setContentView(R.layout.activity_seller);
            }


        } else {
            loadWelcomeSequence();
        }

    }

    // -------------------------------------------------
    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver();
    }

    // -------------------------------------------------
    @Override
    public void onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
        isReceiverRegistered = false;
        super.onPause();
    }

    // -------------------------------------------------
    private Boolean userProfileIsValid() {
        return !PreferenceManager.getDefaultSharedPreferences(this).getString("userMode", "").equalsIgnoreCase("");
    }


    //Register GCM receiver
    // -------------------------------------------------
    private void registerReceiver() {
        if (!isReceiverRegistered) {
            LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                    new IntentFilter(GcmConstants.REGISTRATION_COMPLETE));
            isReceiverRegistered = true;
        }
    }

    // -------------------------------------------------
    public void loadWelcomeSequence() {

        TutorialItem tutorialItem1 = new TutorialItem("Do Stuff", "Text",
                R.color.themeDarkGreen, R.drawable.tut_page_1_front, R.drawable.tut_page_1_background);

        TutorialItem tutorialItem2 = new TutorialItem("Do more stuff", "more text",
                R.color.themeDarkYellow, R.drawable.tut_page_2_front, R.drawable.tut_page_2_background);

        TutorialItem tutorialItem3 = new TutorialItem("Do even more stuff", "Persevere my friend, the end is in sight!",
                R.color.themeLightGreen, R.drawable.tut_page_3_foreground);

        ArrayList<TutorialItem> tutorialItems = new ArrayList<>();
        tutorialItems.add(tutorialItem1);
        tutorialItems.add(tutorialItem2);
        tutorialItems.add(tutorialItem3);

        Intent mainAct = new Intent(this, MaterialTutorialActivity.class);
        mainAct.putParcelableArrayListExtra(MaterialTutorialActivity.MATERIAL_TUTORIAL_ARG_TUTORIAL_ITEMS, tutorialItems);
        startActivityForResult(mainAct, WELCOME_SEQUENCE_REQUEST_CODE);
    }


    // Check for google play services
    // -------------------------------------------------
    private boolean googlePlayServicesIsValid() {
        GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
        int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);

        if (resultCode != ConnectionResult.SUCCESS) {
            if (apiAvailability.isUserResolvableError(resultCode)) {
                apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
                        .show();
            } else {
                Log.i("GCM", "This device is not supported.");
                finish();
            }
            return false;
        }
        return true;
    }


    // -------------------------------------------------
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //Done with welcome screen sequence
        if (resultCode == RESULT_OK && requestCode == WELCOME_SEQUENCE_REQUEST_CODE) {
            //Launch account picker
            Intent intent = AccountPicker.newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null, null, null, null);
            startActivityForResult(intent, ACCOUNT_PICKER_REQUEST_CODE);

            //Successfully picked a user account to use, store it for future reference
        } else if (resultCode == RESULT_OK && requestCode == ACCOUNT_PICKER_REQUEST_CODE) {
            String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            SharedPreferences.Editor editor;
            editor = prefs.edit();
            editor.putString("googleAccount", accountName);
            editor.apply();
            new LookupCloudUserProfile(this).execute();

            //No play services installed, panic
        } else if (resultCode == RESULT_CANCELED && requestCode == PLAY_SERVICES_RESOLUTION_REQUEST) {
            Toast.makeText(this, "Google Play Services must be installed.", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    //Handle permission request to access image gallery
    // -------------------------------------------------
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        if (fragments != null) {
            for (Fragment fragment : fragments) {
                fragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
            }
        }
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.