无法点击WebView片段中的插页式广告

时间:2017-09-12 10:05:09

标签: android android-fragments webview admob

我制作了一个AdvanceWebView应用程序。

因为我已经制作了一个功能,可以在#34; fragmentActivity"中显示interstitialAd,这意味着每当我从该webview下载某些内容时,广告就会显示,但它无法点击。

我认为我的广告正在展示该片段或类似的东西或者其他一些问题。 当Vedio广告出现时,该广告的倒计时也不会消失。

我可以看到广告,但它无法点击,如果我点击广告的任何部分,Logcat
正在显示这个=> " I / HwSecImmHelper:mSecurityInputMethodService为null"

这是我的代码的一部分:

WebfragmentActivy:

public class WebFragment extends Fragment implements AdvancedWebView.Listener, SwipeRefreshLayout.OnRefreshListener{

        //Layouts
        public FrameLayout rl;
        public AdvancedWebView browser;
        public SwipeRefreshLayout swipeLayout;
        public ProgressBar progressBar;

        //WebView Clients
        public WebToAppChromeClient chromeClient;
        public WebToAppWebClient webClient;

        //WebView Session
        public String mainUrl = null;
        static String URL = "url";
        public int firstLoad = 0;

        //Keep track of the interstitials we show
        private int interstitialCount = -1;

        public WebFragment() {
            // Required empty public constructor
        }



        public static WebFragment newInstance(String url) {
            WebFragment fragment = new WebFragment();
            Bundle args = new Bundle();
            args.putString(URL, url);
            fragment.setArguments(args);
            return fragment;
        }

        public void setBaseUrl(String url){
            this.mainUrl = url;
            browser.loadUrl(mainUrl);
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (getArguments() != null && mainUrl == null) {
                mainUrl = getArguments().getString(URL);
                firstLoad = 0;
            }
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            rl = (FrameLayout) inflater.inflate(R.layout.fragment_observable_web_view, container,
                    false);

            progressBar = (ProgressBar) rl.findViewById(R.id.progressbar);
            browser = (AdvancedWebView) rl.findViewById(R.id.scrollable);
            swipeLayout = (SwipeRefreshLayout) rl.findViewById(R.id.swipe_container);

            return rl;
        }

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);

            if (Config.PULL_TO_REFRESH)
                swipeLayout.setOnRefreshListener(this);
            else
                swipeLayout.setEnabled(false);

            // Setting the webview listeners
            browser.setListener(this, this);

            // set javascript and zoom and some other settings
            browser.requestFocus();
            browser.getSettings().setJavaScriptEnabled(true);
            browser.getSettings().setBuiltInZoomControls(false);
            browser.getSettings().setAppCacheEnabled(true);
            browser.getSettings().setDatabaseEnabled(true);
            browser.getSettings().setDomStorageEnabled(true);
            // Below required for geolocation
            browser.setGeolocationEnabled(true);
            // 3RD party plugins (on older devices)
            browser.getSettings().setPluginState(PluginState.ON);

            if (Config.MULTI_WINDOWS) {
                browser.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
                browser.getSettings().setSupportMultipleWindows(true);
            }

            webClient = new WebToAppWebClient(getActivity(), browser);
            browser.setWebViewClient(webClient);

            chromeClient = new WebToAppChromeClient(getActivity(), rl, browser, swipeLayout, progressBar);
            browser.setWebChromeClient(chromeClient);

            // load url (if connection available
            if (webClient.hasConnectivity(mainUrl, true)) {
                String pushurl = ((App) getActivity().getApplication()).getPushUrl();
                if (pushurl != null){
                    browser.loadUrl(pushurl);
                } else {
                    browser.loadUrl(mainUrl);
                }

            }

        }

        @Override
        public void onRefresh() {
            browser.reload();
        }

        @SuppressLint("NewApi")
        @Override
        public void onPause() {
            super.onPause();
            browser.onPause();
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            browser.onDestroy();
        }

        @SuppressLint("NewApi")
        @Override
        public void onResume() {
            super.onResume();
            browser.onResume();
        }

        @SuppressLint("NewApi")
        @Override
        public void onDownloadRequested(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
            if (!hasPermissionToDownload(getActivity())) return;

            String filename = null;
            try {
                filename = new GetFileInfo().execute(url).get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }

            if (filename == null) {
                String fileExtenstion = MimeTypeMap.getFileExtensionFromUrl(url);
                filename = URLUtil.guessFileName(url, null, fileExtenstion);
            }


            if (AdvancedWebView.handleDownload(getActivity(), url, filename)) {
                Toast.makeText(getActivity(), getResources().getString(R.string.download_done), Toast.LENGTH_SHORT).show();
                onDownloadInterstitialAd();

            }
            else {
                Toast.makeText(getActivity(), getResources().getString(R.string.download_fail), Toast.LENGTH_SHORT).show();
            }
        }

        private static boolean hasPermissionToDownload(final Activity context) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
                    ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            == PackageManager.PERMISSION_GRANTED )
                return true;

            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setMessage(R.string.download_permission_explaination);
            builder.setPositiveButton(R.string.common_permission_grant, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // Fire off an async request to actually get the permission
                    // This will show the standard permission request dialog UI
                    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
                        context.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                }
            });
            AlertDialog dialog = builder.create();
            dialog.show();

            return false;
        }

        @Override
        public void onPageStarted(String url, Bitmap favicon) {
            if (firstLoad == 0 && MainActivity.getCollapsingActionBar()){
                ((MainActivity) getActivity()).showToolbar(this);
                firstLoad = 1;
            } else if (firstLoad == 0){
                firstLoad = 1;
            }
        }

        /**
         * Show an interstitial ad
         */
        private void onDownloadInterstitialAd(){
            final InterstitialAd mInterstitialAd = new InterstitialAd(getActivity());
            mInterstitialAd.setAdUnitId(getResources().getString(R.string.ad_interstitial_id));
            AdRequest adRequestInter = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build();
            mInterstitialAd.setAdListener(new AdListener() {
                @Override
                public void onAdLoaded() {
                    mInterstitialAd.show();
                }
            });
            mInterstitialAd.loadAd(adRequestInter);
        }

        @Override
        public void onPageFinished(String url) {
            //showInterstitial();
        }

        @Override
        public void onPageError(int errorCode, String description, String failingUrl) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onExternalPageRequest(String url) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            browser.onActivityResult(requestCode, resultCode, data);
        }
    }

