Android Open Source - LearnByHeart Base Activity






From Project

Back to project page LearnByHeart.

License

The source code is released under:

Apache License

If you think the Android project LearnByHeart listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.mps.learn.pb.ui.factivities;
/* w  ww . j a  v a 2s .  c o  m*/
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

import android.app.Activity;
import android.app.AlarmManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.mps.learn.pb.R;
import com.mps.learn.pb.util.CommonConstants;

public class BaseActivity extends Activity {

  protected AlarmManager mAlaramManager;
  
  /**
     * Tag used on log messages.
     */
    private final String TAG = BaseActivity.class.getSimpleName();
    
  GoogleCloudMessaging gcm;
    AtomicInteger msgId = new AtomicInteger();
    Context context;

    String regid;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getActionBar() != null) getActionBar().setDisplayHomeAsUpEnabled(true);
        
        mAlaramManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        
        context = getApplicationContext();

        // Check device for Play Services APK. If check succeeds, proceed with GCM registration.
        if (checkPlayServices()) {
            gcm = GoogleCloudMessaging.getInstance(this);
            regid = getRegistrationId(context);
            
            Log.i(TAG, "regid: " + regid );

            if (regid.isEmpty()) {
                registerInBackground();
            }
        } else {
            Log.i(TAG, "No valid Google Play Services APK found.");
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        // Check device for Play Services APK.
        checkPlayServices();
    }

    /**
     * Check the device to make sure it has the Google Play Services APK. If
     * it doesn't, display a dialog that allows users to download the APK from
     * the Google Play Store or enable it in the device's system settings.
     */
    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                        CommonConstants.GCMConstants.PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Log.i(TAG, "This device is not supported.");
                finish();
            }
            return false;
        }
        return true;
    }

    /**
     * Stores the registration ID and the app versionCode in the application's
     * {@code SharedPreferences}.
     *
     * @param context application's context.
     * @param regId registration ID
     */
    private void storeRegistrationId(Context context, String regId) {
        final SharedPreferences prefs = getGcmPreferences(context);
        int appVersion = getAppVersion(context);
        Log.i(TAG, "Saving regId on app version " + appVersion);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(CommonConstants.GCMConstants.PROPERTY_REG_ID, regId);
        editor.putInt(CommonConstants.GCMConstants.PROPERTY_APP_VERSION, appVersion);
        editor.commit();
    }

    /**
     * Gets the current registration ID for application on GCM service, if there is one.
     * <p>
     * If result is empty, the app needs to register.
     *
     * @return registration ID, or empty string if there is no existing
     *         registration ID.
     */
    private String getRegistrationId(Context context) {
        final SharedPreferences prefs = getGcmPreferences(context);
        String registrationId = prefs.getString(CommonConstants.GCMConstants.PROPERTY_REG_ID, "");
        if (registrationId.isEmpty()) {
            Log.i(TAG, "Registration not found.");
            return "";
        }
        // Check if app was updated; if so, it must clear the registration ID
        // since the existing regID is not guaranteed to work with the new
        // app version.
        int registeredVersion = prefs.getInt(CommonConstants.GCMConstants.PROPERTY_APP_VERSION, Integer.MIN_VALUE);
        int currentVersion = getAppVersion(context);
        if (registeredVersion != currentVersion) {
            Log.i(TAG, "App version changed.");
            return "";
        }
        return registrationId;
    }

    /**
     * Registers the application with GCM servers asynchronously.
     * <p>
     * Stores the registration ID and the app versionCode in the application's
     * shared preferences.
     */
    private void registerInBackground() {
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                String msg = "";
                try {
                    if (gcm == null) {
                        gcm = GoogleCloudMessaging.getInstance(context);
                    }
                    regid = gcm.register(CommonConstants.GCMConstants.SENDER_ID);
                    msg = "Device registered, registration ID=" + regid;

                    // You should send the registration ID to your server over HTTP, so it
                    // can use GCM/HTTP or CCS to send messages to your app.
                    sendRegistrationIdToBackend();

                    // For this demo: we don't need to send it because the device will send
                    // upstream messages to a server that echo back the message using the
                    // 'from' address in the message.

                    // Persist the regID - no need to register again.
                    storeRegistrationId(context, regid);
                } catch (IOException ex) {
                    msg = "Error :" + ex.getMessage();
                    // If there is an error, don't just keep trying to register.
                    // Require the user to click a button again, or perform
                    // exponential back-off.
                }
                return msg;
            }

            @Override
            protected void onPostExecute(String msg) {
              Log.i(TAG,msg );
            }
        }.execute(null, null, null);
    }

    // Send an upstream message.
    public void sendMessage() {
        {
            new AsyncTask<Void, Void, String>() {
                @Override
                protected String doInBackground(Void... params) {
                    String msg = "";
                    try {
                        Bundle data = new Bundle();
                        data.putString("my_message", "Hello World");
                        data.putString("my_action", "com.google.android.gcm.demo.app.ECHO_NOW");
                        String id = Integer.toString(msgId.incrementAndGet());
                        gcm.send(CommonConstants.GCMConstants.SENDER_ID + "@gcm.googleapis.com", id, data);
                        msg = "Sent message";
                    } catch (IOException ex) {
                        msg = "Error :" + ex.getMessage();
                    }
                    return msg;
                }

                @Override
                protected void onPostExecute(String msg) {
                    Log.i(TAG,msg );
                }
            }.execute(null, null, null);
        }  
    }

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

    /**
     * @return Application's version code from the {@code PackageManager}.
     */
    private static int getAppVersion(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (NameNotFoundException e) {
            // should never happen
            throw new RuntimeException("Could not get package name: " + e);
        }
    }

    /**
     * @return Application's {@code SharedPreferences}.
     */
    private SharedPreferences getGcmPreferences(Context context) {
        // This sample app persists the registration ID in shared preferences, but
        // how you store the regID in your app is up to you.
        return getSharedPreferences(BaseActivity.class.getSimpleName(),
                Context.MODE_PRIVATE);
    }
    /**
     * Sends the registration ID to your server over HTTP, so it can use GCM/HTTP or CCS to send
     * messages to your app. Not needed for this demo since the device sends upstream messages
     * to a server that echoes back the message using the 'from' address in the message.
     */
    private void sendRegistrationIdToBackend() {
      // Your implementation here.
    }
}




