Open files with other apps in webview - java

I'm building a simple app, in which I use a webview in Android Studio, in the app, i search a movie, and then I download the torrent.
When I download in the web, it automatically send me to the utorrent app, but when I download it from my app, I can't open it.
Sorry for my English and for my poor knowledge.
My java code:
public class MainActivity extends AppCompatActivity {
WebView web;
EditText et_peli;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
web=(WebView)findViewById(R.id.web);
et_peli=(EditText)findViewById(R.id.et_peli);
}
public void buscar0nclick(View v){
WebSettings conf = web.getSettings();
conf.setJavaScriptEnabled(true);
web.loadUrl("http://www.miltorrents.com/?pTit=" + et_peli.getText().toString());
web.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
Log.d("WEB_VIEW_TEST", "error code:" + errorCode + " - " + description);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.endsWith(".torrent")) {
Uri source = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(source);
request.setDescription("Description for the DownloadManager Bar");
request.setTitle("YourApp");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "SmartPigs.apk");
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
else view.loadUrl(url);
return true;
}
});
}
}

Just to make sure I have this right, you want to send your user, once they download the torrent to the torrent's app to view the movie, correct?
I would check to see if that torrent app has a broadcast receiver that you can search for. If so, you could just pass along the information. If not, you have to look for a way to have that media file play within your app, or use one of the default movie players.

Related

How to do google sign-in from an Android WebView and after successful sign-in redirect back to the home website?

I have an android app that uses a webview to render a website that has a google log-in and a facebook log-in. The problem is that when i do the google or facebook login, it opens a mobile browser and after successful login it does not go back to the app, it stays in the browser. I want it to go to the app. It doesnot matter the login page opens in the webview itself or it opens in the browser. But after successful login it should redirect back to the home website in the app. i have tried rendering the login page in the webview itself but after logging in it stucks in a page.
I have added the INTERNET permission i the manifest
public class MainActivity extends AppCompatActivity {
WebView myWebView;
WebView myPopedWebView;
WebSettings myWebSettings;
FrameLayout mContainer;
String HOME_URL = "https://www.something.com";
String HOME_URL_PREFIX = "www.something.com";
Context mContext;
#SuppressLint("SetJavaScriptEnabled")
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CookieManager cm = CookieManager.getInstance();
cm.setAcceptCookie(true);
myWebView = findViewById(R.id.myWebView);
myWebSettings = myWebView.getSettings();
mContainer = findViewById(R.id.frame_layout);
myWebView.loadUrl(HOME_URL);
myWebView.setWebViewClient(new customWebViewClient());
myWebView.setWebChromeClient(new customWebChromeClient());
myWebSettings.setJavaScriptEnabled(true);
myWebSettings.setDomStorageEnabled(true);
myWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
myWebSettings.setAppCacheEnabled(true);
myWebSettings.setSupportMultipleWindows(false);
myWebSettings.setUserAgentString(myWebSettings.getUserAgentString().replace("; wv", ""));
mContext = this.getApplicationContext();
}
public class customWebViewClient extends WebViewClient {
#Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
String host = Uri.parse(url).getHost();
Log.d("Loading url", url);
if (host.equals(HOME_URL_PREFIX)) {
if (myPopedWebView != null) {
myPopedWebView.setVisibility(View.GONE);
mContainer.removeView(myPopedWebView);
myPopedWebView = null;
}
return false;
}
if (host.equals("www.facebook.com") || host.equals("www.accounts.google.com")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return false;
}
#Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
Log.d("onReceivedSslError", "onReceivedSslError");
}
}
public class customWebChromeClient extends WebChromeClient {
#SuppressLint("SetJavaScriptEnabled")
#Override public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
myPopedWebView = new WebView(mContext);
myPopedWebView.getSettings().setDomStorageEnabled(true);
myPopedWebView.getSettings().setJavaScriptEnabled(true);
myPopedWebView.setWebChromeClient(new customWebChromeClient());
myPopedWebView.setWebViewClient(new customWebViewClient());
myPopedWebView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
WebView.WebViewTransport transport = (WebView.WebViewTransport)resultMsg.obj;
transport.setWebView(myPopedWebView);
resultMsg.sendToTarget();
return true;
}
#Override public void onCloseWindow(WebView window) {
Log.d("onCloseWindow", "closed");
}
}
}
You don't have any code that requests the facebook (or google) account login with login callback. Here's what you can do:
Either code the login capability(along with login callback url configuration) in the website that has your login with facebook or google buttons.
or, you can add facebook and google sign-in (auth) sdks in your android app and handle the login and callback in your app (writing java/kotlin code).
You can choose either of the two approaches, you can easily find tutorials online on how to integrate facebook sdk in web (approach 1) or android (approach 2).
Happy Coding!!

