有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

添加启动屏幕时,java webview URL未通过FCM更新

我按照this tutorial制作了一个简单的webview应用程序,其中webview的url可以从一个键和一个Firebase通知的值更新,webview加载一个静态url,但也加载FCM通知值中指定的新url

onNewIntent(getIntent());从包含键:webURL和存储在STR_KEY中的值:https://www.newurl.com/mRegistrationBroadcastReceiver获取意图

一切正常,当应用程序位于后台和前台时,url会完美更新。。。在我在应用程序中添加启动屏幕之前,在本例中,当应用程序位于后台且FCM通知到达时,webview的url不会更新,但在前台时会更新

我最好的猜测是Intent intent = new Intent(getBaseContext(), MainActivity.class);丢失了,因为启动屏幕首先加载,而不是主要活动,但我是一个noob,这超出了我拥有的3个神经元

这是我的舱单:

<application
    安卓:allowBackup="true"
    安卓:icon="@mipmap/ic_launcher"
    安卓:label="@string/app_name"
    安卓:roundIcon="@mipmap/ic_launcher_round"
    安卓:supportsRtl="true"
    安卓:theme="@style/AppTheme">
    <activity 安卓:name=".Splash">
        <intent-filter>
            <action 安卓:name="安卓.intent.action.MAIN" />

            <category 安卓:name="安卓.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity 安卓:name=".MainActivity"></activity>

    <service 安卓:name=".MyService">
        <intent-filter>
            <action 安卓:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
</application>

我的FCM服务:

import 安卓.content.Intent;
import 安卓.support.v4.content.LocalBroadcastManager;
import 安卓.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class MyService extends FirebaseMessagingService {

    public static final String STR_KEY = "webURL";
    public static final String STR_PUSH = "pushNotification";
    public static final String STR_MESSAGE = "message";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        handleMessage(remoteMessage.getData().get(STR_KEY));
    }

    private void handleMessage(String message) {
        Intent pushNotification = new Intent(STR_PUSH);
        pushNotification.putExtra(STR_MESSAGE, message);

    LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
    }

    @Override
    public void onNewToken(String token) {
        super.onNewToken(token);
        sendRegistrationToServer(token);
    }

    private void sendRegistrationToServer(String token) {
        Log.d("new Token", token);
    }
}

我的主要活动:

public class MainActivity extends AppCompatActivity {

    WebView webView;

    private BroadcastReceiver mRegistrationBroadcastReceiver;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        webView = findViewById(R.id.webView);
        webView.getSettings().setPluginState(WebSettings.PluginState.OFF);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setUserAgentString("Android Mozilla/5.0 
        AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30");
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAllowContentAccess(true);
        webView.getSettings().supportZoom();
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("https://www.mywebsite.com/");

        mRegistrationBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(STR_PUSH)) {
                    String message = intent.getStringExtra(STR_MESSAGE);
                    showNotification("New URL", message);
                }
            }
        };

        onNewIntent(getIntent());

    }

    @Override
    protected void onNewIntent(Intent intent) {
            webView.loadUrl(intent.getStringExtra(STR_KEY));
    }

    private void showNotification(String title, String message) {
        Intent intent = new Intent(getBaseContext(), MainActivity.class);
        intent.putExtra(STR_KEY, message);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent contentIntent = PendingIntent.getActivity(getBaseContext(), 0, 
                intent, PendingIntent.FLAG_UPDATE_CURRENT);

        Notification.Builder builder = new Notification.Builder(getBaseContext());
        builder.setAutoCancel(true)
                .setWhen(System.currentTimeMillis())
                .setDefaults(Notification.DEFAULT_ALL)
                .setSmallIcon(R.mipmap.ic_launcher_round)
                .setContentTitle(title)
                .setContentText(message)
                .setContentIntent(contentIntent);
        NotificationManager notificationManager = (NotificationManager)
        getBaseContext().getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = getString(R.string.normal_channel_id);
            String channelName = getString(R.string.normal_channel_name);
            NotificationChannel channel = new NotificationChannel(channelId, 
        channelName, NotificationManager.IMPORTANCE_DEFAULT);
        channel.enableVibration(true);
        channel.setVibrationPattern(new long[]{100, 200, 200, 50});
        if (notificationManager != null) {
            notificationManager.createNotificationChannel(channel);
        }

        builder.setChannelId(channelId);
    }

    if (notificationManager !=null) {
        notificationManager.notify("", 0, builder.build());
    }
}

    @Override
    protected void onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver
        (mRegistrationBroadcastReceiver);
        super.onPause();
}

    @Override
    protected void onResume() {
        super.onResume();
        LocalBroadcastManager.getInstance(this).registerReceiver
        (mRegistrationBroadcastReceiver, new IntentFilter("registrationComplete"));
        LocalBroadcastManager.getInstance(this).registerReceiver
        (mRegistrationBroadcastReceiver, new IntentFilter(STR_PUSH));
    }
}

