dimanche 19 juin 2016

Saving notifications data into sqlite

I am building an app where I am using Firebase Cloud Messaging. And I want to, when notification data comes, to save that message in SQLite. And that works but only when app is in the foreground. The reason why is that so is that I wrote logic for inserting messaging into SQLite in Override method OnMessageReceived. And, as we know that method is called only when app is in the foreground. But I want to save notification to the SQLite even when app is in the background. So, my question is: where to call this method insertMsg to become able to save notifications which comes when app is in the background?

Here is myFirebaseMessagingService:

public class myFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG="MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    Log.d("onMessageReceived", "Pozvana funkcija onMessageReceived");
    Log.d(TAG, "From " + remoteMessage.getFrom());
    Log.d(TAG, "Body " + remoteMessage.getNotification().getBody());
    Log.d(TAG, "Location " + remoteMessage.getNotification().getClickAction());
    Log.d(TAG, "Value " + remoteMessage.getData().get("click_action"));
    sendNotification(remoteMessage);
    Log.d("Function called", "sendNotification");

}

private void sendNotification(RemoteMessage remoteMessage) {
    Intent intent = new Intent(myFirebaseMessagingService.this, MainActivity.class);
    intent.putExtra("click_action", "goToFragment1");
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notification=new NotificationCompat.Builder(this)
            .setSmallIcon(logo)
            .setContentText(remoteMessage.getNotification().getBody())
            .setContentTitle("Title")
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);
    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, notification.build());
    String message=remoteMessage.getNotification().getBody();
    DataBaseHelper db=new DataBaseHelper(this);
    db.insertMsg(message);

}

Here is my DataBaseHelper:

public class DataBaseHelper extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "bazaFire.db";
private static final String TABLE_NAME = "Messages";
private static final String COLUMN_NAME="message_body";
SQLiteDatabase myDB;
public DataBaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL("CREATE TABLE " + TABLE_NAME
            + "(id INTEGER PRIMARY KEY AUTOINCREMENT, message_body TEXT)");

}

@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);

}
public void insertMsg(String msg) {

    try{
    SQLiteDatabase db = getWritableDatabase();


    ContentValues cv = new ContentValues();

    cv.put(COLUMN_NAME, msg);


    db.insert(TABLE_NAME, null, cv);
        Log.d("Ubacena poruka", "Poruka je : " + msg + "A tabela je : " + TABLE_NAME);

    db.close();}

    catch (Exception e){
        throw new Error("Error!");
    }

}
public Cursor getAlldata(){
    SQLiteDatabase db=this.getWritableDatabase();
    Cursor res=db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
    return res;
}
}

And here is my MainActivity:

public class MainActivity extends AppCompatActivity {
Button dugme, dugme2, dugmeBaza, dugmeToken;
DataBaseHelper db;
Cursor c;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d("onCreate", "ONCREATE");
    db=new DataBaseHelper(this);
    final Intent intent=getIntent();
    setContentView(R.layout.activity_main);
    String msg = getIntent().getStringExtra("click_action");
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();


    if (msg != null) {
        if (msg.equals("goToFragment1")) {
            Fragment1 fragment1 = new Fragment1();
            fragmentTransaction.replace(R.id.myFragment, fragment1);
            Log.d("FragmentTransaction", "Fragment je promenjen u onCreate!");
            fragmentTransaction.commit();
            Log.d("Create", "Kraj onCreatea");
        }
    }

    dugme = (Button) findViewById(R.id.dugme1);
    dugme2 = (Button) findViewById(R.id.subscribe);
    dugme.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Fragment fragment = null;
            if (view == dugme) {
                fragment = new Fragment1();
            }
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.myFragment, fragment);
            transaction.addToBackStack(null);
            transaction.setTransition(FragmentTransaction.TRANSIT_NONE);
            transaction.commit();
        }
    });


    dugme2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            FirebaseMessaging.getInstance().subscribeToTopic("android");
            Log.d("Log", "Uspesno ste se pretplatili");
        }
    });
    dugmeBaza=(Button)findViewById(R.id.dugmeZabazu);
    viewAll();
    dugmeToken=(Button)findViewById(R.id.TokenButton);
    dugmeToken.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.d("Token je:", "Token: " + FirebaseInstanceId.getInstance().getToken());

        }
    })



@Override
protected void onResume() {
    super.onResume();
    Log.d("onResume", "Resume");
    Intent intent = new Intent();
    String msg = getIntent().getStringExtra("action");
    Log.d("msg", "msg");
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    Log.d("FragmentTransaction", "FragmentTransaction success!");
    if (msg != null)
    {
        if (msg.equals("goToFragment1")) {
            Fragment1 fragment1 = new Fragment1();
            fragmentTransaction.replace(R.id.myFragment, fragment1);
            Log.d("FragmentTransaction", "Fragment je promenjen!");
            fragmentTransaction.commit();
            Log.d("onResume", "Kraj resuma");
        }
    }
}
@Override
protected void onPause() {
    super.onPause();  // Always call the superclass method first

    Log.d("onPause", "Pauza");
}
public void viewAll(){

    dugmeBaza.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           Cursor res= db.getAlldata();
            if(res.getCount()==0) {
                //show message
                showMessage("Error", "Nothing found");


                return;

            }
            StringBuffer buffer=new StringBuffer();
            while (res.moveToNext()){
                buffer.append("Id: " + res.getString(0) + "n");
                buffer.append("poruka: " + res.getString(1));

            }
            showMessage("Data", buffer.toString());
        }
    });
}
public void showMessage(String title, String message){
    AlertDialog.Builder builder=new AlertDialog.Builder(this);
    builder.setCancelable(true);
    builder.setTitle(title);
    builder.setMessage(message);
    builder.show();
}

And this is my manifest:

 <application
    android:allowBackup="true"
    android:icon="@drawable/logo"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
            <intent-filter>
                <action android:name="goToFragment1" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>


    </activity>

    <service android:name=".myFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
    <service
        android:name=".myFirebaseInstanceServiceID">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>

</application>

Aucun commentaire:

Enregistrer un commentaire