android.webkit.URLUtil Java Examples

The following examples show how to use android.webkit.URLUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebRtcPhone.java    From Yahala-Messenger with MIT License 6 votes vote down vote up
private boolean validateUrl(String url) {

        if (URLUtil.isHttpsUrl(url) || URLUtil.isHttpUrl(url)) {
            return true;
        }

        FileLog.e(TAG + ": " + ApplicationLoader.applicationContext.getText(R.string.invalid_url_title), ApplicationLoader.applicationContext.getString(R.string.invalid_url_text, url));

        /* new AlertDialog.Builder(this)
        .setTitle(getText(R.string.invalid_url_title))
        .setMessage(getString(R.string.invalid_url_text, url))
        .setCancelable(false)
        .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
              dialog.cancel();
            }
          }).create().show();*/

        return false;
    }
 
Example #2
Source File: GeneralSettingsFragment.java    From JumpGo with Mozilla Public License 2.0 6 votes vote down vote up
private void homePicker() {
    String currentHomepage;
    mHomepage = mPreferenceManager.getHomepage();
    if (!URLUtil.isAboutUrl(mHomepage)) {
        currentHomepage = mHomepage;
    } else {
        currentHomepage = "https://www.google.com";
    }

    BrowserDialog.showEditText(mActivity,
        R.string.title_custom_homepage,
        R.string.title_custom_homepage,
        currentHomepage,
        R.string.action_ok,
        new BrowserDialog.EditorListener() {
            @Override
            public void onClick(String text) {
                mPreferenceManager.setHomepage(text);
                home.setSummary(text);
            }
        });
}
 
Example #3
Source File: DownloadRequester.java    From AntennaPodSP with MIT License 6 votes vote down vote up
public String getMediafilename(FeedMedia media) {
    String filename;
    String titleBaseFilename = "";

    // Try to generate the filename by the item title
    if (media.getItem() != null && media.getItem().getTitle() != null) {
        String title = media.getItem().getTitle();
        // Delete reserved characters
        titleBaseFilename = title.replaceAll("[\\\\/%\\?\\*:|<>\"\\p{Cntrl}]", "");
        titleBaseFilename = titleBaseFilename.trim();
    }

    String URLBaseFilename = URLUtil.guessFileName(media.getDownload_url(),
            null, media.getMime_type());
    ;

    if (titleBaseFilename != "") {
        // Append extension
        filename = titleBaseFilename + FilenameUtils.EXTENSION_SEPARATOR +
                FilenameUtils.getExtension(URLBaseFilename);
    } else {
        // Fall back on URL file name
        filename = URLBaseFilename;
    }
    return filename;
}
 
Example #4
Source File: WindowViewModel.java    From FirefoxReality with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void onChanged(ObservableBoolean o) {
    String aUrl = url.getValue().toString();
    isUrlBarButtonsVisible.postValue(new ObservableBoolean(
            !isFocused.getValue().get() &&
                    !isLibraryVisible.getValue().get() &&
                    !UrlUtils.isContentFeed(getApplication(), aUrl) &&
                    !UrlUtils.isPrivateAboutPage(getApplication(), aUrl) &&
                    (URLUtil.isHttpUrl(aUrl) || URLUtil.isHttpsUrl(aUrl)) &&
                    (
                            (SettingsStore.getInstance(getApplication()).getTrackingProtectionLevel() != ContentBlocking.EtpLevel.NONE) ||
                            isPopUpAvailable.getValue().get() ||
                            isDrmUsed.getValue().get() ||
                            isWebXRUsed.getValue().get()
                    )
    ));
}
 