还有我的闪屏:

public class Splash extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        int SPLASH_TIME_OUT = 4000;
        new Handler().postDelayed(() -> {
            Intent homeIntent = new Intent(Splash.this, MainActivity.class);
            startActivity(homeIntent);
            finish();
        }, SPLASH_TIME_OUT);
    }
}

共 (2) 个答案

  1. # 1 楼答案

    我认为您应该在不使用布局文件的情况下实现启动屏幕,因为从专用启动屏幕活动启动第二个活动会有延迟

    这篇文章可能会有所帮助

    这样,启动屏幕将仅在应用程序处于加载状态时显示。因此,即使应用程序在后台运行,它也可以防止您的问题

  2. # 2 楼答案

        public class MainActivity extends AppCompatActivity {
    
        private WebView webView;
        private ProgressDialog dialog;
    
        private BroadcastReceiver mRegistrationBroadcastReceiver;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            webView = (WebView) findViewById(R.id.webView);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.loadUrl("https://www.gsmarena.com/samsung_galaxy_note20-10338.php");
            webView.setWebChromeClient(new WebChromeClient() {
                @Override
                public void onPermissionRequest(final PermissionRequest request) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        request.grant(request.getResources());
                    }
    //                super.onPermissionRequest(request);
                }
            });
            webView.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url) {
                    if (dialog.isShowing())
                        dialog.dismiss();
                }
            });
    
            mRegistrationBroadcastReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    if (intent.getAction().equals(Config.STR_PUSH)) {
                        String message = intent.getStringExtra(Config.STR_MESSAGE);
                        showNotification("this is a notification", message);
                    }
                }
            };
    
            onNewIntent(getIntent());
    
        }
    
        @SuppressLint("MissingSuperCall")
        @Override
        protected void onNewIntent(Intent intent) {
            dialog = new ProgressDialog(this);
    
            if (intent.getStringExtra(Config.STR_KEY) != null) {
                dialog.show();
                dialog.setMessage("Please wait loading");
                webView.loadUrl(intent.getStringExtra(Config.STR_KEY));
            }
        }
    
        private void showNotification(String title, String message) {
    //        Intent intent = new Intent(getBaseContext(), MainActivity.class);
            Intent intent = new Intent(this, MainActivity.class);
    //        intent.setAction(Intent.ACTION_MAIN);
    //        intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.putExtra(Config.STR_KEY, message);
    //        intent.setFlags(intent.FLAG_ACTIVITY_SINGLE_TOP);
            intent.setFlags(intent.FLAG_ACTIVITY_NEW_TASK | intent.FLAG_ACTIVITY_SINGLE_TOP | intent.FLAG_ACTIVITY_CLEAR_TOP);
    //        PendingIntent contentIntent = PendingIntent.getActivity(getBaseContext(),0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
            PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
    
    //        NotificationCompat.Builder builder = new NotificationCompat.Builder(getBaseContext());
            Notification.Builder builder = new Notification.Builder(this);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                builder.setAutoCancel(true)
                        .setWhen(System.currentTimeMillis())
                        .setDefaults(Notification.DEFAULT_ALL)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle(title)
                        .setContentText(message)
                        .setContentIntent(contentIntent)
                        .setPriority(Notification.PRIORITY_HIGH)
                        .setVibrate(new long[]{100, 200, 200, 50})
                        .setColor(Color.rgb(247, 133, 39))
                        .setVisibility(Notification.VISIBILITY_PUBLIC)
                        .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
            }
    
    //        NotificationManager notificationManager = (NotificationManager)getBaseContext().getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                String channelId = "ChannelID";
                String channelName = "ChannelName";
                NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
                channel.enableLights(true);
                channel.setLightColor(Color.RED);
                channel.enableVibration(true);
                channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
                channel.setShowBadge(true);
                channel.setVibrationPattern(new long[]{100, 200, 200, 50});
                if (notificationManager != null) {
                    notificationManager.createNotificationChannel(channel);
                }
                builder.setChannelId(channelId);
            }
    
            if (notificationManager != null) {
                notificationManager.notify("", 0, builder.build());
            }
    
    //        notificationManager.notify(1, builder.build());
        }
    
    
        @Override
        protected void onPause() {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
            super.onPause();
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, new IntentFilter("registrationComplete"));
            LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, new IntentFilter(Config.STR_PUSH));
    
        }
    
    }