Skip to content

Commit

Permalink
Notifications release. See changelog for info
Browse files Browse the repository at this point in the history
  • Loading branch information
eagskunst committed Nov 3, 2018
1 parent 724074b commit 12d55ad
Show file tree
Hide file tree
Showing 12 changed files with 160 additions and 65 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ See changelog and develop branch for not-official features.

# Changelog

**-3/11/2018/:**
Hopefully this is the last version that will run on the playstore. You would receive notifications from topics you choose with this build.
Fixed a bug that when activity is destroyed on backgroud and night mode is active, MainActivity background was white instead of gray.
TODO: Add a clean list button in TopicListFragment

**-31/10/2018:**
Manage your topics layouts finished.
Make communication with FirebaseRealtimeDatabase in order to save user prefered topics.
Expand Down
4 changes: 2 additions & 2 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ android {
applicationId "com.eagskunst.emmanuel.gamingnews"
minSdkVersion 16
targetSdkVersion 26
versionCode 3
versionName "1.1"
versionCode 4
versionName "1.2"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
}
Expand Down
Binary file added app/release/release/app.aab
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,19 @@
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.SwitchPreference;
import android.util.Log;
import android.widget.ListView;


import com.eagskunst.emmanuel.gamingnews.R;
import com.eagskunst.emmanuel.gamingnews.Utility.SharedPreferencesLoader;
import com.eagskunst.emmanuel.gamingnews.views.MainActivity;
import com.eagskunst.emmanuel.gamingnews.views.SettingsActivity;
import com.google.firebase.messaging.FirebaseMessaging;


