I am a beginner and building webview app with splash screen in AIED.
I want to add spinner loading for every page loading in webview. I mean when this webview loads after the splash screen, I can see home page of website when I open any other page. While loading that page I want to show spinner in the center of screen. When the page load the spinner should disappear.
I not know where to add the specific code.
Here is mainactivity.java
package com.mystore.mominbaba;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
public class MainActivity extends Activity {
//private WebView webView = null;
private WebView mWebView;
private ImageView mSplashView;
private ValueCallback <Uri> mUploadMessage;
public ValueCallback <Uri[]> uploadMessage;
public static final int REQUEST_SELECT_FILE = 100;
private final static int FILECHOOSER_RESULTCODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webview);
mSplashView = (ImageView) findViewById(R.id.splash);
mWebView.getSettings().setJavaScriptEnabled(true); // enable javascript
mWebView.getSettings().setLoadWithOverviewMode(true); //sets Overview to true
mWebView.getSettings().setUseWideViewPort(true); //sets wideviewport deleting whitespsce
mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
mWebView.getSettings().setAllowFileAccess(true);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mSplashView.setVisibility(View.GONE);
mWebView.setVisibility(View.VISIBLE);
}
});
mWebView.loadUrl("https://www.mominbaba.com");
mWebView.setVisibility(View.GONE);
mSplashView.setVisibility(View.VISIBLE);
mWebView.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
public boolean onShowFileChooser(WebView mWebView, ValueCallback <Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
if (uploadMessage != null) {
uploadMessage.onReceiveValue(null);
uploadMessage = null;
}
uploadMessage = filePathCallback;
Intent intent = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
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);
}
});
}
#Override
public 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;
}
}
private class xWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.
`onKeyDown` (keyCode, event);
}
}
Here is activity main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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=".MainActivity">
<ImageView
android:id="#+id/splash"
android:scaleType="fitXY"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:visibility="gone"
android:src="#drawable/image_1"/>
<WebView
android:id="#+id/webview"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible"/>
</RelativeLayout>
Big Caveat: This solution won't completely hide the white screen(loading) on websites that has to download and load .js files especially if they are big.
First, you are using onPageFinished incorrectly. onPageFinished is always going to be called after every page load has finished. This means if you are navigating on your website, it will call onPageFinished every after you navigate a URL and the webview has finished loading it.
Here's an idea on how to do this:
First create an HTML page and design on how you want your spinner would look like. Save the HTML template as a string HTMLSpinner.
Then create a second webview and load the HTML template string to it
public WebView spinner;
spinner.loadData(HTMLSpinner, "text/html", "UTF-8");
Then modify your main mWebView.setWebViewClient like this
mWebView.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, final String url, Bitmap favicon) {
mWebView.setVisibility(View.GONE);
spinner.setVisibility(View.VISIBLE);
// YOUR LANDING PAGE
if(url.equals("https://www.mominbaba.com")){
mWebView.setVisibility(View.GONE);
mSplashView.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageFinished(WebView view, String url) {
mWebView.setVisibility(View.VISIBLE);
spinner.setVisibility(View.GONE);
// YOUR LANDING PAGE
if(url.equals("https://www.mominbaba.com")){
mWebView.setVisibility(View.GONE);
mSplashView.setVisibility(View.VISIBLE);
}
}
});
That should swap the current webview that you see from the main webview to the loader. I have chosen to use a second webview because the asset that was given to was an animated SVG.
Related
I am building an Android app and I am newbie.
I am not able to make calls by clicking a button inside android webview app
Here is my code:
Mainactivity
package pk.gogobazar.gogobazarapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
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 String url ="https://gogobazar.pk/";
#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(url);
webView.setWebViewClient(new xWebViewClient());
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
public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
{
if (uploadMessage != null) {
uploadMessage.onReceiveValue(null);
uploadMessage = null;
}
uploadMessage = filePathCallback;
Intent intent = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
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);
}
});
}
#Override
public 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;
}
}
private class xWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Android Manifest File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pk.gogobazar.gogobazarapp">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CALL_PHONE"/>
<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=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I am new and still learning basics. Please help me to allow the phone calls in webview on this activity. So when someone clicks on phone number it should call, thanks.
This is How it works for me:
package com.example.myapplication;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.app.Activity;
import android.content.Intent;
public class MainActivity extends Activity {
private static final String TEL_PREFIX = "tel:";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView wv = (WebView) findViewById(R.id.webview);
wv.setWebViewClient(new CustomWebViewClient());
wv.loadUrl("https://google.pk");
WebSettings webSettings = wv.getSettings();
webSettings.setJavaScriptEnabled(true);
}
private class CustomWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView wv, String url) {
if(url.startsWith(TEL_PREFIX)) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
startActivity(intent);
return true;
}
return false;
}
}
}
First you would need to bind your javascript code to your android code, this guide demonstrates how to do that. Then in your javascript, you could add a listener to your button that invokes a Java method.
Second, you need to integrate a calling solution into your app this guide explains what options you have and how you can implement them.
Once you implemented the calling solution, you could simply make a call from the Java method that you intend to invoke from your javascript.
I built This App and i want that i can choose an image from gallery to replace the image view at the top. like the profil at facebook etc...
i tried the above code:
public class MainActivity extends Activity {
private static int RESULT_LOAD_IMAGE = 1;
Uri myPicture = null;
Button buttonLoadImage;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//getting View
buttonLoadImage =(Button) findViewById(R.id.regButton);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.regUserPhoto);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
in my phone with android 4.4.4: i can choose the image but when i press ok the app crash.
in emulator android 5.1.1: when i press the image the app crash
Make your button call the activity implement here with startActivityForResult:
https://www.youtube.com/watch?v=w06OnGwhh4I&feature=youtu.be
This activity pick image from camera, gallery, google drive, etc. Crop and rotate the image to.
Code Java:
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.android.controledevendas.R;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
public class Image_Cropper_Activity extends AppCompatActivity {
private ImageButton btn_browse;
private ImageButton btn_reset;
private ImageView imageView;
private Uri uriPass = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image__cropper_);
btn_browse = findViewById(R.id.image_cropper_btn_add_picture);
btn_reset = findViewById(R.id.image_cropper_btn_reset);
imageView = findViewById(R.id.cropper_image);
btn_browse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CropImage.startPickImageActivity(Image_Cropper_Activity.this);
}
});
btn_reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imageView.setImageBitmap(null);
uriPass = null;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add_cliente_fornecedor, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case (android.R.id.home):
setResult(RESULT_OK);
finish();
return true;
case (R.id.save_client_fornecedor):
saveImage();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK){
Uri imageUri = CropImage.getPickImageResultUri(this, data);
if(CropImage.isReadExternalStoragePermissionsRequired(this, imageUri)){
}
else {
startCrop(imageUri);
}
}
if(requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE){
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK){
imageView.setImageURI(result.getUri());
uriPass = result.getUri();
//Toast.makeText(this, "Imagem Atualizada Com Sucesso!", Toast.LENGTH_SHORT).show();
}
}
}
private void startCrop(Uri imageUri) {
CropImage.activity(imageUri).setGuidelines(CropImageView.Guidelines.ON).setMultiTouchEnabled(true).start(this);
}
private void saveImage() {
if (uriPass==null){
Toast.makeText(this, "Por favor, insira uma imagem.", Toast.LENGTH_SHORT).show();
return;
}
Intent dataForAddEditScreen = new Intent();
dataForAddEditScreen.setData(uriPass);
setResult(RESULT_OK, dataForAddEditScreen);
finish();
}
}
Xml code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
android:orientation="vertical"
android:gravity="center"
android:padding="10dp"
tools:context=".Activities.Image_Cropper_Activity">
<ImageView
android:id="#+id/cropper_image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal"
android:padding="20dp">
<ImageButton
android:id="#+id/image_cropper_btn_add_picture"
android:layout_width="80dp"
android:layout_height="80dp"
android:background="#drawable/bg_round"
app:srcCompat="#drawable/ic_image_sample_50x50_white" />
<Space
android:layout_width="20dp"
android:layout_height="wrap_content" />
<Space
android:layout_width="20dp"
android:layout_height="wrap_content" />
<ImageButton
android:id="#+id/image_cropper_btn_reset"
android:layout_width="80dp"
android:layout_height="80dp"
android:background="#drawable/bg_round"
app:srcCompat="#drawable/ic_refresh_50x50_white" />
</LinearLayout>
</LinearLayout>
After you return the image Uri:
private ImageView imageProduto;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add__edit__produto_);
imageProduto = findViewById(R.id.image_produto_detail);
}
...
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == Constantes.REQUEST_CODE_ADD_PICTURE && resultCode == RESULT_OK && data!= null){
Uri imageUri = data.getData();
imageProduto.setImageURI(imageUri);
Toast.makeText(this, "Image Update Successfully!", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this, "Image Not Updated!", Toast.LENGTH_SHORT).show();
}
}
Getting Error while sharing a news on whatsapp using my Webview App
**package com.agraleaks.imgauravanimator;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.View;
import android.graphics.Bitmap;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import com.agraleaks.imgauravanimator.Common.Config;
public class MainActivity extends AppCompatActivity implements OnRefreshListener {
private WebView webView;
private ProgressDialog dialog;
private BroadcastReceiver mRegistrationBroadcastReceiver;
private SwipeRefreshLayout swipeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
//WebView
webView = (WebView)findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
//hide loading image
findViewById(R.id.imageView1).setVisibility(View.GONE);
findViewById(R.id.progressBar1).setVisibility(View.GONE);
//show webview
findViewById(R.id.webView).setVisibility(View.VISIBLE);
}
});
webView.loadUrl("http://www.agraleaks.com/");
webView.setHorizontalScrollBarEnabled(false);
webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setBackgroundColor(128);
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Config.STR_PUSH))
{
String message = intent.getStringExtra(Config.STR_PUSH);
showNotification ("Agra Leaks- Fastest News Channel in the City",message);
}
}
};
onNewIntent(getIntent());
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
if(url != null && url.startsWith("whatsapp://"))
{
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Agra Leaks - Digital Newspaper.");
sendIntent.setType("text/plain");
sendIntent.setPackage("com.whatsapp");
startActivity(sendIntent);
return true;
}else
{
return false;
}
}
private void showNotification(String title, String message) {
Intent intent = new Intent(getBaseContext(),MainActivity.class);
intent.putExtra(Config.STR_KEY,message);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(getBaseContext(),0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.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);
notificationManager.notify(1,builder.build());
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction()== KeyEvent.ACTION_DOWN){
switch (keyCode){
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()){
webView.goBack();
}
else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#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));
}
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override public void run() {
// webView.reload();
swipeLayout.setRefreshing(false);
webView.loadUrl( "javascript:window.location.reload( true )" );
}
}, 5000);
}
}**
These are my code
Unable to share on Whatsapp from my WebView. Getting Error - The webpage at whatsapp://send?text= could not be load because net::ERR_UNKNOWN_URL_SCHEME.
here is my activity_main
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="com.agraleaks.imgauravanimator.MainActivity">
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/webView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</android.support.v4.widget.SwipeRefreshLayout>
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/splash" />
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView1"
android:layout_centerHorizontal="true" />
</RelativeLayout>
i found my Answer myself ,
i just need to put these codes
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url != null && url.startsWith("whatsapp://"))
{
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Moon TV");
sendIntent.setType("text/plain");
sendIntent.setPackage("com.whatsapp");
startActivity(sendIntent);return true;
}else
{
return false;
}
My question is why can't I use getActivity method in the following code. I'm trying to upload image with webView. It's my first Android application. I want to create an app for my classified osclass site.
When I build the app I get the following message:
error: cannot find symbol method getActivity().
Please change my code, and paste in Answer or write where should I put your code (or change).
package org.satlyk.org.myapplication;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private String WebAddress = "https://satlyk.org";
private WebView webView;
private ProgressBar progressBar;
private FrameLayout frameLayout;
private ValueCallback<Uri> mUploadMessage;
public ValueCallback<Uri[]> uploadMessage;
public static final int REQUEST_SELECT_FILE = 100;
private final static int FILECHOOSER_RESULTCODE = 1;
#Override
public 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
Toast.makeText(getActivity().getApplicationContext(), "Failed to Upload Image", Toast.LENGTH_LONG).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frameLayout = (FrameLayout) findViewById(R.id.frameLayout);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setMax(100);
webView = findViewById(R.id.webView);
WebSettings mWebSettings = webView.getSettings();
mWebSettings.setJavaScriptEnabled(true);
mWebSettings.setSupportZoom(false);
mWebSettings.setAllowFileAccess(true);
mWebSettings.setAllowFileAccess(true);
mWebSettings.setAllowContentAccess(true);
webView.getSettings().setUserAgentString("satlyk_app");
webView.setWebViewClient(new HelpCliet());
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
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;
Toast.makeText(getActivity().getApplicationContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
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);
}
public void onProgressChanged (WebView view, int progress)
{
frameLayout.setVisibility(View.VISIBLE);
progressBar.setProgress(progress);
setTitle("Ýüklenýär...");
if (progress == 100) {
frameLayout.setVisibility(View.GONE);
setTitle(view.getTitle());
}
super.onProgressChanged(view, progress);
}
});
webView.getSettings() .setJavaScriptEnabled(true);
webView.setVerticalScrollBarEnabled(false);
webView.loadUrl(WebAddress);
progressBar.setProgress(0);
}
private class HelpClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
frameLayout.setVisibility(view.VISIBLE);
return true;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (webView.canGoBack()) {
webView.goBack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
You don't need to do getActivity() since you are already in the activity. You should just be able to do getApplicationContext()
Toast.makeText(getApplicationContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
How show Banner Ads on Newspaper Link "Webview" Android Eclipse
I already set Admob "Banner Ads and Interstitial Ads" on my Project. Interstitial Ads Work Correctly but Banner Ads not Show on Webview.
Here my Java & xml Code
Details_Newspaper.Java
package com.nasir.newspaper;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewConfiguration;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
#SuppressLint("SetJavaScriptEnabled")
public class Details_Newapaper extends Activity {
WebView mWebview;
AdView mAdView;
private InterstitialAd interAd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Adds Progrss bar Support
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.details_newapaper );
// For Banner Ads View
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
// For Interstitial Ads View
interAd = new InterstitialAd(this);
interAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
AdRequest adRequest_FC = new AdRequest.Builder().build();
interAd.loadAd(adRequest_FC);
interAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
// TODO Auto-generated method stub
displayInterstitial();
}
});
getOverflowMenu();
// Makes Progress bar Visible
getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
mWebview = new WebView(this);
mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
mWebview.getSettings().setSupportZoom(true); //Zoom Control on web (You don't need this
//if ROM supports Multi-Touch
mWebview.getSettings().setBuiltInZoomControls(true); //Enable Multitouch if supported by ROM
final Activity Activity = this;
mWebview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
//Make the bar disappear after URL is loaded, and changes string to Loading...
Activity.setTitle("Loading..... Please Wait");
Activity.setProgress(progress * 100); //Make the bar disappear after URL is loaded
// Return the app name after finish loading
if(progress == 100)
Activity.setTitle(R.string.app_name);
}
});
mWebview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
Toast.makeText(Activity, description, Toast.LENGTH_SHORT).show();
}
});
String customHtml = getIntent().getStringExtra("Newspaper_Name");
mWebview.loadUrl(customHtml);
setContentView(mWebview);
mWebview.getSettings().setBuiltInZoomControls(true);
}
// On Back Button Press, Go to Website Back
#Override
public void onBackPressed() {
if (mWebview.isFocused() && mWebview.canGoBack()) {
mWebview.goBack();
} else {
super.onBackPressed();
finish();
}
}
// For Interstitial Ads View
public void displayInterstitial() {
if (interAd.isLoaded()) {
interAd.show();
}
}
/** Called when leaving the activity */
#Override
public void onPause() {
if (mAdView != null) {
mAdView.pause();
}
super.onPause();
}
/** Called when returning to the activity */
#Override
public void onResume() {
super.onResume();
if (mAdView != null) {
mAdView.resume();
}
}
/** Called before the activity is destroyed */
#Override
public void onDestroy() {
if (mAdView != null) {
mAdView.destroy();
}
super.onDestroy();
}
// inflate for action bar
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.refresh_main, menu);
return true;
}
// handle click events for action bar items
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.refresh:
showToast("Refresh was clicked.");
return true;
// case R.id.share:
// showToast("Share was clicked.");
// return true;
//
default:
return super.onOptionsItemSelected(item);
}
}
// put the other two menu on the three dots (overflow)
private void getOverflowMenu() {
try {
ViewConfiguration config = ViewConfiguration.get(this);
java.lang.reflect.Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if(menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception e) {
e.printStackTrace();
}
}
// so that we know something was triggered
public void showToast(String msg){
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}
details_newspaper.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="top|fill_vertical"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<WebView
android:id="#+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
ads:adSize="BANNER"
ads:adUnitId="ca-app-pub-1528948212400372/9325301249" >
</com.google.android.gms.ads.AdView>
</RelativeLayout>