Friday, 31 May 2019

How to start socket.io like foreground service to stay connected and listen for messages

I am using this source app to chat with other devices. But how to make it to start like a Service so I can to start foreground service. Do I need MainFragment and LoginActivity rewrite in Service?

socket.io app socket.io-android-chat

I have tried something like that in class SocketService, what other I need to include in Service for App to get notification messages even if app is closed.

public class SocketService extends Service {
    private Socket mSocket;
    public static final String TAG = SocketService.class.getSimpleName();
    private static final String NOTIFICATION_CHANNEL_ID_DEFAULT = "App running in background";
    String GROUP_KEY_WORK_EMAIL = "com.android.example.WORK_EMAIL";
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this, "on created", Toast.LENGTH_SHORT).show();

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setGroup(GROUP_KEY_WORK_EMAIL);
        Notification notification = builder.build();
        NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
        // Set big text style.
        builder.setStyle(bigTextStyle);
        startForeground(3, notification);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "start command", Toast.LENGTH_SHORT).show();
        try {
            mSocket = IO.socket(Constants.CHAT_SERVER_URL);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        mSocket.on("newMessageReceived", onNewMessage);
        mSocket.connect();
        return START_STICKY;
    }

    private Emitter.Listener onNewMessage = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            JSONObject data = (JSONObject) args[0];
            String username;
            String message;
            try {
                username = data.getString("username");
                message = data.getString("message");
            } catch (JSONException e) {
                Log.e(TAG, e.getMessage());
                return;
            }

            Log.d(TAG, "call: new message ");
            setNotificationMessage(message, username);
        }
    };

    public void setNotificationMessage(CharSequence message, CharSequence title) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.drawable.ic_launcher);
        builder.setContentTitle(title);
        builder.setContentText(message);
        NotificationManagerCompat nm = NotificationManagerCompat.from(this);
        nm.notify(3, builder.build());
    }
}




from How to start socket.io like foreground service to stay connected and listen for messages

What does mean key value pair inside the square brackets []?

Lets consider following is my object,

var n = {"aa":"x","dd":'d'};

I am using square bracket in Object.assign it gives the following result. [aa: "x", dd: "d"]. The final code is

var n = {"aa":"x","dd":'d'};
var m = Object.assign([],n);

// result is 
[aa: "x", dd: "d"]

in the console.log __proto__ tells this is Array, if it is array following code giving the, unexpected token error

var v = ["sss":"ddd","ccc":"ddd"]; 

What does mean?

enter image description here



from What does mean key value pair inside the square brackets []?

How do you read data from firestore?

I'm trying to learn how to use firestore.

The google documentation says to try this format:

db.collection("users").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        console.log(`${doc.id} => ${doc.data()}`);
    });
});

So, I used that to do this (changing the db to fsDB and "users" to "newsletters"

fsDB.collection("newsletters").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        console.log(`${doc.id} => ${doc.data()}`);
    });
});

When I try this, I get an error that says querySnapshot is not defined. Screen shot of error message is attached.

enter image description here

I've seen this post and tried its suggestion as follows:

fsDB.collection("newsletters").query.get().then(function(querySnapshot) { 

                            if (querySnapshot.empty) { 
                                console.log('no documents found');
                            } else {
                                    querySnapshot.docs.map(function (documentSnapshot) {
                                        console.log(documentSnapshot.data().name); 
                                    });
                            }

                        });

This attempt generates a parsing error with the if statement, but I can't find a way to solve that either.

This must have a simple solution, but I can't figure out how to get a record from the database.

NEXT ATTEMPT

I tried moving the code above the return statement and putting in inside a variable as follows shown in the attached screen shot, but it still produces errors as shown. These errors are the same regardless of whether i keep or lose the brackets around querySnapshot.

enter image description here5]5



from How do you read data from firestore?