这是我的主要活动:

public class MainActivity extends AppCompatActivity implements DrawerFragment.DrawerFragmentListener{

    //Views
    public Toolbar mToolbar;
    public View mHeaderView;
    public TabLayout mSlidingTabLayout;
    public SwipeableViewPager mViewPager;

    //App Navigation Structure
    private NavigationAdapter mAdapter;
    private DrawerFragment drawerFragment;

    private WebFragment CurrentAnimatingFragment = null;
    private int CurrentAnimation = 0;

    //Identify toolbar state
    private static int NO = 0;
    private static int HIDING = 1;
    private static int SHOWING = 2;

    //Keep track of the interstitials we show
    private int interstitialCount = 0;

    SharedPreferences prefs;

    public FirebaseAuth authtt;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        authtt = FirebaseAuth.getInstance();

        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mHeaderView = (View) findViewById(R.id.header_container);
        mSlidingTabLayout = (TabLayout) findViewById(R.id.tabs);
        mViewPager = (SwipeableViewPager) findViewById(R.id.pager);

        setSupportActionBar(mToolbar);

        mAdapter = new NavigationAdapter(getSupportFragmentManager(), this);

        final Intent intent = getIntent();
        final String action = intent.getAction();

        if (Intent.ACTION_VIEW.equals(action)) {
            String data = intent.getDataString();
            ((App) getApplication()).setPushUrl(data);
        }

        hasPermissionToDo(this, Config.PERMISSIONS_REQUIRED);

        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mViewPager.getLayoutParams();
        if ((Config.HIDE_ACTIONBAR && getHideTabs()) || ((Config.HIDE_ACTIONBAR || getHideTabs()) && getCollapsingActionBar())){
            lp.topMargin = 0;
        } else if ((Config.HIDE_ACTIONBAR || getHideTabs()) || (!Config.HIDE_ACTIONBAR && !getHideTabs() && getCollapsingActionBar())){
            lp.topMargin = getActionBarHeight();
        } else if (!Config.HIDE_ACTIONBAR && !getHideTabs()){
            lp.topMargin = getActionBarHeight() * 2;
        }

        if (Config.USE_DRAWER) {
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            getSupportActionBar().setLogo(R.mipmap.ic_launcher);
            getSupportActionBar().setDisplayUseLogoEnabled(true);

            drawerFragment = (DrawerFragment)
                    getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
            drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
            drawerFragment.setDrawerListener(this);
        } else {
            ((DrawerLayout) findViewById(R.id.drawer_layout)).setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        }

        mViewPager.setLayoutParams(lp);