Example #5
Source File: QQVideoDetailPresenter.java    From NewFastFrame with Apache License 2.0 6 votes vote down vote up
private Observable<String> getDetailDataForTwo(String url) {
    return Observable.just(url).subscribeOn(Schedulers.io())
            .flatMap(new Function<String, ObservableSource<String>>() {
                @Override
                public ObservableSource<String> apply(String s) throws Exception {
                    StringBuilder stringBuilder = new StringBuilder("http://all.baiyug.cn:2021/QQQ/index.php").append("?url=")
                            .append(s);
                    Document document = Jsoup.connect(stringBuilder.toString()).header("Referer", "http://app.baiyug.cn").get();
                    String content = document.outerHtml();
                    String start = "url:";
                    int startIndex = content.indexOf(start);
                    String end = "pic: pic";
                    String url1 = content.substring(startIndex + start.length(), content.lastIndexOf(end)).trim();
                    String realUrl = url1.substring(1, url1.length() - 2);
                    if (URLUtil.isValidUrl(realUrl)) {
                        return Observable.just(realUrl);
                    } else {
                        return getDetailDataForThree(url);
                    }
                }
            });
}
 
Example #6
Source File: QQVideoDetailPresenter.java    From NewFastFrame with Apache License 2.0 6 votes vote down vote up
public Observable<String> getDetailDataForFour(String url) {
    return Observable.just(url).subscribeOn(Schedulers.io())
            .flatMap((Function<String, ObservableSource<String>>) s -> {
                StringBuilder stringBuilder = new StringBuilder("http://all.baiyug.cn:2021/QQ/index.php").append("?url=")
                        .append(s);
                Document document = Jsoup.connect(stringBuilder.toString()).header("Referer", "http://app.baiyug.cn").get();
                String content = document.outerHtml();
                String start = "url:";
                int startIndex = content.indexOf(start);
                String end = "pic: pic";
                String url1 = content.substring(startIndex + start.length(), content.lastIndexOf(end)).trim();
                String realUrl = url1.substring(1, url1.length() - 2);
                if (URLUtil.isValidUrl(realUrl)) {
                    return Observable.just(realUrl);
                } else {
                    return getDetailDataForThree(url);
                }
            });
}
 
Example #7
Source File: UriBeacon.java    From EFRConnect-android with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the Uri string with embedded expansion codes.
 *
 * @param uri to be encoded
 * @return the Uri string with expansion codes.
 */
public static byte[] encodeUri(String uri) {
    if (uri.length() == 0) {
        return new byte[0];
    }
    ByteBuffer bb = ByteBuffer.allocate(uri.length());
    // UUIDs are ordered as byte array, which means most significant first
    bb.order(ByteOrder.BIG_ENDIAN);
    int position = 0;

    // Add the byte code for the scheme or return null if none
    Byte schemeCode = encodeUriScheme(uri);
    if (schemeCode == null) {
        return null;
    }
    String scheme = URI_SCHEMES.get(schemeCode);
    bb.put(schemeCode);
    position += scheme.length();

    if (URLUtil.isNetworkUrl(scheme)) {
        return encodeUrl(uri, position, bb);
    } else if ("urn:uuid:".equals(scheme)) {
        return encodeUrnUuid(uri, position, bb);
    }
    return null;
}
 
Example #8
Source File: ArticleInfoDetailFragment.java    From travelguide with Apache License 2.0 6 votes vote down vote up
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
  if (URLUtil.isNetworkUrl(url))
  {
    final Intent i = new Intent(Intent.ACTION_VIEW);
    i.setData(Uri.parse(url));
    if (getActivity().getPackageManager().resolveActivity(i, 0) != null)
      startActivity(i);

    return true;
  }
  else if (url.startsWith("mapswithme://"))
  {
    final PendingIntent pi = ArticleInfoListActivity.createPendingIntent(getActivity());

    // TODO: Decided to use 11 as default scale, but MapsWithMe has bug with scales,
    // so do pass 13 as a compromise.
    MapsWithMeApi.showMapsWithMeUrl(getActivity(), pi, 13, url);

    return true;
  }

  return super.shouldOverrideUrlLoading(view, url);
}
 
