user4780686
user4780686

Reputation:

Android WebView With Firebase Cloud Messaging

I currently have an Android application that loads my website inside a WebView.

WebView browserView;
browserView.loadUrl(URL);

I have also implemented Firebase Cloud Messaging so I can utilize push notifications.

public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService {
    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();

        // Send the token to the server
        sendRegistrationToServer(refreshedToken);
    }

    private void sendRegistrationToServer(String refreshedToken) {
        try {
            URL url = new URL(URL + "/API.php");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");

            conn.setDoOutput(true);
            conn.setDoInput(true);
            DataOutputStream wr = new DataOutputStream(
                    conn.getOutputStream());
            wr.writeBytes("action=insertDeviceID&deviceID=" + refreshedToken);
            wr.flush();
            wr.close();

            InputStream is = conn.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            is.close();
            rd.close();
        } catch(Exception e) {}
    }
}

When sendRegistrationToServer() is run my API populates a table with the ID of the current Android device. Here is a picture:

enter image description here

The problem is that I have no way of getting the user_id until the person has logged in to the website via the Android WebView. As you can probably guess, this means I do not know which device is associated with which user. This is a problem for sending push notifications to certain users.

Does anybody know a solution to this problem?

Note: I have already debated making a native Android application and do not want to do that. I also have thought of simply loading the website in a native web browser like Chrome or Firefox, however, I also do not want to do that.

Thoughts: Could it be possible to "trigger" a function in the Android application when a user logs in on the website and pass the user_id?

More thoughts: Can I accomplish this using WebView's addJavascriptInterface()?

Upvotes: 5

Views: 3053

Answers (1)

user4780686
user4780686

Reputation:

Solved it using my solution in the comments. I used the function addJavascriptInterface() which is part of the Android WebView class. By using it I was able to call back to my Android application after I log in to the website. I then call my API and pass the user id and device id.

Upvotes: 1

Related Questions