Java Source Code List

com.mps.learn.pb.App.java
com.mps.learn.pb.PhraseManager.java
com.mps.learn.pb.adapter.AllPhraseAdapter.java
com.mps.learn.pb.alarm.ReminderReceiver.java
com.mps.learn.pb.alarm.ReminderUtil.java
com.mps.learn.pb.db.DataSourcePhrase.java
com.mps.learn.pb.db.DatabaseHelper.java
com.mps.learn.pb.db.PhraseReaderContract.java
com.mps.learn.pb.gcm.GcmBroadcastReceiver.java
com.mps.learn.pb.gcm.GcmIntentService.java
com.mps.learn.pb.http.DataUpdaterCallback.java
com.mps.learn.pb.http.DataUpdaterTask.java
com.mps.learn.pb.http.HttpConstant.java
com.mps.learn.pb.http.PhraseParser.java
com.mps.learn.pb.model.PhraseBook.java
com.mps.learn.pb.model.PhraseModel.java
com.mps.learn.pb.ui.activities.AddPhraseActivity.java
com.mps.learn.pb.ui.activities.MainActivity.java
com.mps.learn.pb.ui.activities.PhraseViewActivity.java
com.mps.learn.pb.ui.activities.SettingActivity.java
com.mps.learn.pb.ui.factivities.BaseActivity.java
com.mps.learn.pb.ui.factivities.FActivity.java
com.mps.learn.pb.ui.factivities.FoldableListActivity.java
com.mps.learn.pb.ui.factivities.ItemsAdapter.java
com.mps.learn.pb.ui.factivities.PaintingsAdapter.java
com.mps.learn.pb.ui.factivities.SpannableBuilder.java
com.mps.learn.pb.ui.factivities.UnfoldableDetailsActivity.java
com.mps.learn.pb.ui.views.FoldableItemLayout.java
com.mps.learn.pb.ui.views.FoldableListLayout.java
com.mps.learn.pb.ui.views.UnfoldableView.java
com.mps.learn.pb.ui.views.shading.FoldShading.java
com.mps.learn.pb.ui.views.shading.GlanceFoldShading.java
com.mps.learn.pb.ui.views.shading.SimpleFoldShading.java
com.mps.learn.pb.util.CommonConstants.java
com.mps.learn.pb.util.Debugger.java