Example #9
Source File: ArticleInfoDetailFragment.java    From travelguide with Apache License 2.0 6 votes vote down vote up
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
  super.onPageStarted(view, url, favicon);

  // Fix java.lang.NullPointerException at:
  // android.view.animation.AnimationUtils.loadAnimation(AnimationUtils.java:71)
  final Context context = getActivity();
  if (shouldAnimate(url, context))
  {
    Utils.fadeOut(context, mWebView);
    Utils.fadeIn(context, mProgressContainer);
  }

  if (URLUtil.isFileUrl(url) && url.endsWith(".html"))
  {
    final String strippedUrl = url.substring(url.lastIndexOf('/') + 1, url.lastIndexOf('.'));
    mTitle.setText(getStorage().getArticleInfoByUrl(strippedUrl).getName());
  }
}
 
Example #10
Source File: WebViewDiscoverFragment.java    From edx-app-android with Apache License 2.0 6 votes vote down vote up
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    setWebViewActionListener();
    // Check for search query in extras
    String searchQueryExtra = null;
    String searchUrl = null;

    if (savedInstanceState != null) {
        searchUrl = savedInstanceState.getString(INSTANCE_CURRENT_DISCOVER_URL, null);
    }
    if (searchUrl == null && getArguments() != null) {
        searchQueryExtra = getArguments().getString(Router.EXTRA_SEARCH_QUERY);
    }

    if (searchQueryExtra != null) {
        initSearch(searchQueryExtra);
    } else {
        loadUrl(searchUrl == null || !URLUtil.isValidUrl(searchUrl) ? getInitialUrl() : searchUrl);
    }
    if (!EventBus.getDefault().isRegistered(this)) {
        EventBus.getDefault().register(this);
    }
}
 
Example #11
Source File: AboutAdapter.java    From wallpaperboard with Apache License 2.0 6 votes vote down vote up
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    if (holder.getItemViewType() == TYPE_HEADER) {
        HeaderViewHolder headerViewHolder = (HeaderViewHolder) holder;
        String imageUri = mContext.getString(R.string.about_image);

        if (ColorHelper.isValidColor(imageUri)) {
            headerViewHolder.image.setBackgroundColor(Color.parseColor(imageUri));
        } else if (!URLUtil.isValidUrl(imageUri)) {
            imageUri = "drawable://" + DrawableHelper.getResourceId(mContext, imageUri);
            ImageLoader.getInstance().displayImage(imageUri, headerViewHolder.image,
                    ImageConfig.getDefaultImageOptions());
        } else {
            ImageLoader.getInstance().displayImage(imageUri, headerViewHolder.image,
                    ImageConfig.getDefaultImageOptions());
        }

        String profileUri = mContext.getResources().getString(R.string.about_profile_image);
        if (!URLUtil.isValidUrl(profileUri)) {
            profileUri = "drawable://" + DrawableHelper.getResourceId(mContext, profileUri);
        }

        ImageLoader.getInstance().displayImage(profileUri, headerViewHolder.profile,
                ImageConfig.getDefaultImageOptions());
    }
}
 
Example #12
Source File: LightningWebClient.java    From Xndroid with GNU General Public License v3.0 6 votes vote down vote up
private boolean shouldOverrideLoading(@NonNull WebView view, @NonNull String url) {
    // Check if configured proxy is available
    if (!mProxyUtils.isProxyReady(mActivity)) {
        // User has been notified
        return true;
    }

    Map<String, String> headers = mLightningView.getRequestHeaders();

    if (mLightningView.isIncognito()) {
        // If we are in incognito, immediately load, we don't want the url to leave the app
        return continueLoadingUrl(view, url, headers);
    }
    if (URLUtil.isAboutUrl(url)) {
        // If this is an about page, immediately load, we don't need to leave the app
        return continueLoadingUrl(view, url, headers);
    }

    if (isMailOrIntent(url, view) || mIntentUtils.startActivityForUrl(view, url)) {
        // If it was a mailto: link, or an intent, or could be launched elsewhere, do that
        return true;
    }

    // If none of the special conditions was met, continue with loading the url
    return continueLoadingUrl(view, url, headers);
}
 
