Introduction
Smart WebView (SWV) is an open-source Android project that enhances the capabilities of the standard Android WebView. It allows you to create hybrid applications by combining the flexibility of web technologies with the power of native Android features.
Getting Started
To integrate Smart WebView into your Android project, follow these steps:
Installation
- Add the following dependency to your app-level
build.gradle
file: - Add the Google Services plugin to your
build.gradle
file: - Include the necessary Firebase dependencies in your app-level
build.gradle
: - Add the `google-services.json` file (downloaded from the Firebase console) to your app module directory.
dependencies {
implementation 'com.github.mgks:Android-SmartWebView:7.0' // Replace with latest version if available
}
plugins {
// ... other plugins
id 'com.google.gms.google-services'
}
dependencies {
// ... other dependencies
implementation platform('com.google.firebase:firebase-bom:32.7.2') // Use latest version
implementation 'com.google.firebase:firebase-messaging'
}
Basic Usage
In your `MainActivity.java`, initialize the `SmartWebView` object and load your desired URL:
public class MainActivity extends AppCompatActivity {
// ...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SmartWebView.asw_view = findViewById(R.id.smartWebView);
// Configure Smart WebView (optional)
SmartWebView.ASWV_URL = "your_url_here"; // Set your starting URL here
// ... other SmartWebView configurations ...
// Initialize Smart WebView
WebSettings webSettings = SmartWebView.asw_view.getSettings();
// ... set your WebSettings ...
// Set the WebViewClient
SmartWebView.asw_view.setWebViewClient(new SmartWebViewClient());
// Load the URL
SmartWebView.asw_view.loadUrl(SmartWebView.ASWV_URL);
}
// ...
}
Features
Smart WebView offers a wide range of features to enhance your hybrid application:
File Uploads and Camera Access
Allow users to upload files from their device or capture images/videos using the camera within the WebView.
Configuration:
ASWP_FUPLOAD
: Enable/disable file uploads (`true` by default).ASWP_CAMUPLOAD
: Enable/disable camera uploads (`true` by default).ASWV_F_TYPE
: Allowed file types (e.g., "*⁄*", "image/⁄*", "video/⁄*").
Permissions:
Manifest.permission.CAMERA
Manifest.permission.READ_EXTERNAL_STORAGE
(for API levels below 33)Manifest.permission.WRITE_EXTERNAL_STORAGE
(for API levels below 29)Manifest.permission.READ_MEDIA_IMAGES
(for API levels 33 and above)Manifest.permission.READ_MEDIA_VIDEO
(for API levels 33 and above)
Geolocation
Access the user's location using the device's GPS or network location.
Configuration:
ASWP_LOCATION
: Enable/disable geolocation (`true` by default).
Permissions:
Manifest.permission.ACCESS_FINE_LOCATION
Manifest.permission.ACCESS_COARSE_LOCATION
Push Notifications
Integrate with Firebase Cloud Messaging (FCM) to send push notifications to your app.
Configuration:
See the Firebase section for details on setting up FCM.
Permissions:
Manifest.permission.POST_NOTIFICATIONS
(for API levels 33 and above)
Custom URL Handling
Override specific URLs to trigger native actions or handle them within your app.
Configuration:
Plugins can define custom URL schemes that they will handle. For example, the `PlugQRReader` plugin handles URLs starting with `qrscan://start`.
JavaScript Interface
Communicate between JavaScript code running in the WebView and your native Android code.
Refer to the Android documentation for more details on implementing a JavaScript interface.
Configuration
Smart WebView can be configured using a set of static variables in the `SmartWebView` class. Here are some of the key configuration options:
Variable | Description | Default Value |
---|---|---|
ASWV_URL |
The URL to load when the app starts. | "your_url_here" |
ASWP_FUPLOAD |
Enable file uploads. | true |
ASWP_CAMUPLOAD |
Enable camera uploads. | true |
ASWV_F_TYPE |
Allowed file types for uploads (e.g., "*⁄*", "image/⁄*", "video/⁄*"). | "*⁄*" |
ASWP_LOCATION |
Enable geolocation access. | true |
ASWP_RATINGS |
Enable the app rating prompt. | true |
ASWP_PULLFRESH |
Enable pull-to-refresh functionality. | true |
ASWP_PBAR |
Enable the progress bar. | true |
ASWP_ZOOM |
Enable zoom controls. | false |
ASWP_SFORM |
Enable save form data. | false |
ASWP_OFFLINE |
Enable offline mode. | false |
ASWP_EXTURL |
Open external URLs in a separate browser. | true |
ASWP_TAB |
Open external URLs in Chrome Custom Tabs. | true |
ASWP_ADMOB |
Enable AdMob ads. | false |
ASWP_EXITDIAL |
Show an exit confirmation dialog. | true |
You can set these variables in your `MainActivity.java` before initializing the `SmartWebView` object.
Configuration Options
Here's a more detailed explanation of each configuration option:
Add detailed explanations of each configuration option here.
Permissions
Smart WebView requests the following permissions at runtime if the corresponding features are enabled:
Manifest.permission.ACCESS_FINE_LOCATION
(ifASWP_LOCATION
is `true`)Manifest.permission.CAMERA
(ifASWP_CAMUPLOAD
is `true`)Manifest.permission.READ_EXTERNAL_STORAGE
(if targeting below Android 13 andASWP_FUPLOAD
is `true`)Manifest.permission.WRITE_EXTERNAL_STORAGE
(if targeting below Android 10 andASWP_FUPLOAD
is `true`)Manifest.permission.READ_MEDIA_IMAGES
(if targeting Android 13 and above andASWP_FUPLOAD
is `true`)Manifest.permission.READ_MEDIA_VIDEO
(if targeting Android 13 and above andASWP_FUPLOAD
is `true`)Manifest.permission.POST_NOTIFICATIONS
(if using Firebase Cloud Messaging on Android 13 and above)
Plugins
Smart WebView supports a plugin architecture that allows you to extend its functionality without modifying the core library code. To create a plugin, you need to implement the `PluginInterface` interface:
public interface PluginInterface {
void initialize(PluginManager pluginManager, Activity activity, WebView webView);
String getPluginName();
String[] getOverriddenUrls();
void handlePermissionRequest(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults);
void handleActivityResult(int requestCode, int resultCode, Intent data);
boolean shouldOverrideUrlLoading(WebView view, String url); // Added for handling custom URLs
void onPageStarted(String url); // Added for page start event
void onPageFinished(String url); // Added for page finish event
}
Plugin Interface
The `PluginInterface` defines the following methods:
initialize()
: Called when the plugin is initialized.getPluginName()
: Returns the name of the plugin.getOverriddenUrls()
: Returns an array of URLs that the plugin wants to handle.handlePermissionRequest()
: Called when a permission request result is received.handleActivityResult()
: Called when an activity result is received.shouldOverrideUrlLoading()
: Called to determine if the plugin should handle a specific URL.onPageStarted()
: Called when a new page starts loading in the WebView.onPageFinished()
: Called when a page finishes loading in the WebView.
Example Plugin (QR Code Reader)
The `PlugQRReader` is an example plugin that demonstrates how to implement a QR code reader using the ZXing library.
Code Example:
public class PlugQRReader implements PluginInterface {
// ... implementation details ...
@Override
public void onPageFinished(String url) {
// Inject JavaScript to add a button for QR scanning
if (url.contains("scanqr")) {
String js = "javascript:" +
"var button = document.createElement('button');" +
"button.innerHTML = 'Scan QR Code';" +
"button.onclick = function() { window.location.href = 'qrscan://start'; };" +
"document.body.appendChild(button);";
webView.evaluateJavascript(js, null);
} else {
// Inject JavaScript to remove button from the page
String js = "javascript:" +
"var button = document.querySelector('button[data-qr-button=\"true\"]);" +
"if (button) { button.remove(); }";
webView.evaluateJavascript(js, null);
}
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
if (url.startsWith("qrscan://start")) {
startQRScanning();
return true; // Indicate that this plugin handled the URL
}
return false; // URL not handled by this plugin
}
// ... other methods for handling permissions, scanning, etc. ...
}
To register a plugin, add it to the `plugins` map in the `PluginManager` class:
public class PluginManager {
// ...
private void registerPlugins() {
try {
plugins.put("PlugQRReader", new PlugQRReader(this));
// Add other plugins as needed
} catch (Exception e) {
Log.e(TAG, "Failed to load plugins", e);
}
for (PluginInterface plugin : plugins.values()) {
plugin.initialize(activity, webView);
}
}
// ...
}
Firebase Cloud Messaging
Smart WebView provides built-in support for Firebase Cloud Messaging (FCM). To enable FCM, follow these steps:
- Add the Firebase dependencies to your app-level
build.gradle
file. - Add the `google-services.json` file to your app module directory.
- Implement the `FirebaseMessagingService` class to handle incoming messages and token refreshes.
Refer to the Firebase documentation for more details on integrating FCM into your Android app.
Troubleshooting
If you encounter any issues with Smart WebView, here are some common troubleshooting steps:
- Check the Logcat output for error messages.
- Ensure that you have requested the necessary permissions.
- Verify that your `build.gradle` file contains the correct dependencies.
- Make sure your HTML, CSS, and JavaScript code is free of errors.
- If you are using a JavaScript interface, ensure that it is implemented correctly.
- If you are using plugins, make sure they are registered properly with the `PluginManager`.
- Consult the Smart WebView documentation and the GitHub discussions for solutions to common problems.
Changelog
Version 7.0
- Updated target SDK to 35.
- Migrated to Java 17.
- Refactored file upload and camera handling.
- Implemented a new plugin architecture.
- Added a QR code reader plugin example.
- Improved error handling and user feedback.
- Updated dependencies to the latest versions.
- Added this documentation page.