Совместное использование входа между веб-просмотром действий и веб-просмотром службы в Android - PullRequest
0 голосов
/ 21 июня 2020

У меня есть клиент веб-просмотра для моего веб-приложения. Он используется для просмотра пользователем сайта. Теперь я хочу, чтобы другой веб-просмотр был запущен в службе, чтобы получать уведомления для пользователя, которые затем отображаются как уведомления pu sh.

Теперь проблема в том, что мой MainActivity webView работает нормально, и когда я залогинился все работает. Но в моем веб-просмотре службы я вижу в консоли, что я не вошел в систему! Поэтому я не могу получить новые уведомления с сервера.

Мои исследования показали, что на самом деле приложение Session per Android используется всеми веб-просмотрами. Поэтому, когда я вошел в систему в webview, AI также должен войти в систему в webview B. Но это не так.

Как я могу решить эту проблему?

Мой код:

//MainActivity
package com.danielbrendel.bodypositivity;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.danielbrendel.bodypositivityuncovered.PushService;

import java.io.File;

import static android.app.Notification.DEFAULT_LIGHTS;
import static android.app.Notification.DEFAULT_SOUND;
import static android.app.Notification.DEFAULT_VIBRATE;

public class MainActivity extends AppCompatActivity {
    private WebView webView;
    private ValueCallback<Uri> mUploadMessage;
    public ValueCallback<Uri[]> uploadMessage;
    public static final int REQUEST_SELECT_FILE = 100;
    private final static int FILECHOOSER_RESULTCODE = 1;
    public static MainActivity instance = null;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.instance = this;

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.webView = (WebView)findViewById(R.id.webview);
        this.webView.getSettings().setJavaScriptEnabled(true);
        this.webView.getSettings().setSupportZoom(true);
        this.webView.getSettings().setAllowFileAccess(true);

        JavaScriptInterface javaScriptInterface = new JavaScriptInterface();
        webView.addJavascriptInterface(javaScriptInterface, "native");

        startService(new Intent(this, PushService.class));

        this.webView.loadUrl("https://my-site.net/clep/index?clep_push_handler=androidNotificationHandler");

        this.webView.setWebViewClient(new WebViewClient() {
            public void onPageFinished(WebView view, String url) {
                webView.loadUrl("javascript:window.androidNotificationHandler = function(shortMsg, longMsg) { window.native.handlePushNotification(shortMsg, longMsg); };");
                CookieSyncManager.getInstance().sync();
            }

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            public boolean shouldOverrideUrlLoading (WebView view,
                                                     WebResourceRequest request)
            {
                if (!request.getUrl().toString().contains("clep_push_handler=androidNotificationHandler")) {
                    if (request.getUrl().toString().contains("?")) {
                        view.loadUrl(request.getUrl().toString() + "&clep_push_handler=androidNotificationHandler");
                    } else {
                        view.loadUrl(request.getUrl().toString() + "?clep_push_handler=androidNotificationHandler");
                    }
                    return true;
                }

                return false;
            }
        });
        webView.setWebChromeClient(new WebChromeClient() {

            // For 3.0+ Devices (Start)
            // onActivityResult attached before constructor
            protected void openFileChooser(ValueCallback uploadMsg, String acceptType)
            {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
            }


            // For Lollipop 5.0+ Devices
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
            {
                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                }

                uploadMessage = filePathCallback;

                Intent intent = fileChooserParams.createIntent();
                try
                {
                    startActivityForResult(intent, REQUEST_SELECT_FILE);
                } catch (ActivityNotFoundException e)
                {
                    uploadMessage = null;
                    return false;
                }
                return true;
            }

            //For Android 4.1 only
            protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
            {
                mUploadMessage = uploadMsg;
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE);
            }