Example #13
Source File: GeneralSettingsFragment.java    From Xndroid with GNU General Public License v3.0 6 votes vote down vote up
private void homePicker() {
    String currentHomepage;
    mHomepage = mPreferenceManager.getHomepage();
    if (!URLUtil.isAboutUrl(mHomepage)) {
        currentHomepage = mHomepage;
    } else {
        currentHomepage = "https://www.google.com";
    }

    BrowserDialog.showEditText(mActivity,
        R.string.title_custom_homepage,
        R.string.title_custom_homepage,
        currentHomepage,
        R.string.action_ok,
        new BrowserDialog.EditorListener() {
            @Override
            public void onClick(String text) {
                mPreferenceManager.setHomepage(text);
                home.setSummary(text);
            }
        });
}
 
Example #14
Source File: ParserUtils.java    From Android-nRF-Beacon-for-Eddystone with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static String decodeUri(final byte[] serviceData, final int start, final int length) {
    if (start < 0 || serviceData.length < start + length)
        return null;

    final StringBuilder uriBuilder = new StringBuilder();
    int offset = 0;
    if (offset < length) {
        byte b = serviceData[start + offset++];
        String scheme = URI_SCHEMES.get(b);
        if (scheme != null) {
            uriBuilder.append(scheme);
            if (URLUtil.isNetworkUrl(scheme)) {
                return decodeUrl(serviceData, start + offset, length - 1, uriBuilder);
            } else if ("urn:uuid:".equals(scheme)) {
                return decodeUrnUuid(serviceData, start + offset, uriBuilder);
            }
        }
        Log.w(TAG, "decodeUri unknown Uri scheme code=" + b);
    }
    return null;
}
 
Example #15
Source File: DialogFragmentAddMediaItem.java    From uPods-android with Apache License 2.0 6 votes vote down vote up
private boolean saveMediaItem() {
    if (etMediaName.getText().toString().length() < MIN_TITLE_LENGTH) {
        Toast.makeText(getActivity(), getString(R.string.title_too_short), Toast.LENGTH_SHORT).show();
        return false;
    } else if (!URLUtil.isValidUrl(etMediaUrl.getText().toString())) {
        Toast.makeText(getActivity(), getString(R.string.url_not_correct), Toast.LENGTH_SHORT).show();
        return false;
    }

    if (mediaItemType == MediaItemType.RADIO) {
        StreamUrl streamUrl = new StreamUrl(etMediaUrl.getText().toString());
        RadioItem radioItem = new RadioItem(etMediaName.getText().toString(), streamUrl, "");
        ProfileManager.getInstance().addSubscribedMediaItem(radioItem);
        Toast.makeText(getActivity(), getString(R.string.radio_added), Toast.LENGTH_SHORT).show();
    } else if (mediaItemType == MediaItemType.PODCAST) {
        Podcast podcast = new Podcast(etMediaName.getText().toString(), etMediaUrl.getText().toString());
        ProfileManager.getInstance().addSubscribedMediaItem(podcast);
        Toast.makeText(getActivity(), getString(R.string.podcast_added), Toast.LENGTH_SHORT).show();
    }
    return true;
}
 
Example #16
Source File: ActionFactory.java    From android-sdk with MIT License 6 votes vote down vote up
/**
 * Gets URL parameter from JSON and validates it.
 *
 * @param jsonElement - JsonElement that contains the url string.
 * @param messageType - Message type.
 * @return - Returns the verified URI string. If not valid or empty will return an empty string.
 */