Is there a way to play Twitch Streams inside Android app (Java)

I am unable to play Twitch Streams in my Android application.
Twitch is only providing their embed url for playing Streams.
I am using this url: https://player.twitch.tv/?channel=CHANNEL_NAME
I am using a WebView to load this url by
mWebview.loadUrl(url);
But this method has several issues, like the video tends to autoplay but gets stuck initially. I need to press Pause first and then the Play button to start this stream.
Try using this code.
private WebView mWebview ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
mWebview = new WebView(this);
mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
final Activity activity = this;
mWebview.setWebViewClient(new WebViewClient() {
#SuppressWarnings("deprecation")
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
}
#TargetApi(android.os.Build.VERSION_CODES.M)
#Override
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
// Redirect to deprecated method, so you can use it in all SDK versions
onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
}
});
mWebview .loadUrl(url);
setContentView(mWebview );
}

How to show custom error message on webview

I'm trying to create custom error message for my app which is using webview. so far i'm using below code which has a very minimal problem... when i click links on the webview the page is reloading the same page instead of processing the clicked link. my links on the webview are download link so either it should download using the same app or open down-loader options
protected void fetch_web(){
final WebView web;
web = (WebView) findViewById(R.id.voice_mail_view_port);
NoNetwork = (Button) findViewById(R.id.btn_no_internet);
NoNetwork.setVisibility(View.GONE);
String mdb = "http://192.168.23.1/default.php";
getWindow().setFeatureInt( Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
final Activity MyActivity = this;
web.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
MyActivity.setTitle("Fetching feeds...");
MyActivity.setProgress(progress * 100);
loader();
if(progress == 100) {
MyActivity.setTitle(R.string.app_name);
deLoader();;
}
}
});
web.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String
failingUrl) {
deLoader();
alert("No Internet Connection","Let's get connected to see feeds");
web.setVisibility(View.GONE);
NoNetwork.setVisibility(View.VISIBLE);
}
});
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl((mdb));
}
protected void loader(){
loading = (ProgressBar) findViewById(R.id.loader);
loading.setVisibility(View.VISIBLE);
}
protected void deLoader(){
loading = (ProgressBar) findViewById(R.id.loader);
loading.setVisibility(View.INVISIBLE);
}
Sample download link http://192.168.23.1/download.php?id=1
Can someone help me out, i suspect my error is coming from here
web.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String
failingUrl) {
deLoader();
alert("No Internet Connection","Let's get connected to see feeds");
web.setVisibility(View.GONE);
NoNetwork.setVisibility(View.VISIBLE);
}
});
Try forcing the app to open links in other browsers
Intent intent= new Intent(Intent.ACTION_VIEW,Uri.parse(url));
startActivity(intent);
If it fails let me know to help more.

Web scraping with Android on page with dynamic content (JavaScript)