public class SettingsFragment extends PreferenceFragment {
Expand All @@ -43,8 +41,9 @@ public void onCreate(Bundle savedInstanceState) {
nightmodePreference.setOnPreferenceClickListener(preferenceClickListener("night_mode",nightmodePreference.isChecked()));
SwitchPreference disableImagesPreference = (SwitchPreference) findPreference("pref_loadimages");
disableImagesPreference.setOnPreferenceClickListener(preferenceClickListener("load_images",disableImagesPreference.isChecked()));
CheckBoxPreference dailyReminderPreference = (CheckBoxPreference) findPreference("pref_dailynotf");
dailyReminderPreference.setOnPreferenceClickListener(preferenceClickListener("daily_notf",dailyReminderPreference.isChecked()));
Preference manageTopics = findPreference("pref_managetopics");

manageTopics.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
Expand All @@ -70,15 +69,31 @@ private Preference.OnPreferenceClickListener preferenceClickListener(final Strin
return new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
if(isChecked)
sharedPreferences.edit().putBoolean(prefKey,false).apply();
else
sharedPreferences.edit().putBoolean(prefKey,true).apply();
if(prefKey.equals("night_mode"))
reloadApp();
else if(prefKey.equals("load_images")){
SharedPreferencesLoader.setCanLoadImages(sharedPreferences);
if(prefKey.equals("daily_notf")){
boolean daily_notf = sharedPreferences.getBoolean(prefKey,false);
if(!daily_notf){
Log.d(this.getClass().getSimpleName(), "onPreferenceClick: subscribed");
FirebaseMessaging.getInstance().subscribeToTopic("all");
sharedPreferences.edit().putBoolean(prefKey,true).commit();
}
else{
Log.d(this.getClass().getSimpleName(), "onPreferenceClick: unsubscribed");
FirebaseMessaging.getInstance().unsubscribeFromTopic("all");
sharedPreferences.edit().putBoolean(prefKey,false).commit();
}
}
else{
if(isChecked)
sharedPreferences.edit().putBoolean(prefKey,false).apply();
else
sharedPreferences.edit().putBoolean(prefKey,true).apply();
if(prefKey.equals("night_mode"))
reloadApp();
else if(prefKey.equals("load_images")){
SharedPreferencesLoader.setCanLoadImages(sharedPreferences);
}
}

return true;
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.eagskunst.emmanuel.gamingnews.R;
import com.eagskunst.emmanuel.gamingnews.Utility.SharedPreferencesLoader;
Expand Down Expand Up @@ -108,10 +109,15 @@ public boolean onOptionsItemSelected(MenuItem item) {
*/
case android.R.id.home:
if (getActivity().getFragmentManager().getBackStackEntryCount() >= 1) {
addTopicsToFirebase();
subscribeToTopics();
SharedPreferencesLoader.saveTopics(sharedPreferences.edit(),topicList);
getFragmentManager().popBackStack();
try{
addTopicsToFirebase();
subscribeToTopics();
SharedPreferencesLoader.saveTopics(sharedPreferences.edit(),topicList);
getFragmentManager().popBackStack();
}catch (IllegalArgumentException e){
Toast.makeText(getActivity(),R.string.ilegalargumentfirebase,Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
return true;
}/*
Providing topic addition
Expand Down Expand Up @@ -149,10 +155,23 @@ public void onClick(DialogInterface dialogInterface, int i) {
}
else if(!editText.getText().toString().isEmpty()){
topicList.set(position,editText.getText().toString());
if(!text.equalsIgnoreCase(editText.getText().toString())){
try{
FirebaseMessaging.getInstance().unsubscribeFromTopic(text.replace(" ","_").toUpperCase());
}catch(IllegalArgumentException e){
Toast.makeText(getActivity(),R.string.ilegalargumentfirebase,Toast.LENGTH_SHORT);
e.printStackTrace();
}
}
}
else{
topicList.remove(position);
FirebaseMessaging.getInstance().unsubscribeFromTopic(text.replace(" ","_"));
try{
FirebaseMessaging.getInstance().unsubscribeFromTopic(text.replace(" ","_").toUpperCase());
}catch(IllegalArgumentException e){
Toast.makeText(getActivity(),R.string.ilegalargumentfirebase,Toast.LENGTH_SHORT);
e.printStackTrace();
}
}
topicsAdapter.notifyDataSetChanged();
dialogInterface.dismiss();
Expand All @@ -165,17 +184,16 @@ else if(!editText.getText().toString().isEmpty()){
private void addTopicsToFirebase(){
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
database.child("topics").child(SharedPreferencesLoader.getFirebaseToken(sharedPreferences)).removeValue();
database.child("topics").child(SharedPreferencesLoader.getFirebaseToken(sharedPreferences))
.child("lang").setValue(Locale.getDefault().getLanguage());
DatabaseReference userReference = database.child("topics")
.child(SharedPreferencesLoader.getFirebaseToken(sharedPreferences)).child("subscribedList");
for(int i = 0;i<topicList.size();i++){
database.child("topics").child(SharedPreferencesLoader.getFirebaseToken(sharedPreferences))
.child("topic"+i).setValue(topicList.get(i).replace(" ","_"));
userReference.child(Integer.toString(i)).setValue(topicList.get(i).replace(" ","_").toUpperCase());
}
}

private void subscribeToTopics(){
for(String topic:topicList){
FirebaseMessaging.getInstance().subscribeToTopic(topic.replace(" ","_"));
FirebaseMessaging.getInstance().subscribeToTopic(topic.replace(" ","_").toUpperCase());
}
}

Expand All @@ -201,12 +219,12 @@ public void onButtonPressed(Uri uri) {
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
/*if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}*/
}

@Override
Expand All @@ -225,10 +243,16 @@ public void onDetach() {
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy");
addTopicsToFirebase();
subscribeToTopics();
SharedPreferencesLoader.saveTopics(sharedPreferences.edit(),topicList);
getFragmentManager().popBackStack();
try{
addTopicsToFirebase();
subscribeToTopics();
SharedPreferencesLoader.saveTopics(sharedPreferences.edit(),topicList);
getFragmentManager().popBackStack();
}catch (IllegalArgumentException e){
Toast.makeText(getActivity(),R.string.ilegalargumentfirebase,Toast.LENGTH_SHORT).show();
e.printStackTrace();
}

}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@
import com.google.firebase.iid.InstanceIdResult;
import com.google.firebase.messaging.FirebaseMessaging;

import java.util.Calendar;
import java.util.TimeZone;

public class BaseActivity extends AppCompatActivity {

private SharedPreferences sharedPreferences;
Expand All @@ -40,10 +43,18 @@ protected void onCreate(@Nullable Bundle savedInstanceState) {
@Override
protected void onDestroy() {
super.onDestroy();
/* Code for knowing user last session
DatabaseReference presenceRef = FirebaseDatabase.getInstance().getReference("disconnectmessage");
presenceRef.onDisconnect().setValue(ServerValue.TIMESTAMP);
*/
SharedPreferencesLoader.saveCurrentTime(getUserSharedPreferences().edit());
}

@Override
protected void onResume() {
super.onResume();
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
try{
manager.cancelAll();
}catch (NullPointerException e){
e.printStackTrace();
}
}

protected void showToolbar(Toolbar toolbar, int title, boolean upButton, ProgressBar progressBar) {
Expand All @@ -61,9 +72,10 @@ protected void showToolbar(Toolbar toolbar, int title, boolean upButton, Progres
protected void setFirebaseToken(){
if(isPlayServicesAvailable()){
callLog(getClass().getSimpleName(),"Play services available!");
NotificationMaker nm = new NotificationMaker(sharedPreferences);
NotificationMaker nm = new NotificationMaker();
nm.sharedPreferences = sharedPreferences;
nm.setToken();
FirebaseMessaging.getInstance().subscribeToTopic("all"); //TODO: Add this line in Settings Fragment

}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.app.NotificationCompat;
Expand All @@ -13,19 +14,22 @@
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
import java.util.concurrent.TimeUnit;


public class NotificationMaker extends FirebaseMessagingService {
private final String TAG = getClass().getSimpleName();
private String sessionToken;
private SharedPreferences sharedPreferences;

public NotificationMaker(SharedPreferences sharedPreferences) {
this.sharedPreferences = sharedPreferences;
}
public SharedPreferences sharedPreferences;

@Override
public void onNewToken(String s) {
Expand All @@ -37,31 +41,36 @@ public void onNewToken(String s) {
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d(TAG,"Message: "+remoteMessage);
generateNotification(remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());
generateNotification(remoteMessage.getData().get("title"),remoteMessage.getData().get("descp"),
remoteMessage.getData().get("lang"));
}

private void generateNotification(String title, String body) {

Intent pendingIntent = new Intent(this, MainActivity.class);
pendingIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

PendingIntent notifyPendingIntent =
PendingIntent.getActivity(
this,
99,
pendingIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
private void generateNotification(String title, String body, String lang) {
Log.d(TAG, "Lang: "+lang);
if(lang.equals(Locale.getDefault().getLanguage())){
Random r = new Random();
Intent pendingIntent = new Intent(this, MainActivity.class);
pendingIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
int requestCode = r.nextInt((100-1)+1)+1;
PendingIntent notifyPendingIntent =
PendingIntent.getActivity(
this,
requestCode,
pendingIntent,
0
);

Notification notification = new NotificationCompat.Builder(this,"0")
.setContentTitle(title)
.setContentText(body)
.setContentIntent(notifyPendingIntent)
.setSmallIcon(R.mipmap.ic_launcher)
.build();
Notification notification = new NotificationCompat.Builder(this,"0")
.setContentTitle(title)
.setContentText(body)
.setContentIntent(notifyPendingIntent)
.setColor(getResources().getColor(R.color.colorPrimary))
.setSmallIcon(R.drawable.ic_all)
.build();

NotificationManagerCompat manager = NotificationManagerCompat.from(getApplicationContext());
manager.notify(0,notification);
NotificationManagerCompat manager = NotificationManagerCompat.from(getApplicationContext());
manager.notify(requestCode,notification);
}
}

public void setToken() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

public class SharedPreferencesLoader {
public static boolean canLoadImages = true;
Expand Down Expand Up @@ -75,4 +79,15 @@ public static String getFirebaseToken(SharedPreferences sharedPreferences){
return sharedPreferences.getString("USER_TOKEN","no_play_services");
}

public static void saveCurrentTime(SharedPreferences.Editor spEditor){
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
String session = formatter.format(date);
spEditor.putString("LAST_SESSION",session);
}

public static String getLastSession(SharedPreferences sharedPreferences){
return sharedPreferences.getString("LAST_SESSION",null);
}

}
Loading

0 comments on commit 12d55ad

Please sign in to comment.