public static String getUriFromJson(JsonElement jsonElement, int messageType) {
    String urlToCheck = jsonElement == null || jsonElement.isJsonNull() ? "" : jsonElement.getAsString();
    String returnUrl = "";

    //we allow deep links for in app actions and URL messages; we enforce valid network URLs
    // for the visit website action
    if ((messageType == ServerType.IN_APP && validatedUrl(urlToCheck))
            || (messageType == ServerType.URL_MESSAGE && validatedUrl(urlToCheck))
            || URLUtil.isNetworkUrl(urlToCheck)) {
        returnUrl = urlToCheck;
    }

    if (returnUrl.isEmpty()) {
        Logger.log.logError("URL is invalid, please change in the campaign settings.");
    }

    return returnUrl;
}
 
Example #17
Source File: MainActivity.java    From HtmlNative with Apache License 2.0 6 votes vote down vote up
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.layout_example:
            Intent i = new Intent(this, ExampleListActivity.class);
            startActivity(i);
            break;

        case R.id.about:
            Intent ii = new Intent(this, TestActivity.class);
            startActivity(ii);
            break;

        case R.id.main_in_webview:
            String url = mSearch.getText().toString();
            if (URLUtil.isValidUrl(url)) {
                Intent intent = new Intent(this, WebViewActivity.class);
                intent.putExtra(EXTAL_URL, url);
                startActivity(intent);
            } else {
                Toast.makeText(this, "not valid url", Toast.LENGTH_LONG).show();
            }
            break;
    }
    return super.onOptionsItemSelected(item);
}
 
Example #18
Source File: ConnectActivity.java    From Yahala-Messenger with MIT License 6 votes vote down vote up
private boolean validateUrl(String url) {
     if (URLUtil.isHttpsUrl(url) || URLUtil.isHttpUrl(url)) {
         return true;
     }
     FileLog.e(TAG + ": " + getText(R.string.invalid_url_title), getString(R.string.invalid_url_text, url));
/* new AlertDialog.Builder(this)
     .setTitle(getText(R.string.invalid_url_title))
     .setMessage(getString(R.string.invalid_url_text, url))
     .setCancelable(false)
     .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int id) {
           dialog.cancel();
         }
       }).create().show();*/
     return false;
 }
 
Example #19
Source File: NinjaDownloadListener.java    From Ninja with Apache License 2.0 6 votes vote down vote up
@Override
public void onDownloadStart(final String url, String userAgent, final String contentDisposition, final String mimeType, long contentLength) {
    final Context holder = IntentUnit.getContext();
    if (holder == null || !(holder instanceof Activity)) {
        BrowserUnit.download(context, url, contentDisposition, mimeType);
        return;
    }

    AlertDialog.Builder builder = new AlertDialog.Builder(holder);
    builder.setCancelable(false);

    builder.setTitle(R.string.dialog_title_download);
    builder.setMessage(URLUtil.guessFileName(url, contentDisposition, mimeType));

    builder.setPositiveButton(R.string.dialog_button_positive, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            BrowserUnit.download(holder, url, contentDisposition, mimeType);
        }
    });

    builder.setNegativeButton(R.string.dialog_button_negative, null);
    builder.create().show();
}
 