            protected void openFileChooser(ValueCallback<Uri> uploadMsg)
            {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
            }
        });   // End setWebChromeClient
    }

    public View viewById(int id)
    {
        return findViewById(id);
    }

    public String getStringById(int id)
    {
        return getString(id);
    }

    public Object getSysService(String name)
    {
        return getSystemService(name);
    }

    @Override
    public void onBackPressed() {
        if (this.webView.canGoBack()) {
            this.webView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {


        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        {
            if (requestCode == REQUEST_SELECT_FILE)
            {
                if (uploadMessage == null)
                    return;
                uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
                uploadMessage = null;
            }
        }
        else if (requestCode == FILECHOOSER_RESULTCODE)
        {
            if (null == mUploadMessage)
                return;
            // Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment
            // Use RESULT_OK only if you're implementing WebView inside an Activity
            Uri result = intent == null || resultCode != MainActivity.RESULT_OK ? null : intent.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        } else {
            super.onActivityResult(requestCode, resultCode, intent);
        }
    }
}

class JavaScriptInterface {
    private static final String CHANNEL_ID = "BodyPositivity";

    public JavaScriptInterface()
    {
        this.createNotificationChannel();
    }

    private void createNotificationChannel() {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "Body Positivity";
            String description = "Body Positivity Push Channel";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = MainActivity.instance.getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

    @JavascriptInterface
    public void handlePushNotification(String shortMsg, String longMsg)
    {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.instance, CHANNEL_ID)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(shortMsg)
                .setContentText(longMsg)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setDefaults(DEFAULT_SOUND | DEFAULT_VIBRATE | DEFAULT_LIGHTS);
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(MainActivity.instance);
        notificationManager.notify(PushService.notificationId, builder.build());
        PushService.notificationId++;
    }
}
//PushService
package com.danielbrendel.bodypositivityuncovered;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.webkit.ConsoleMessage;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import com.danielbrendel.bodypositivity.MainActivity;
import com.danielbrendel.bodypositivity.R;

import static android.app.Notification.DEFAULT_LIGHTS;
import static android.app.Notification.DEFAULT_SOUND;
import static android.app.Notification.DEFAULT_VIBRATE;

public class PushService extends Service {
    WebView webView = null;
    Handler handler = null;
    public static int notificationId = 0;

    public PushService()
    {
    }

    @SuppressLint("ResourceType")
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        webView = new WebView(this);
        webView.getSettings().setJavaScriptEnabled(true);

        JavaScriptInterface javaScriptInterface = new JavaScriptInterface();
        webView.addJavascriptInterface(javaScriptInterface, "service");

        webView.setWebViewClient(new WebViewClient() {
            public void onPageFinished(WebView view, String url) {
                webView.loadUrl("javascript:window.androidNotificationHandler = function(shortMsg, longMsg) { window.service.handlePushNotification(shortMsg, longMsg); };");
                webView.loadUrl("javascript:fetchNotifications();");
            }
        });

        handler = new Handler();

        final Runnable r = new Runnable() {
            public void run() {
                webView.loadUrl("https://www.my-site.net/feed?clep_push_handler=androidNotificationHandler");

                handler.postDelayed(this, 95000);
            }
        };

        handler.postDelayed(r, 15000);

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

class JavaScriptInterface {
    private static final String CHANNEL_ID = "BodyPositivityService";

    public JavaScriptInterface()
    {
        this.createNotificationChannel();
    }

    private void createNotificationChannel() {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "Body Positivity Service";
            String description = "Body Positivity Service Push Channel";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = MainActivity.instance.getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

    @JavascriptInterface
    public void handlePushNotification(String shortMsg, String longMsg)
    {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.instance, CHANNEL_ID)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(shortMsg)
                .setContentText(longMsg)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setDefaults(DEFAULT_SOUND | DEFAULT_VIBRATE | DEFAULT_LIGHTS);
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(MainActivity.instance);
        notificationManager.notify(PushService.notificationId, builder.build());
        PushService.notificationId++;
    }
}
...