        mViewPager.setAdapter(mAdapter);
        mViewPager.setOffscreenPageLimit(mViewPager.getAdapter().getCount() - 1);

        mSlidingTabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.accent));
        mSlidingTabLayout.setupWithViewPager(mViewPager);
        mSlidingTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (getCollapsingActionBar()) {
                    showToolbar(getFragment());
                }
                mViewPager.setCurrentItem(tab.getPosition());
                showInterstitial();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        for (int i = 0; i < mSlidingTabLayout.getTabCount(); i++) {
            if (Config.ICONS.length > i  && Config.ICONS[i] != 0) {
                mSlidingTabLayout.getTabAt(i).setIcon(Config.ICONS[i]);
            }
        }

        // admob
        if (!getResources().getString(R.string.ad_banner_id).equals("")) {
            // Look up the AdView as a resource and load a request.
            AdView adView = (AdView) findViewById(R.id.adView);
            AdRequest adRequest = new AdRequest.Builder().build();
            adView.loadAd(adRequest);
        } else {
            AdView adView = (AdView) findViewById(R.id.adView);
            adView.setVisibility(View.GONE);
        }



        // application rating
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle(getString(R.string.rate_title))
                .setMessage(String.format(getString(R.string.rate_message), getString(R.string.app_name)))
                .setPositiveButton(getString(R.string.rate_yes), null)
                .setNegativeButton(getString(R.string.rate_never), null)
                .setNeutralButton(getString(R.string.rate_later), null);

        new AppRate(this)
                .setShowIfAppHasCrashed(false)
                .setMinDaysUntilPrompt(2)
                .setMinLaunchesUntilPrompt(2)
                .setCustomDialog(builder)
                .init();

        // showing the splash screen
        if (Config.SPLASH) {
            findViewById(R.id.imageLoading1).setVisibility(View.VISIBLE);
            //getFragment().browser.setVisibility(View.GONE);
        }
    }

    // using the back button of the device
    @Override
    public void onBackPressed() {
        View customView = null;
        WebChromeClient.CustomViewCallback customViewCallback = null;
        if (getFragment().chromeClient != null) {
            customView = getFragment().chromeClient.getCustomView();
            customViewCallback = getFragment().chromeClient.getCustomViewCallback();
        }

        if ((customView == null)
                && getFragment().browser.canGoBack()) {
            getFragment().browser.goBack();
        } else if (customView != null
                && customViewCallback != null) {
            customViewCallback.onCustomViewHidden();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onPause() {

        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    public void setTitle(String title) {
        if (mAdapter != null && mAdapter.getCount() == 1 && !Config.USE_DRAWER && !Config.STATIC_TOOLBAR_TITLE)
            getSupportActionBar().setTitle(title);
    }

    public WebFragment getFragment(){
        return (WebFragment) mAdapter.getCurrentFragment();
    }

    boolean getHideTabs(){
        if (mAdapter.getCount() == 1 || Config.USE_DRAWER){
            return true;
        } else {
            return Config.HIDE_TABS;
        }
    }

    @Override
    public boolean onDrawerItemSelected(View view, int position) {
        String url = Config.URLS[position];
        if (WebToAppWebClient.urlShouldOpenExternally(url)){
            try {
                view.getContext().startActivity(
                        new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            } catch(ActivityNotFoundException e) {
                if (url.startsWith("intent://")) {
                    view.getContext().startActivity(
                            new Intent(Intent.ACTION_VIEW, Uri.parse(url.replace("intent://", "http://"))));
                } else {
                    Toast.makeText(this, getResources().getString(R.string.no_app_message), Toast.LENGTH_LONG).show();
                }
            }
            return false;
        } else {
            getFragment().browser.loadUrl("about:blank");
            getFragment().setBaseUrl(Config.URLS[position]);
            showInterstitial();
            return true;
        }
    }

    private static boolean hasPermissionToDo(final Activity context, final String[] permissions) {
        boolean oneDenied = false;
        for (String permission : permissions) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
                    ContextCompat.checkSelfPermission(context, permission)
                            != PackageManager.PERMISSION_GRANTED)
                oneDenied = true;
        }

        if (!oneDenied) return true;

        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(context);
        builder.setMessage(R.string.common_permission_explaination);
        builder.setPositiveButton(R.string.common_permission_grant, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // Fire off an async request to actually get the permission
                // This will show the standard permission request dialog UI
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
                    context.requestPermissions(permissions,1);
            }
        });
        android.support.v7.app.AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

        return false;
    }
}

0 个答案:

没有答案