Example #20
Source File: UrlUtils.java    From Xndroid with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Attempts to determine whether user input is a URL or search
 * terms.  Anything with a space is passed to search if canBeSearch is true.
 * <p/>
 * Converts to lowercase any mistakenly uppercased schema (i.e.,
 * "Http://" converts to "http://"
 *
 * @param canBeSearch If true, will return a search url if it isn't a valid
 *                    URL. If false, invalid URLs will return null
 * @return Original or modified URL
 */
@NonNull
public static String smartUrlFilter(@NonNull String url, boolean canBeSearch, String searchUrl) {
    String inUrl = url.trim();
    boolean hasSpace = inUrl.indexOf(' ') != -1;
    Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
    if (matcher.matches()) {
        // force scheme to lowercase
        String scheme = matcher.group(1);
        String lcScheme = scheme.toLowerCase();
        if (!lcScheme.equals(scheme)) {
            inUrl = lcScheme + matcher.group(2);
        }
        if (hasSpace && Patterns.WEB_URL.matcher(inUrl).matches()) {
            inUrl = inUrl.replace(" ", "%20");
        }
        return inUrl;
    }
    if (!hasSpace) {
        if (Patterns.WEB_URL.matcher(inUrl).matches()) {
            return URLUtil.guessUrl(inUrl);
        }
    }
    if (canBeSearch) {
        return URLUtil.composeSearchUrl(inUrl,
            searchUrl, QUERY_PLACE_HOLDER);
    }
    return "";
}
 
Example #21
Source File: CreditsAdapter.java    From candybar with Apache License 2.0 5 votes vote down vote up
@Override
public View getView(int position, View view, ViewGroup viewGroup) {
    ViewHolder holder;
    if (view == null) {
        view = View.inflate(mContext, R.layout.fragment_credits_item_list, null);
        holder = new ViewHolder(view);
        view.setTag(holder);
    } else {
        holder = (ViewHolder) view.getTag();
    }

    Credit credit = mCredits.get(position);
    holder.title.setText(credit.getName());
    holder.subtitle.setText(credit.getContribution());
    holder.container.setOnClickListener(view1 -> {
        String link = credit.getLink();
        if (URLUtil.isValidUrl(link)) {
            try {
                mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(link)));
            } catch (ActivityNotFoundException e) {
                LogUtil.e(Log.getStackTraceString(e));
            }
        }
    });

    if (credit.getContribution().length() == 0) {
        holder.subtitle.setVisibility(View.GONE);
    } else {
        holder.subtitle.setVisibility(View.VISIBLE);
    }

    ImageLoader.getInstance().displayImage(credit.getImage(),
            new ImageViewAware(holder.image), mOptions.build(),
            new ImageSize(144, 144), null, null);
    return view;
}
 
Example #22
Source File: CreditsAdapter.java    From wallpaperboard with Apache License 2.0 5 votes vote down vote up
@Override
public View getView(int position, View view, ViewGroup viewGroup) {
    ViewHolder holder;
    if (view == null) {
        view = View.inflate(mContext, R.layout.fragment_credits_item_list, null);
        holder = new ViewHolder(view);
        view.setTag(holder);
    } else {
        holder = (ViewHolder) view.getTag();
    }

    Credit credit = mCredits.get(position);
    holder.title.setText(credit.getName());
    holder.subtitle.setText(credit.getContribution());
    holder.container.setOnClickListener(view1 -> {
        String link = credit.getLink();
        if (URLUtil.isValidUrl(link)) {
            try {
                mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(link)));
            } catch (ActivityNotFoundException e) {
                LogUtil.e(Log.getStackTraceString(e));
            }
        }
    });

    if (credit.getContribution().length() == 0) {
        holder.subtitle.setVisibility(View.GONE);
    } else {
        holder.subtitle.setVisibility(View.VISIBLE);
    }

    ImageLoader.getInstance().displayImage(credit.getImage(),
            new ImageViewAware(holder.image), mOptions.build(),
            new ImageSize(144, 144), null, null);
    return view;
}
 
Example #23
Source File: DownloadIGTVFragment.java    From Instagram-Profile-Downloader with MIT License 5 votes vote down vote up
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.activity_download_igtv_from_url, container, false);


    download = view.findViewById(R.id.download);
    url = view.findViewById(R.id.edt_url);
    adContainer = view.findViewById(R.id.adContainer);
    open_instagram = view.findViewById(R.id.open_instagram);
    showBannerAd();
    download.setOnClickListener(v -> {

        if (TextUtils.isEmpty(url.getText().toString())) {
            ToastUtils.ErrorToast(context, "Url field can't be empty");
        } else if (!URLUtil.isValidUrl(url.getText().toString())) {
            ToastUtils.ErrorToast(context, "Url is not valid url");
        } else if (checkURL(url.getText().toString())) {

            new ValidateFileFromURL().execute(url.getText().toString());
        } else {
            ToastUtils.ErrorToast(context, "Url is not valid url");
        }


    });

    open_instagram.setOnClickListener(v -> {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("https://www.instagram.com/explore/tags/igtv/"));
        startActivity(intent);

    });


    return view;
}
 
