简体   繁体   中英

How to store the GCM push notification message into sqlite database using new GCM API?

I am new to android and programming also and working on GCM new API. Everything is working fine and I have implemented the GCM successfully . But I need to save the message into a database table. But when I implemented the below database manipulation code, the GCM stopped working as well as database.

 public class GCMNotificationIntentService extends IntentService {

public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder; 
DBHelper db;

public GCMNotificationIntentService() {
    super("GcmIntentService");
//   db= new DBHelper(this.getBaseContext());
}

public static final String TAG = "GCMNotificationIntentService";

@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) {
        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
                .equals(messageType)) {
            sendNotification("Send error: " + extras.toString());
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
                .equals(messageType)) {
            sendNotification("Deleted messages on server: "
                    + extras.toString());
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
                .equals(messageType)) {

            for (int i = 0; i < 3; i++) {
                Log.i(TAG,
                        "Working... " + (i + 1) + "/5 @ "
                                + SystemClock.elapsedRealtime());
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                }

            }
            Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());

            String eid =  extras.get(Config.EVENT_ID).toString();
            String loc =  extras.get(Config.LOCATION).toString();
            String mag =  extras.get(Config.MAGNITUDE).toString();
            String lat =  extras.get(Config.LATITUDE).toString();
            String lon =  extras.get(Config.LONGITUDE).toString();
            String time = extras.get(Config.ORIGINE_TIME).toString();


                db.insertEventInfo(eid,loc,mag,lat,lon,time);

            sendNotification("["+mag+"]"+" "+loc+" "+time);

            Log.i(TAG, "Received: " + extras.toString());
        }
    }
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}

private void sendNotification(String msg) {
    Log.d(TAG, "Preparing to send notification...: " + msg);
    mNotificationManager = (NotificationManager) this
            .getSystemService(Context.NOTIFICATION_SERVICE);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, EarthquakeListActivity.class), 0);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            this).setSmallIcon(R.drawable.gcm_cloud)
            .setContentTitle("ITEWC Notification")
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
            .setContentText(msg);

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    Log.d(TAG, "Notification sent successfully.");
  }

}

And DBHelper Class is

public class DBHelper extends SQLiteOpenHelper{

public SQLiteDatabase db;
public String DBPath;   
public static final int version = 1;
public static Context currentContext;

public static  String DATABASE_NAME = "EarthquakeList";
public static  String EARTHQUAKE_TABLE_NAME="earthquakes";
public static  String EARTHQUAKE_ID = "eventId";
public static  String EARTHQUAKE_LOCATION = "location";
public static  String EARTHQUAKE_ORIGIN_TIME = "originTime";
public static  String EARTHQUAKE_LATITUDE = "latitude";
public static  String EARTHQUAKE_LONGITUDE = "longitude";
public static  String EARTHQUAKE_MAGNITUDE = "magnitude";   

static final String TAG = "DBHelper";

public DBHelper(Context context) {
super(context, DATABASE_NAME, null, version);
}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL(
              "CREATE TABLE IF NOT EXISTS earthquakes  (eventId  VARCHAR ,location VARCHAR , originTime VARCHAR , latitude VARCHAR ,longitude VARCHAR , magnitude VARCHAR)"
              );

    Log.d("DBHelper", "Database Created ");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
     db.execSQL("DROP TABLE IF EXISTS earthquakes");
      onCreate(db);

}

 public void insertEventInfo  (String eventId, String location, String originTime, String latitude,String longitude, String magnitude){


      SQLiteDatabase db = this.getWritableDatabase();         

      ContentValues values = new ContentValues();
      values.put(EARTHQUAKE_ID, eventId);
      values.put(EARTHQUAKE_LOCATION, location);
      values.put(EARTHQUAKE_ORIGIN_TIME, originTime);
      values.put(EARTHQUAKE_LATITUDE, latitude);
      values.put(EARTHQUAKE_LONGITUDE,longitude );
      values.put(EARTHQUAKE_MAGNITUDE, magnitude);

      db.insert(EARTHQUAKE_TABLE_NAME, null, values);


      Log.d("DBHelper", "in Insert Method ");
      db.close();        
    }   
}

You must Initialise your DBHelper class.

db= new DBHelper(this);

I will suggest you must use library for database handling like sugar ORM here is link http://satyan.github.io/sugar/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM