Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/firebase sync service #6

Merged
merged 3 commits into from
Nov 30, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@ dependencies {
annotationProcessor "androidx.room:room-compiler:2.2.1"
implementation "androidx.lifecycle:lifecycle-extensions:2.1.0"

// WorkManager Library
implementation ("androidx.work:work-runtime:2.2.0") {
exclude group: 'com.google.guava', module: 'listenablefuture'
}
implementation 'com.google.guava:guava:27.0.1-android'


// Networking libraries
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.amitshekhar.android:android-networking:1.0.2'
Expand Down
5 changes: 4 additions & 1 deletion app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,17 @@

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

<application
android:name=".ChatBotApp"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:usesCleartextTraffic="true"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true"
tools:ignore="GoogleAppIndexingWarning">
<activity android:name=".ui.chat.ChatActivity" />
<activity android:name=".ui.login.LoginActivity" />
Expand All @@ -31,6 +32,8 @@
<activity
android:name=".ui.registration.RegistrationActivity"
android:windowSoftInputMode="adjustResize" />

<service android:name=".intentservice.FireBaseIntentService" />
</application>

</manifest>
31 changes: 31 additions & 0 deletions app/src/main/java/com/fazemeright/chatbotmetcs622/ChatBotApp.java
Original file line number Diff line number Diff line change
@@ -1,19 +1,50 @@
package com.fazemeright.chatbotmetcs622;

import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;

import androidx.work.Constraints;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;

import com.fazemeright.chatbotmetcs622.network.NetworkManager;
import com.fazemeright.chatbotmetcs622.workers.FireBaseSyncWorker;

import java.util.concurrent.TimeUnit;

import timber.log.Timber;

public class ChatBotApp extends Application {

public static final String CHANNEL_ID = "FireBaseSyncChannel";

@Override
public void onCreate() {
super.onCreate();
if (BuildConfig.DEBUG) {
Timber.plant(new Timber.DebugTree());
}
NetworkManager.getInstance().init(getApplicationContext(), 300);

createNotificationChannel();
}

/**
* Call to create a notification channel for OS greater than OREO
*/
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"FireBase Sync channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
if (manager != null) {
manager.createNotificationChannel(serviceChannel);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,18 @@
import androidx.room.Entity;
import androidx.room.PrimaryKey;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
* POJO for a message
*/
@Entity(tableName = "my_messages_table")
public class Message {
public class Message implements Serializable {
public static final String SENDER_USER = "User";
/**
* mid of message
Expand Down Expand Up @@ -52,6 +55,17 @@ public static Message newMessage(String msg, String sender, String receiver, lon
return new Message(0, msg, sender, receiver, chatRoomId, System.currentTimeMillis());
}

public static Map<String, Object> getHashMap(Message message) {
Map<String, Object> messageHashMap = new HashMap<>();
messageHashMap.put("mid", message.getMid());
messageHashMap.put("msg", message.getMsg());
messageHashMap.put("sender", message.getSender());
messageHashMap.put("receiver", message.getReceiver());
messageHashMap.put("chatRoomId", message.getChatRoomId());
messageHashMap.put("timestamp", message.getTimestamp());
return messageHashMap;
}

public long getMid() {
return mid;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package com.fazemeright.chatbotmetcs622.database.messages;

import androidx.room.Dao;
import androidx.room.FtsOptions;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;

import com.fazemeright.chatbotmetcs622.database.BaseDao;
Expand All @@ -24,4 +27,10 @@ public interface MessageDao extends BaseDao<Message> {

@Query("DELETE from my_messages_table WHERE chatRoomId = :chatRoomId")
void clearChatRoomMessages(long chatRoomId);

@Query("SELECT * FROM my_messages_table WHERE chatRoomId = :chatRoomId ORDER BY timestamp DESC LIMIT 1")
Message getLatestMessage(long chatRoomId);

@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAllMessages(List<Message> order);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
package com.fazemeright.chatbotmetcs622.intentservice;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Intent;
import android.os.Build;
import android.os.PowerManager;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.fazemeright.chatbotmetcs622.ChatBotApp;
import com.fazemeright.chatbotmetcs622.R;
import com.fazemeright.chatbotmetcs622.database.ChatBotDatabase;
import com.fazemeright.chatbotmetcs622.database.messages.Message;
import com.fazemeright.chatbotmetcs622.repositories.MessageRepository;
import com.fazemeright.firebase_api_library.api.FireBaseApiManager;
import com.fazemeright.firebase_api_library.listeners.DBValueListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import timber.log.Timber;

public class FireBaseIntentService extends IntentService {

public static final String ACTION_ADD_MESSAGE = "AddMessage";
public static final String ACTION_SYNC_MESSAGES = "SyncMessages";
/**
* TAG for logs
*/
private static final String TAG = "FireBaseIntentService";
/**
* Use to send data with intent
*/
public static final String ACTION = "IntentAction";
public static final String MESSAGE = "Message";
public static final String RESULT_RECEIVER = "ResultReceiver";

protected ChatBotDatabase database;
private PowerManager.WakeLock wakeLock;
private FireBaseApiManager fireBaseApiManager;
private MessageRepository messageRepository;

/**
* Creates an IntentService. Invoked by your subclass's constructor.
* <p>
* TAG Used to name the worker thread, important only for debugging.
*/
public FireBaseIntentService() {
super(TAG);
}

@Override
public void onCreate() {
super.onCreate();
Timber.i("onCreate");
database = ChatBotDatabase.getInstance(getApplicationContext());
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ChatBot:WakeLockTag");
wakeLock.acquire(60 * 1000); // acquire CPU
Timber.i("onCreate: Wake Lock acquired");
}
showForegroundServiceNotification("Chat Bot", "Syncing Messages...");
}

@Override
public void onDestroy() {
super.onDestroy();
Timber.i("onDestroy");
wakeLock.release();
Timber.i("onDestroy: Wake Lock released");

}

@Override
protected void onHandleIntent(@Nullable Intent intent) {
Timber.d("onHandleIntent");
if (intent != null) {
switch (intent.getStringExtra(ACTION)) {
case ACTION_ADD_MESSAGE:
addMessageToFireStore((Message) intent.getSerializableExtra(MESSAGE));
break;
case ACTION_SYNC_MESSAGES:
syncMessages();
break;
}
}

}

/**
* Call to sync messages from FireStore to Room for the logged in user
*/
private void syncMessages() {
try {
Thread.sleep(5000); // intentionally kept delay to show in presentation TODO: Remove afterwards
} catch (InterruptedException e) {
e.printStackTrace();
}
messageRepository.syncMessagesFromFireStoreToRoom();
}

/**
* Call to add given message to FireStore
*
* @param message given message
*/
private void addMessageToFireStore(Message message) {
messageRepository.addMessageToFireBase(Message.getHashMap(message));
}

/**
* Call to display foreground running notification to notify user of a background operation running
*
* @param title title to display in notification
* @param text text to display in notification
*/
private void showForegroundServiceNotification(String title, String text) {
Timber.i("Show notification called");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

Notification notification = new NotificationCompat.Builder(this, ChatBotApp.CHANNEL_ID)
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setPriority(NotificationManager.IMPORTANCE_DEFAULT)
.build();

startForeground(1, notification);
}
}

@Override
public void onStart(@Nullable Intent intent, int startId) {
super.onStart(intent, startId);
fireBaseApiManager = FireBaseApiManager.getInstance();
messageRepository = MessageRepository.getInstance(getApplicationContext());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ class DatabaseUrl {
}

class BaseUrl {
final static String BASE_URL = "http://192.168.0.24:8080";
final static String BASE_URL = "http://192.168.0.29:8080";
final static String BASE_APP_NAME = "/MET_CS622_ChatBot_Backend_war_exploded";
final static String BASE_HI = "/hi";
}
Expand Down
Loading