Example #24
Source File: DownloadPostFragment.java    From Instagram-Profile-Downloader with MIT License 5 votes vote down vote up
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.activity_download_from_url, container, false);
    context = getActivity();
    download = view.findViewById(R.id.download);
    edt_url = view.findViewById(R.id.edt_url);
    adContainer = view.findViewById(R.id.adContainer);
    open_instagram = view.findViewById(R.id.open_instagram);
    showBannerAd();
    download.setOnClickListener(v -> {

        if (TextUtils.isEmpty(edt_url.getText().toString())) {
            ToastUtils.ErrorToast(context, "Url field can't be empty");
        } else if (!URLUtil.isValidUrl(edt_url.getText().toString())) {
            ToastUtils.ErrorToast(context, "Url is not valid url");
        } else if (checkURL(edt_url.getText().toString())) {
            new ValidateFileFromURL().execute(edt_url.getText().toString());
        } else {
            ToastUtils.ErrorToast(context, "Url is not valid url");
        }


    });

    open_instagram.setOnClickListener(v -> {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("https://www.instagram.com/"));
        startActivity(intent);

    });

    return view;
}
 
Example #25
Source File: OtherAppsAdapter.java    From candybar with Apache License 2.0 5 votes vote down vote up
@Override
public View getView(int position, View view, ViewGroup viewGroup) {
    ViewHolder holder;
    if (view == null) {
        view = View.inflate(mContext, R.layout.fragment_other_apps_item_list, null);
        holder = new ViewHolder(view);
        view.setTag(holder);
    } else {
        holder = (ViewHolder) view.getTag();
    }

    CandyBarApplication.OtherApp otherApp = mOtherApps.get(position);
    String uri = otherApp.getIcon();
    if (!URLUtil.isValidUrl(uri)) {
        uri = "drawable://" + DrawableHelper.getResourceId(mContext, uri);
    }

    ImageLoader.getInstance().displayImage(
            uri, holder.image, ImageConfig.getDefaultImageOptions(true));
    holder.title.setText(otherApp.getTitle());

    if (otherApp.getDescription() == null || otherApp.getDescription().length() == 0) {
        holder.desc.setVisibility(View.GONE);
    } else {
        holder.desc.setText(otherApp.getDescription());
        holder.desc.setVisibility(View.VISIBLE);
    }

    holder.container.setOnClickListener(v -> {
        if (!URLUtil.isValidUrl(otherApp.getUrl())) return;

        try {
            mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(otherApp.getUrl())));
        } catch (ActivityNotFoundException e) {
            LogUtil.e(Log.getStackTraceString(e));
        }
    });
    return view;
}
 
Example #26
Source File: Downloader.java    From Zom-Android-XMPP with GNU General Public License v3.0 5 votes vote down vote up
private String getFilenameFromUrl(String urlString) {
    String fileName = URLUtil.guessFileName(urlString, null, null);

    if (fileName.contains("#"))
        return fileName.split("#")[0];
    else if (fileName.contains("?"))
        return fileName.split("\\?")[0];
    else
        return fileName;

}
 