As a step in auto-filling some fields in a flow I need to scrape a URL that has its interesting content filled dynamically by JavaScript.
Based on a cars license plates I can look up information on a government website, set an option and a value and submit.
The resulting page will hold the desired content in different tabs so I'll also have to navigate those. (Sorry cant give direct link to this but selecting "Registrerings­nummer", using "YN28579" as the value and pressing "Søg" will take you to the page.)
I've done this with a WebViewClient in another Activity so it is possible to navigate the website directly on the android phone/tablet. But in this other Activity I don't want to display the resulting page just scrape some of the data items.
Here is how I've done it with the WebViewClient:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
((Button)findViewById(R.id.btnBack)).setVisibility(View.VISIBLE);
wv = (WebView) findViewById(R.id.wv);
reg = getIntent().getStringExtra("reg");
wv.getSettings().setJavaScriptEnabled(true);
wv.setWebViewClient(new WebViewClient() {
private ProgressDialog pd;
private int count = 0;
#Override
public void onPageFinished(WebView view, String url) {
if (count==1) {
view.loadUrl("javascript:document.getElementById('regnr').checked=true;"
+"document.getElementById('soegeord').value='"+reg+"';"
+"document.getElementById('searchForm').submit();"
+"DMR.WaitForLoad.on();");
} else if (count>=2) {
view.loadUrl("javascript:document.body.innerHTML " +
"= '<div class=\"tabNav\">'+document.getElementsByClassName('tabNav')[0].innerHTML+'</div>';" +
"document.getElementsByClassName('h-tab-content')[0].style.width='320px';" +
"document.getElementsByClassName('h-tab-btns')[0].style.width='320px';" +
"document.getElementsByClassName('h-tab-btns')[0].style.height='45px';" +
"document.getElementsByTagName('ul')[0].style.display='inline';" +
"document.head.appendChild='<meta name=\"viewport\" content=\"width=device-width\">';" +
"document.body.style.minWidth ='300px';");
if (pd!=null) {
pd.dismiss();
}
view.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (pd==null || !pd.isShowing()) {
pd = ProgressDialog.show(SkatActivity.this, "cars.dk", "Vent venligst...", true, false);
}
count++;
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
wv.loadUrl("https://motorregister.skat.dk/dmr-front/appmanager/skat/dmr?_nfpb=true&_nfpb=true&_pageLabel=vis_koeretoej_side&_nfls=false");
}
I can't seem to figure out how to incorporate this in
Do you set the WebView as invisible? Found this question that seems to be working along those same lines, but I can't figure out how to get the working WebViewClient hidden but usable inside this other activity?

Android - webview opens extra activity

I have a android app, in which the main activity calls a function from a external library, which then opens a webview if neccesary.
Opening the webview is no problem. My problem start when people/users close the webview. It appears that the webview (I think, I am not sure though) has opened an extra activity or something on top of the original app that called the external library.
Now users have to close 2 windows, before they can continue in the original app.
Does anyone have experience with this, or knows what's happening here?
MainActivity
public class MainActivity extends Activity
{
private final String appKey = "Android.Lib.Test";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
externalLib.Initialize(this, getIntent(), appKey);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
External Lib
public class externalLib
{
private static final String TAG = "externalLib";
private static int messageId;
public static void Initialize(Context context, Intent intent, String newAppKey)
{
Log.d(TAG, "initializing");
APPKEY = newAppKey;
if(intent.hasExtra("url"))
{
if(intent.getExtras().getString("url") != null)
{
Intent webViewIntent = new Intent(context, externalLibWebView.class);
webViewIntent.putExtra("url", intent.getExtras().getString("url"));
context.startActivity(webViewIntent);
}
}
if(intent.hasExtra("messageId"))
{
messageId = intent.getExtras().getInt("messageId");
Log.e(TAG, "messageId: " + messageId);
}
else
{
messageId = 0;
}
}
}
I found out what the problems was. I wanted the webview to load the url, but instead, the browser was opened leaving the webview empty and thus "creating" the extra acitvity. Now the webview loads the url.

Categories