I want to download documents from the links ive scraped on the web, i have a listview listener so when i press one of the item in the list it will return a url, ive set it up so getLink will be the link of the pdf file i want to download and set up filenametoo.
getLink = http://www.phivolcs.dost.gov.ph/images/Flyer-eq-and-eq-hazards.pdf
filename = Flyer-eq-and-eq-hazards.pdf
So i call this inside my listview listener and its suppose to download but its not working.
new DownloadFile().execute(getLink, filename);
I have errors like java.io.IOException: open failed: ENOENT (No such file or directory)
insideMain
private class DownloadFile extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String... strings) {
String fileUrl = strings[0]; // -> getLink = http://www.phivolcs.dost.gov.ph/images/Flyer-eq-and-eq-hazards.pdf
String fileName = strings[1]; // -> Flyer-eq-and-eq-hazards.pdf
String extStorageDirectory = Environment.getDataDirectory().toString();
File folder = new File(extStorageDirectory, "testthreepdf");
folder.mkdir();
File pdfFile = new File(folder, fileName);
try{
pdfFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
FileDownloader.downloadFile(fileUrl, pdfFile);
return null;
}
}
downloadFile
package com.example.boneyflesh.homepage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class FileDownloader {
private static final int MEGABYTE = 1024 * 1024;
public static void downloadFile(String fileUrl, File directory) {
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.boneyflesh.homepage">
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" ></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:ignore="AllowBackup">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps" />
<!--
ATTENTION: This was auto-generated to add Google Play services to your project for
App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information.
-->
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity android:name=".GeohazardResults" />
<activity android:name=".MineralResults" />
<activity android:name=".LandformResults" />
<activity android:name=".Downloads"></activity>
</application>
EDIT
I called useFileAsyncTask(); then i received an error FATAL EXCEPTION: AsyncTask #1
Constructor
protected void useFileAsyncTask() {
DownloadFile task = new DownloadFile(this);
task.execute();
}
Asynktask
private class DownloadFile extends AsyncTask<String, Void, Void>{
private Context myContextRef;
public DownloadFile(Context context) {
myContextRef = context;
}
#Override
protected Void doInBackground(String... strings) {
//String fileUrl = strings[0]; // -> http://maven.apache.org/maven-1.x/maven.pdf
//String fileName = strings[1]; // -> maven.pdf
String extStorageDirectory = myContextRef.getFilesDir().toString();
//String extStorageDirectory = Environment.getDataDirectory().toString();
File folder = new File(extStorageDirectory, "testthreepdf");
folder.mkdir();
File pdfFile = new File(folder, filename);
try{
pdfFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
FileDownloader.downloadFile(getLink, pdfFile);
return null;
}
}
downloadFile remains the same.
Change the line
String extStorageDirectory = Environment.getDataDirectory().toString();
to
String extStorageDirectory = context.getFilesDir().toString();
where context is the Context that you will need to supply to the AsyncTask.
Environment.getDataDirectory() is the system-wide user data directory where you may not create files while ontext.getFilesDir() is the data directory for your app where you may create files.
Related
Android Studio / SDK 30 I need to upload into a input file in webview.
There is TONS of 6,7 to 8 years ago answers that don't work anymore :(
I have a working webview that can use .getUserMedia (webrtc), can use GPS, but is unable to upload in a regular <input type="file" >
This code does ask (when start the app) permissions for camera, storage, gps...
I want to trigger a prompt that ask the user take photo, take video or choose from gallery and that actually uploads it.
here my Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.apptheway.wexview">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" android:maxSdkVersion="28" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.CAMERA2" />
<uses-permission android:name="android.webkit.PermissionRequest" />
<uses-permission android:name="com.android.vending.BILLING" />
<uses-permission android:name="com.android.vending.CHECK_LICENSE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera2" />
<uses-feature android:name="android.hardware.location.gps" />
<uses-feature android:name="android.hardware.location.network" />
<application
android:allowBackup="true"
android:fullBackupContent="true"
android:hardwareAccelerated="true"
android:requestLegacyExternalStorage="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.NoActionBar">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here MainActivity
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.GeolocationPermissions;
import android.webkit.PermissionRequest;
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 androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Random;
#SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends AppCompatActivity {
private WebView mWebView;
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE = 1;
#Override
protected void onStart() {
super.onStart();
String[] permissions = {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.CAMERA,
Manifest.permission.RECORD_AUDIO,
Manifest.permission.MODIFY_AUDIO_SETTINGS,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
requestPermissions(permissions, 0);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
for (int i = 0; i < permissions.length; i++) {
String permission = permissions[i];
boolean isGranted = grantResults[i] >= 0;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
mWebView = new WebView(this);
WebSettings webSettings = mWebView.getSettings();
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);
webSettings.setDomStorageEnabled(true);
webSettings.setGeolocationEnabled(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setDisplayZoomControls(false);
webSettings.setSupportZoom(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
webSettings.setAllowFileAccess(true);
webSettings.setAllowContentAccess(true);
webSettings.setDatabaseEnabled(true);
webSettings.setMediaPlaybackRequiresUserGesture(false);
webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
int opensInWexView = 1;
// DOMAINS
// if ( !url.contains("stubfee.com") && !url.contains("stubfee.com") && !url.contains("stubfeedevent.com") ) {
// opensInWexView = 0;
// }
// IF FILE
if ( url.contains(".pdf") || url.contains(".mov") || url.contains(".mp") ||
url.contains(".hv") || url.contains(".aif") || url.contains(".wav") ||
url.contains(".xls") || url.contains(".doc") || url.contains(".txt")
) {
opensInWexView = 0;
}
// URL SCHEME
if ( url.startsWith("tel:") || url.startsWith("sms:") ||
url.startsWith("mms:") || url.startsWith("mailto:") ||
url.startsWith("fax:")
) {
opensInWexView = 0;
}
switch (opensInWexView) {
case 0:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
break;
default:
view.loadUrl(url);
break;
}
return true;
}
});
mWebView.setWebChromeClient(new WebChromeClient() {
// CAMERA
public void onPermissionRequest(final PermissionRequest request) {
request.grant(request.getResources());
}
// GPS
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, false);
}
// FILE INPUT
});
mWebView.loadUrl("https://www.stubfee.com/account/" + (new Random().nextInt((1000000 - 1) + 1) + 1) + "/");
this.setContentView(mWebView);
}
#Override
public boolean onKeyDown(final int keyCode, final KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
In many answers they talk about adding code inside
mWebView.setWebChromeClient(new WebChromeClient() {}
But any answer from the web I try; it does work :(
in one of the answers, I get the gallery to open, but when select a file, nothing happens :(
is there a more recent approach ?
what I'm I missing ?
Tried those without success
Upload an Image from camera or gallery in WebView
Android Webview Upload Image from gallery or camera
Saving photos and videos using Android FileProvider to the gallery
File Upload in WebView Android Studio
How to Upload Files with WebView in Android Studio?
How to make upload button work in android app?
Thanks
I had the same problem, and was having problems with WebChromeClient, too, and I recently found the answer. onShowFileChooser is the key event. (I had trouble trying to pass mWebView as a param to a new class constructor, but it did work when I kept the definition inside MainActivity.)
Also, this technique avoids the now-deprecated startActivityForResult and onActivityResult functions.
In Kotlin
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportActionBar!!.hide()
val progressBarView = findViewById<ProgressBar>(R.id.webviewProgress)
mWebview.settings.allowContentAccess = true
mWebview.settings.allowFileAccess = true
mWebview.settings.domStorageEnabled = true
mWebview.settings.javaScriptEnabled = true
mWebview.webViewClient = AppWebViewClient(progressBarView)
mWebview.webChromeClient = object:WebChromeClient() {
override fun onShowFileChooser(mWebView:WebView,
filePathCallback:ValueCallback<Array<Uri>>,
fileChooserParams:FileChooserParams):Boolean {
if (mUploadMessage != null) {
mUploadMessage!!.onReceiveValue(null)
mUploadMessage = null
}
mUploadMessage = filePathCallback
val contentSelectionIntent = Intent(Intent.ACTION_GET_CONTENT)
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE)
contentSelectionIntent.type = "*/*"
val intent = Intent(Intent.ACTION_CHOOSER)
intent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent)
intent.putExtra(Intent.EXTRA_TITLE, "File Chooser")
try {
getFileResultLauncher.launch(intent)
} catch (e: ActivityNotFoundException) {
mUploadMessage = null
Toast.makeText(getApplicationContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show()
return false
}
return true
}
}
mWebview.loadUrl(getString(R.string.app_url))
}
val getFileResultLauncher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {
ar: ActivityResult ->
val intent: Intent? = ar.data
val result = if (intent == null || ar.resultCode != RESULT_OK) null else arrayOf(Uri.parse(intent.dataString))
mUploadMessage!!.onReceiveValue(result);
mUploadMessage = null;
}
override fun onBackPressed() {
_webview.goBack()
}
Hi guys Im trying to make a push notif using alarmmanager
for my simple voting system.
The problem is no notification showing.
whats wrong with this?
Also i notice that my mBuilder = new NotificationCompat.Builder(context)
has warning says "Builder is deprecated" is that the reason why its not working?
this is my codes
AlerReciever class
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import. android.support.v4.app.
NotificationCompat;
/**
* Created by ivan on 2/27/2018.
*/
public class AlertReceiver extends. B.
BroadcastReceiver {
#Override
public void onReceive(
Context context, Intent. intent) {
createNotification(context,"Voting. System","
Congrats to winner","Alert" );
}
public void createNotification(Context context,
String msg
,String msgText, String msgAlert){
PendingIntent notificIntent =
PendingIntent.getActivity(context,0,
new Intent(context,
AddCandidate.class),0);
NotificationCompat.Builder mBuilder = new.
NotificationCompat.Builder(context)
.setSmallIcon(R.
drawable.ic_account_circle_black_2. 4dp)
.setContentTitle(msg)
.setTicker(msgAlert)
.setContentText(msgText);
mBuilder.setContentIntent(notificIntent);
mBuilder.setDefaults(NotificationCompat.
DEFAULT. _SOUND);
mBuilder.setAutoCancel(true);
NotificationManager notificationManager =
(NotificationManager)
context.getSystemService(context.
NOTIFICATION_SERVICE);
notificationManager.notify(1, mBuilder.build());
}
}
button
btnStart.setOnClickListener(new.
View.OnClickListener()
{
#Override
public void onClick(View view) {
Long alertTime =
GregorianCalendar.getInstance().
getTimeInMillis()+5*1000;
Intent alertIntent = new.
Intent(AddCandidate.this, AlertReceiver.class);
AlarmManager alarmManager =
(AlarmManager)getSystemService(
Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.
RTC_WAKEUP, alertTime,
PendingIntent.getBroadcast(
AddCandidate.this, 1,alertIntent,
PendingIntent.FLAG_UPDATE_CURRENT));
Toast.makeText(AddCandidate.this, "ll",
Toast.LENGTH_SHORT).show();
}
});
Manifest
xmlns:android="
http://schemas.android.com/apk/res/android"
package="com.example.ivan.votingsystem">
<uses-permission. android:name="android.
permission.READ_EXTERNAL_STORAGE" />
<uses-permission. android:name="
android.permission.SET_ALARM"/>
<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>
<activity android:name=".Dashboard" />
<activity android:name=".AddCandidate"/>
<activity android:name=".VoteNow"></activity>
</application>
</manifest>
I'm very new to android studio development so the answer is probably trivial.
That being said, I've busted my head around the problem for a day now :/
I am trying to run a chunk of code every 10 seconds even when the app is closed using AlarmManager.
I copy-pasted what is suggested in this guide https://guides.codepath.com/android/Starting-Background-Services
I'm a little puzzled by the result -
I think I do get alarm triggered every 10 seconds, as indicated in the log:
04-20 21:25:44.125 557-632/? D/AlarmManager: Triggered Alarm 22ad4130
RTC_WAKEUP IntentSender{220fb650: PendingIntentRecord{2243b570
com.example.somelocation.myapplication broadcastIntent}} 04-20
21:25:44.125 557-557/? V/AlarmManager: triggered: flg=0x14
cmp=com.example.somelocation.myapplication/.MyAlarmReceiver
But i can't see any of my custom logs positioned inside my BroadcastReceiver or my IntentService.
MyTestService:
package com.example.somelocation.myapplication;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
public class MyTestService extends IntentService {
public MyTestService() {
super("MyTestService");
}
#Override
protected void onHandleIntent(Intent intent) {
// Do the task here
Log.i("MyTestService", "Service running"); // Can't see this log
}
}
MyAlarmReceiver:
package com.example.somelocation.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class MyAlarmReceiver extends BroadcastReceiver {
public static final int REQUEST_CODE = 12345;
#Override
public void onReceive(Context context, Intent intent) {
Log.e("MyTestService","broadcastreciever onReceive called"); // Can't see this log
Intent i = new Intent(context, MyTestService.class);
i.putExtra("foo", "bar");
context.startService(i);
}
}
Main Activity:
package com.example.somelocation.myapplication;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView batteryInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scheduleAlarm();
}
public void scheduleAlarm() {
Intent intent = new Intent(getApplicationContext(), MyAlarmReceiver.class);
final PendingIntent pIntent = PendingIntent.getBroadcast(this, MyAlarmReceiver.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
long firstMillis = System.currentTimeMillis();
AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
10000, pIntent);
}
}
my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.somelocation.myapplication">
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<receiver
android:name=".MyAlarmReceiver"
android:process=":remote" >
</receiver>
<service
android:name=".MyTestService"
android:exported="false"/>
</activity>
</application>
</manifest>
What am I missing?
update:
Got it! It was an error in my manifest file:
The close tag of the main activity was after the receiver declaration. should be:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".MyAlarmReceiver"
android:process=":remote" >
</receiver>
<receiver
android:name=".BootReceiver"
android:enabled="true"
android:exported="true"/>
</application>
The log is being printed on the console... here is the log I am getting
04-22 18:30:28.421 1830-4146/com.example.somelocation.myapplication I/MyTestService: Service running
04-22 18:30:45.337 2641-2641/com.example.somelocation.myapplication:remote E/MyTestService: broadcastreciever onReceive called
04-22 18:30:45.344 1830-4394/com.example.somelocation.myapplication I/MyTestService: Service running
04-22 18:30:48.4032641-2641/com.example.somelocation.myapplication:remote E/MyTestService: broadcastreciever onReceive called
You are creating a separate process('remote') for the BroadcastReceiver and your logcat may be setup to display only the main process create at first.
See the screenshots -
So change the application process from the dropdown and also select the log level to Verbose.
I am trying to build a simple app using WebView in android studio.
It runs okay in Nexus 5 emulator. However, when I run the same app on my real Samsung Tab S 8.4 SM-T700, the tablet asks me to select a default browser (using a dialog "open with Chrome or Internet"). And my app does not display the selected webpage.
How can I force android to run my app on Samsung Tab 8.4 S M-T700?
Here is the relevant code segment:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url= "http://www.google.com";
WebView view=(WebView) this.findViewById(R.id.webView);
view.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
view.loadUrl(url);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
You need to add:
view.setWebViewClient(new WebViewClient());
before your call to loadUrl. Google does a redirect, and redirects should be handled by a WebViewClient. When it's not set, WebView passes the URL to the default browser. Setting an empty WebViewClient makes WebView to load the URL in itself.
i want to implement searcb bar concept in my app .
when ever user clicks on searbar the keyboard buttons need to display with default searchable button in it ..i followed few of the links ...but unable to get the searchable bar nor the keyboard populated buttons ...
please help me thanks in advance .
this is my searchable.xml placed res/xml
<searchable
android:label="#string/app_label"
android:hint="#string/search_hint" >
</searchable>
and this is my manifest file
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".SearchboxActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="android.app.searchable"
android:resource="#xml/searchable"/>
</activity>
</application>
here is the activity ...
package com.hands;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
public class SearchboxActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the intent, verify the action and get the query
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
// doMySearch(query);
}
}
private void doMySearch(String query) {
// TODO Auto-generated method stub
System.out.println("hello 2");
}
}