Example #27
Source File: FragmentVideoPlayer.java    From uPods-android with Apache License 2.0 5 votes vote down vote up
private void createPlayer() {
    releasePlayer();
    String videoLink = UniversalPlayer.getInstance().getPlayingMediaItem().getAudeoLink();
    try {
        Logger.printInfo(TAG, "Trying to play video: " + videoLink);

        ArrayList<String> options = new ArrayList<String>();
        options.add("--aout=opensles");
        options.add("--audio-time-stretch"); // time stretching
        options.add("-vvv"); // verbosity
        libvlc = new LibVLC(options);
        shVideoHolder.setKeepScreenOn(true);

        // Create media player
        mMediaPlayer = new MediaPlayer(libvlc);
        mMediaPlayer.setEventListener(this);

        // Set up video output
        final IVLCVout vout = mMediaPlayer.getVLCVout();
        vout.setVideoView(sfVideo);
        vout.addCallback(this);
        vout.attachViews();

        Media m = URLUtil.isValidUrl(videoLink) ? new Media(libvlc, Uri.parse(videoLink)) : new Media(libvlc, videoLink);
        mMediaPlayer.setMedia(m);
        mMediaPlayer.play();
    } catch (Exception e) {
        Logger.printInfo(TAG, "Error creating video player: ");
        e.printStackTrace();
        if (onPlayingFailedCallback != null) {
            onPlayingFailedCallback.operationFinished();
        }
    }
}
 
Example #28
Source File: WallpaperHelper.java    From candybar-library with Apache License 2.0 5 votes vote down vote up
public static int getWallpaperType(@NonNull Context context) {
    String url = context.getResources().getString(R.string.wallpaper_json);
    if (URLUtil.isValidUrl(url)) {
        return CLOUD_WALLPAPERS;
    } else if (url.length() > 0) {
        return EXTERNAL_APP;
    }
    return UNKNOWN;
}
 
Example #29
Source File: UrlHelper.java    From candybar-library with Apache License 2.0 5 votes vote down vote up
public static Type getType(String url) {
    if (url == null) return Type.INVALID;
    if (!URLUtil.isValidUrl(url)) {
        if (Patterns.EMAIL_ADDRESS.matcher(url).matches()) {
            return Type.EMAIL;
        }
        return Type.INVALID;
    }

    if (url.contains("behance.")) {
        return Type.BEHANCE;
    } else if (url.contains("dribbble.")) {
        return Type.DRIBBBLE;
    } else if (url.contains("facebook.")) {
        return Type.FACEBOOK;
    } else if (url.contains("github.")) {
        return Type.GITHUB;
    } else if (url.contains("plus.google.")) {
        return Type.GOOGLE_PLUS;
    } else if (url.contains("instagram.")) {
        return Type.INSTAGRAM;
    } else if (url.contains("pinterest.")) {
        return Type.PINTEREST;
    } else if (url.contains("twitter.")) {
        return Type.TWITTER;
    } else {
        return Type.UNKNOWN;
    }
}
 
Example #30
Source File: IntentPlayer.java    From intent_radio with MIT License 5 votes vote down vote up
public int play_launch(String url)
{
   log("Launching: ", url);

   launch_url = null;
   if ( ! URLUtil.isValidUrl(url) )
   {
      toast("Invalid URL.");
      return stop();
   }

   launch_url = url;

   // Note:  Because of the way we handle network connectivity, the player
   // always stops and then restarts as we move between network types.
   // Therefore, stop() and start() are always called.  So we always have
   // the WiFi lock if we're on WiFi and we need it, and don't otherwise.
   // 
   // Here, we could be holding a WiFi lock because the playlist URL was a
   // network URL, but perhaps now the launch URL is not.  Or the other way
   // around.  So release the WiFi lock (if it's being held) and reaquire
   // it, if necessary.
   WifiLocker.unlock();
   if ( isNetworkUrl(url) )
      WifiLocker.lock(context, app_name_long);

   try
   {
      player.setVolume(1.0f, 1.0f);
      player.setDataSource(context, Uri.parse(url));
      player.prepareAsync();
   }
   catch (Exception e)
      { return stop(); }

   start_buffering();
   return done(State.STATE_BUFFER);
}