У меня есть простой браузер. Мне надо чтобы в нём открывались ссылки, как например в Google Chrome. Как это реализовать. Гуглил, нужного ответа не нашёл. Да и в манифесте всё что нужно прописал, но в менюшке он не алё. Помогите пожалуйста, если кто с этим сталкивался. Заранее спасибо
public class BrowserActivity extends AppCompatActivity {
private SharedPreferences mSharedPreferences;
private static final String TAG = BrowserActivity.class.getSimpleName();
private String mCM;
private ValueCallback<Uri> mUM;
private ValueCallback<Uri[]> mUMA;
private final static int FCR=1;
SwipeRefreshLayout swipeRefreshLayout;
ProgressBar progressBar;
EditText inputUrl;
WebView webView;
ImageButton forward, back;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
super.onActivityResult(requestCode, resultCode, intent);
if(Build.VERSION.SDK_INT >= 21){
Uri[] results = null;
if(resultCode== Activity.RESULT_OK){
if(requestCode == FCR){
if(null == mUMA){
return;
}
if(intent == null){
if(mCM != null){
results = new Uri[]{Uri.parse(mCM)};
}
}else{
String dataString = intent.getDataString();
if(dataString != null){
results = new Uri[]{Uri.parse(dataString)};
}
}
}
}
mUMA.onReceiveValue(results);
mUMA = null;
}else{
if(requestCode == FCR){
if(null == mUM) return;
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
mUM.onReceiveValue(result);
mUM = null;
}
}
}
@SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(ThemeUtils.getCurrentTheme());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browser);
if(Build.VERSION.SDK_INT >=23 && (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(BrowserActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
}
progressBar = (ProgressBar) findViewById(R.id.progressBar);
webView = (WebView) findViewById(R.id.webView);
registerForContextMenu(webView);
webView.getSettings().setBuiltInZoomControls(false);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.getSettings().setGeolocationDatabasePath(getFilesDir().getPath() );
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
swipeRefreshLayout.setColorSchemeResources(
R.color.colorAccent);
webView.setWebViewClient(new WebKit());
webView.setWebChromeClient(new WebChromeClient(){
@Override
public void onProgressChanged(WebView view, int newProgress) {
progressBar.setProgress(newProgress);
if(newProgress==100)
progressBar.setVisibility(View.GONE);
else
progressBar.setVisibility(View.VISIBLE);
}
@Override
public void onPermissionRequest(final PermissionRequest request) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
request.grant(request.getResources());
}
}
@Override
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, false);
}
public boolean onShowFileChooser(
WebView webView, ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams){
if(mUMA != null){
mUMA.onReceiveValue(null);
}
mUMA = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(takePictureIntent.resolveActivity(BrowserActivity.this.getPackageManager()) != null){
File photoFile = null;
try{
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCM);
}catch(IOException ex){
Log.e(TAG, "Image file creation failed", ex);
}
if(photoFile != null){
mCM = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
}else{
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("*/*");
Intent[] intentArray;
if(takePictureIntent != null){
intentArray = new Intent[]{takePictureIntent};
}else{
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, R.string.img_chooser);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, FCR);
return true;
}
public class Callback extends WebViewClient{
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
Toast.makeText(getApplicationContext(), R.string.not_app, Toast.LENGTH_SHORT).show();
}
}
private File createImageFile() throws IOException{
@SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "img_"+timeStamp+"_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return File.createTempFile(imageFileName,".jpg",storageDir);
}
});
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
webView.reload();
}
});
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if( URLUtil.isNetworkUrl(url) ) {
return false;
}
if (appInstalledOrNot(url)) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity( intent );
} else {
}
return true;
}
private boolean appInstalledOrNot(String uri) {
PackageManager pm = getPackageManager();
try {
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
return true;
} catch (PackageManager.NameNotFoundException e) {
}
return false;
}
@Override
public void onPageFinished(WebView view, String url) {
swipeRefreshLayout.setRefreshing(false);
super.onPageFinished(view, url);
}
});
WebSettings webset = webView.getSettings();
webset.setJavaScriptEnabled(true);
webset.setAllowFileAccess(true);
if(Build.VERSION.SDK_INT >= 21){
webset.setMixedContentMode(0);
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}else if(Build.VERSION.SDK_INT >= 19){
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}else if(Build.VERSION.SDK_INT < 19){
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
CookieManager.getInstance().setAcceptCookie(false);
webView = findViewById(R.id.webView);
Intent intent = getIntent();
String search_bar = intent.getStringExtra("search_b");
webView.setBackgroundColor(Color.TRANSPARENT);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.clearFormData();
webView.getSettings().setSavePassword(true);
webView.getSettings().setSaveFormData(true);
webView.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT );
webView.clearCache(false);
if ( !isNetworkAvailable() ) {
webView.getSettings().setCacheMode( WebSettings.LOAD_CACHE_ELSE_NETWORK );
}
webView.loadUrl("https://duckduckgo.com/?q=" + search_bar);
webView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Download file");
request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimeType));
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), R.string.download_toast, Toast.LENGTH_LONG).show();
}
});
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService( CONNECTIVITY_SERVICE );
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public void onBackPressed()
{
if(webView.canGoBack()){
webView.goBack();
}else{
super.onBackPressed();
}
}
@Override
protected void onResume() {
super.onResume();
Boolean password = mSharedPreferences.getBoolean(getString(R.string.pass_t), false);
Boolean cookies = mSharedPreferences.getBoolean(getString(R.string.cookie_t), true);
Boolean cacheWeb = mSharedPreferences.getBoolean(getString(R.string.cache_t), true);
Boolean fontLarge = mSharedPreferences.getBoolean(getString(R.string.font_t), false);
Boolean supportJavaScript = mSharedPreferences.getBoolean(getString(R.string.js_t), true);
Boolean navButtons = mSharedPreferences.getBoolean(getString(R.string.nav_but_t), false);
if (password) {
webView.clearFormData();
webView.getSettings().setSavePassword(false);
webView.getSettings().setSaveFormData(false);
}
if (cookies) {
CookieManager.getInstance().setAcceptCookie(true);
}
if (cacheWeb) {
webView.getSettings().setCacheMode( WebSettings.LOAD_NO_CACHE);
webView.clearHistory();
webView.clearCache(true);
if ( !isNetworkAvailable() ) {
webView.getSettings().setCacheMode( WebSettings.LOAD_NO_CACHE );
}
}
webView.getSettings().setJavaScriptEnabled(supportJavaScript);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(supportJavaScript);
if (fontLarge) {
webView.getSettings().setDefaultFontSize(20);
}
if (navButtons) {
showNavButtons();
} else {
hideNavButtons();
}
}
void hideNavButtons() {
ImageButton mWebViewBackButton = (ImageButton) findViewById(R.id.mWebViewBackButton);
ImageButton mWebViewForwardButton = (ImageButton) findViewById(R.id.mWebViewForwardButton);
mWebViewBackButton.setVisibility(View.GONE);
mWebViewForwardButton.setVisibility(View.GONE);
}
void showNavButtons() {
ImageButton mWebViewBackButton = (ImageButton) findViewById(R.id.mWebViewBackButton);
ImageButton mWebViewForwardButton = (ImageButton) findViewById(R.id.mWebViewForwardButton);
mWebViewBackButton.setVisibility(View.VISIBLE);
mWebViewForwardButton.setVisibility(View.VISIBLE);
}
public void WebViewGoForward(View view) {
if (webView.isFocused() && webView.canGoForward()) {
webView.goForward();
}
}
public void WebViewGoBack(View view) {
if (webView.isFocused() && webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
finish();
}
}
}
Чтобы открыть ссылку, пришедшую из другого приложения, нужно взять её из интента и отдать в WebView
:
String url = getIntent().getDataString();
if (url != null) {
webView.loadUrl(url); // если есть ссылка - открываем её
} else {
webView.loadUrl(START_PAGE); // иначе открываем какую-либо стартовую страницу
}
Посмотрите статью Александра климова о WebView http://developer.alexanderklimov.ru/android/mybrowser.php
Надеюсь это вам поможет.
Айфон мало держит заряд, разбираемся с проблемой вместе с AppLab
Я получаю уведомления в панели разработчика что в приложении происходят сбои, а именно IllegalArgumentExeption на 9 Андроиде по большей части на устройствах...