Reputation: 7348
Here we are making an app using Firebase Relatime Database. When our app open for the first time it tries to connect to firebase database which takes a lot to time. And after that first connection it is really fast. I want to know how to establish the connection fast for the first time?
Upvotes: 2
Views: 1514
Reputation: 7348
In this we can use SERVICE long running background task to solve first time slow connection ISSUE.
/**
* Created by bipin on 1/18/17.
*/
public class FirstConnectionService extends Service {
public static DatabaseReference databaseReference;
private static String TAG = FirstConnectionService.class.getSimpleName();
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
getDriverStatus();
return START_STICKY;
}
/**
* long running background task using services
*/
private void getDriverStatus() {
try {
databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl(
Constants.FIREBASE_DRIVER + "/" + 100 + "/status");
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
AppUtils.showLog(TAG, "onDataChange");
}
@Override
public void onCancelled(DatabaseError databaseError) {
AppUtils.showLog(TAG, "onCancelled");
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
And Start the service by checking if it is already running.
/**
* First check if service is already running.
*/
if (!ServiceUtils.isMyServiceRunning(FirstConnectionService.class, this)) {
AppUtils.showLog("FirstConnectionService", "isMyServiceRunning: false");
startService(new Intent(this, FirstConnectionService.class));
} else {
AppUtils.showLog("FirstConnectionService", "isMyServiceRunning: true");
}
Service Utils
/**
* Created by bipin on 1/18/17.
*/
public class ServiceUtils {
/**
* Check if service is already running in background
* */
public static boolean isMyServiceRunning(Class<?> serviceClass, Context context) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
Upvotes: 1