添加启动画面时,Webview URL无法通过FCM更新

时间:2019-07-13 14:31:28

标签: java android firebase-cloud-messaging

我跟随this tutorial制作了一个简单的Webview应用程序,该应用程序可通过键和Firebase Notification中的值更新Webview的URL,该Webview会加载静态URL,但还会加载指定的新URL在FCM通知的值中

onNewIntent(getIntent());mRegistrationBroadcastReceiver获取意图,该意图包含密钥webURL和值https://www.newurl.com/存储在STR_KEY中。

一切正常,当应用程序在后台和前景时,URL会完美更新...直到我在应用程序中添加启动画面,在这种情况下,当应用程序在后台并且FCM通知到达时, webview的网址不会更新,但是在前台时会更新。

我的最佳猜测是Intent intent = new Intent(getBaseContext(), MainActivity.class);丢失了,因为初始屏幕而不是Main活动加载了,但是我是一个菜鸟,这超出了我拥有的3个神经元。

这是我的清单:

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

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

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

我的FCM服务:

import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.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);
    }
}

我的MainActivity:

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 个答案:

答案 0 :(得分:1)

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

本文可能对您有帮助-creating splashscreen the right way

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

答案 1 :(得分:0)

    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));

    }

}