You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio WebView应用:通知弹窗与加载进度条实现求助

Hey there! Let's tackle your two Android dev issues step by step—since you're new to this, I'll break everything down with exact code snippets and where to put them.

1. Open OneSignal Notifications in a Separate Window

To make notifications open in a new window (instead of your main Activity), we'll create a dedicated Activity for notification content and configure OneSignal to launch it when a notification is tapped.

Step 1: Create the Notification WebView Activity

Create a new Java class named NotificationWebViewActivity.java in your package (same folder as MainActivity.java):

package com.example.rijvan.awebaddress;

import android.content.Intent;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.appcompat.app.AppCompatActivity;

public class NotificationWebViewActivity extends AppCompatActivity {
    private WebView notificationWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification_webview);

        notificationWebView = findViewById(R.id.notification_webview);
        WebSettings webSettings = notificationWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        // Get the URL passed from the notification (adjust if your payload uses a different key)
        String url = getIntent().getStringExtra("notification_url");
        // Fallback to your main website if no URL is provided
        if (url == null || url.isEmpty()) {
            url = "https://my web site/";
        }

        notificationWebView.loadUrl(url);
        notificationWebView.setWebViewClient(new WebViewClient());
    }

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

Step 2: Create the Layout for the Notification Activity

Create a new layout file activity_notification_webview.xml in res/layout/:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".NotificationWebViewActivity">

    <WebView
        android:id="@+id/notification_webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</android.support.constraint.ConstraintLayout>

Step 3: Register the New Activity in AndroidManifest.xml

Add this <activity> tag inside the <application> section of your AndroidManifest.xml:

<activity android:name=".NotificationWebViewActivity"
          android:launchMode="standard"
          android:theme="@style/AppTheme"/>

The standard launch mode ensures each notification tap opens a new instance of this Activity (true "separate window" behavior).

Step 4: Update OneSignal Initialization in MainActivity.java

Modify your OneSignal setup in the onCreate method to handle notification clicks:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    // OneSignal setup with notification click handler
    OneSignal.startInit(this)
        .inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
        .unsubscribeWhenNotificationsAreDisabled(true)
        .setNotificationOpenedHandler(new OneSignal.NotificationOpenedHandler() {
            @Override
            public void notificationOpened(OSNotificationOpenResult result) {
                // Extract the URL from the notification's additional data
                String url = result.notification.payload.additionalData.optString("url", "");
                
                // Launch the new Notification Activity
                Intent intent = new Intent(MainActivity.this, NotificationWebViewActivity.class);
                intent.putExtra("notification_url", url);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        })
        .init();

    setContentView(R.layout.activity_main);
    // Rest of your existing onCreate code...
}

Note: When sending notifications via OneSignal, make sure to include a url key in the "Additional Data" section of your notification payload. If you don't include it, the Activity will fall back to your main website URL.


2. Add a Loading Progress Bar to WebView

We'll add a progress bar that shows while your WebView loads content, then hides when loading is complete.

Step 1: Update activity_main.xml

Modify your existing layout to include a ProgressBar above the WebView:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <!-- Progress Bar -->
    <ProgressBar
        android:id="@+id/loading_progress"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="4dp"
        android:visibility="gone"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

    <!-- WebView -->
    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintTop_toBottomOf="@id/loading_progress"/>

</android.support.constraint.ConstraintLayout>

Step 2: Update MainActivity.java to Track Loading Progress

Add code to initialize the ProgressBar and use a WebChromeClient to update its progress:

package com.example.rijvan.awebaddress;

// Don't forget to import these!
import android.view.View;
import android.widget.ProgressBar;
import android.content.Intent;
import com.onesignal.OSNotificationOpenResult;
import com.onesignal.OneSignal;
import android.webkit.WebChromeClient;

public class MainActivity extends AppCompatActivity {
    public WebView mywebView;
    private ProgressBar loadingProgress; // Add this variable

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // OneSignal setup (from Step 4 above) goes here...
        
        setContentView(R.layout.activity_main);
        
        // Initialize ProgressBar
        loadingProgress = findViewById(R.id.loading_progress);
        
        mywebView = findViewById(R.id.webview);
        android.webkit.WebSettings webSettings = mywebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        
        // Set WebChromeClient to track loading progress
        mywebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                loadingProgress.setProgress(newProgress);
                
                // Show progress bar when loading starts, hide when complete
                if (newProgress == 100) {
                    loadingProgress.setVisibility(View.GONE);
                } else {
                    loadingProgress.setVisibility(View.VISIBLE);
                }
            }
        });
        
        mywebView.loadUrl("https://my web site/");
        mywebView.setWebViewClient(new android.webkit.WebViewClient());
    }

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

That's it! Both changes should work smoothly with your existing setup. Let me know if you run into any snags—happy to help you troubleshoot further.

内容的提问来源于stack exchange,提问作者Rizvan Rahman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:44:07