Example usage for android.app Activity getWindow

List of usage examples for android.app Activity getWindow

Introduction

In this page you can find the example usage for android.app Activity getWindow.

Prototype

public Window getWindow() 

Source Link

Document

Retrieve the current android.view.Window for the activity.

Usage

From source file:android.support.v17.leanback.widget.FullWidthDetailsOverviewSharedElementHelper.java

public void setSharedElementEnterTransition(Activity activity, String sharedElementName, long timeoutMs) {
    if (activity == null && !TextUtils.isEmpty(sharedElementName)
            || activity != null && TextUtils.isEmpty(sharedElementName)) {
        throw new IllegalArgumentException();
    }/*from w w  w .ja v  a2s  .com*/
    if (activity == mActivityToRunTransition && TextUtils.equals(sharedElementName, mSharedElementName)) {
        return;
    }
    mActivityToRunTransition = activity;
    mSharedElementName = sharedElementName;
    if (DEBUG) {
        Log.d(TAG, "postponeEnterTransition " + mActivityToRunTransition);
    }
    Object transition = TransitionHelper.getSharedElementEnterTransition(activity.getWindow());
    setAutoStartSharedElementTransition(transition != null);
    ActivityCompat.postponeEnterTransition(mActivityToRunTransition);
    if (timeoutMs > 0) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (DEBUG) {
                    Log.d(TAG, "timeout " + mActivityToRunTransition);
                }
                startPostponedEnterTransitionInternal();
            }
        }, timeoutMs);
    }
}

From source file:br.ufrgs.ufrgsmapas.libs.SearchBox.java

private void revealFrom(float x, float y, Activity a, SearchBox s) {
    FrameLayout layout = (FrameLayout) a.getWindow().getDecorView().findViewById(android.R.id.content);
    RelativeLayout root = (RelativeLayout) s.findViewById(R.id.search_root);
    Resources r = getResources();
    float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 96, r.getDisplayMetrics());
    int cx = layout.getLeft() + layout.getRight();
    int cy = layout.getTop();

    int finalRadius = (int) Math.max(layout.getWidth(), px);

    SupportAnimator animator = ViewAnimationUtils.createCircularReveal(root, cx, cy, 0, finalRadius);
    animator.setInterpolator(new AccelerateDecelerateInterpolator());
    animator.setDuration(500);/*from  w ww  . j a  v  a2s  .com*/
    animator.addListener(new SupportAnimator.AnimatorListener() {

        @Override
        public void onAnimationCancel() {

        }

        @Override
        public void onAnimationEnd() {
            toggleSearch();
        }

        @Override
        public void onAnimationRepeat() {

        }

        @Override
        public void onAnimationStart() {

        }

    });
    animator.start();
}

From source file:nya.miku.wishmaster.http.cloudflare.CloudflareChecker.java

private Cookie checkAntiDDOS(final CloudflareException exception, final HttpHost proxy, CancellableTask task,
        final Activity activity) {
    synchronized (lock) {
        if (processing)
            return null;
        processing = true;//ww  w. j  ava 2s  . c o  m
    }
    processing2 = true;
    currentCookie = null;

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        CookieSyncManager.createInstance(activity);
        CookieManager.getInstance().removeAllCookie();
    } else {
        CompatibilityImpl.clearCookies(CookieManager.getInstance());
    }

    final ViewGroup layout = (ViewGroup) activity.getWindow().getDecorView().getRootView();
    final WebViewClient client = new WebViewClient() {
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }

        @Override
        public void onPageFinished(WebView webView, String url) {
            super.onPageFinished(webView, url);
            Logger.d(TAG, "Got Page: " + url);
            String value = null;
            try {
                String[] cookies = CookieManager.getInstance().getCookie(url).split("[;]");
                for (String cookie : cookies) {
                    if ((cookie != null) && (!cookie.trim().equals(""))
                            && (cookie.startsWith(" " + exception.getRequiredCookieName() + "="))) {
                        value = cookie.substring(exception.getRequiredCookieName().length() + 2);
                    }
                }
            } catch (NullPointerException e) {
                Logger.e(TAG, e);
            }
            if (value != null) {
                BasicClientCookieHC4 cf_cookie = new BasicClientCookieHC4(exception.getRequiredCookieName(),
                        value);
                cf_cookie.setDomain("." + Uri.parse(url).getHost());
                cf_cookie.setPath("/");
                currentCookie = cf_cookie;
                Logger.d(TAG, "Cookie found: " + value);
                processing2 = false;
            } else {
                Logger.d(TAG, "Cookie is not found");
            }
        }
    };

    activity.runOnUiThread(new Runnable() {
        @SuppressLint("SetJavaScriptEnabled")
        @Override
        public void run() {
            webView = new WebView(activity);
            webView.setVisibility(View.GONE);
            layout.addView(webView);
            webView.setWebViewClient(client);
            webView.getSettings().setUserAgentString(HttpConstants.USER_AGENT_STRING);
            webView.getSettings().setJavaScriptEnabled(true);
            webViewContext = webView.getContext();
            if (proxy != null)
                WebViewProxy.setProxy(webViewContext, proxy.getHostName(), proxy.getPort());
            webView.loadUrl(exception.getCheckUrl());
        }
    });

    long startTime = System.currentTimeMillis();
    while (processing2) {
        long time = System.currentTimeMillis() - startTime;
        if ((task != null && task.isCancelled()) || time > TIMEOUT) {
            processing2 = false;
        }
    }

    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            try {
                layout.removeView(webView);
                webView.stopLoading();
                webView.clearCache(true);
                webView.destroy();
                webView = null;
            } finally {
                if (proxy != null)
                    WebViewProxy.setProxy(webViewContext, null, 0);
                processing = false;
            }
        }
    });

    return currentCookie;
}

From source file:com.borax12.materialdaterangepicker.single.date.DatePickerDialog.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    final Activity activity = getActivity();
    activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    mCurrentView = UNINITIALIZED;//from   w  w w  . j  a v a  2 s. c o m
    if (savedInstanceState != null) {
        mCalendar.set(Calendar.YEAR, savedInstanceState.getInt(KEY_SELECTED_YEAR));
        mCalendar.set(Calendar.MONTH, savedInstanceState.getInt(KEY_SELECTED_MONTH));
        mCalendar.set(Calendar.DAY_OF_MONTH, savedInstanceState.getInt(KEY_SELECTED_DAY));
        mDefaultView = savedInstanceState.getInt(KEY_DEFAULT_VIEW);
    }
}

From source file:br.ufrgs.ufrgsmapas.libs.SearchBox.java

/***
 * Reveal the searchbox from a menu item. Specify the menu item id and pass the activity so the item can be found
 * @param id View ID/*from w  ww . j  a  va 2  s  . com*/
 * @param activity Activity
 */
public void revealFromMenuItem(int id, Activity activity) {
    setVisibility(View.VISIBLE);
    View menuButton = activity.findViewById(id);
    if (menuButton != null) {
        FrameLayout layout = (FrameLayout) activity.getWindow().getDecorView()
                .findViewById(android.R.id.content);
        if (layout.findViewWithTag("searchBox") == null) {
            int[] location = new int[2];
            menuButton.getLocationInWindow(location);
            revealFrom((float) location[0], (float) location[1], activity, this);
        }
    }
}

From source file:com.borax12.materialdaterangepicker.date.DatePickerDialog.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    final Activity activity = getActivity();
    activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    if (savedInstanceState != null) {
        mCalendar.set(Calendar.YEAR, savedInstanceState.getInt(KEY_SELECTED_YEAR));
        mCalendar.set(Calendar.MONTH, savedInstanceState.getInt(KEY_SELECTED_MONTH));
        mCalendar.set(Calendar.DAY_OF_MONTH, savedInstanceState.getInt(KEY_SELECTED_DAY));
        mCalendarEnd.set(Calendar.YEAR, savedInstanceState.getInt(KEY_SELECTED_YEAR_END));
        mCalendarEnd.set(Calendar.MONTH, savedInstanceState.getInt(KEY_SELECTED_MONTH_END));
        mCalendarEnd.set(Calendar.DAY_OF_MONTH, savedInstanceState.getInt(KEY_SELECTED_DAY_END));
    }/*w ww.java  2s .  c o  m*/
}

From source file:org.appcelerator.titanium.view.TiDrawableReference.java

/**
 * Gets the bitmap, scaled to a width & height specified in TiDimension params.
 * @param destWidthDimension (null-ok) TiDimension specifying the desired width.  If .isUnitAuto()
 * then the width will be the source width.  If destWidthDimension is null, then the TiContext
 * will be used to determine the activity window's decor width and use that.
 * @param destHeightDimension (null-ok) TiDimension specifying the desired height.  If .isUnitAuto()
 * then the height will be the source height.  If destHeightDimension is null, then resulting height will
 * be at same ratio to the resulting width as the original height:width.
 * @return Bitmap, or null if any problem getting it.  Check logcat if null.
 *///from  w  w w . ja v  a  2s.co  m
public Bitmap getBitmap(View parent, TiDimension destWidthDimension, TiDimension destHeightDimension) {
    int srcWidth, srcHeight, destWidth, destHeight;

    Bounds bounds = peekBounds();
    srcWidth = bounds.width;
    srcHeight = bounds.height;

    if (srcWidth <= 0 || srcHeight <= 0) {
        Log.w(TAG, "Bitmap bounds could not be determined. If bitmap is loaded, it won't be scaled.");
        return getBitmap(); // fallback
    }

    if (parent == null) {
        Activity activity = softActivity.get();
        if (activity != null && activity.getWindow() != null) {
            parent = activity.getWindow().getDecorView();
        }
    }

    Bounds destBounds = calcDestSize(srcWidth, srcHeight, destWidthDimension, destHeightDimension, parent);
    destWidth = destBounds.width;
    destHeight = destBounds.height;

    // If src and dest width/height are same, no need to go through all the sampling and scaling jazz.
    if (srcWidth == destWidth && srcHeight == destHeight) {
        return getBitmap();
    }

    if (destWidth <= 0 || destHeight <= 0) {
        // calcDestSize() should actually prevent this from happening, but just in case...
        Log.w(TAG, "Bitmap final bounds could not be determined.  If bitmap is loaded, it won't be scaled.");
        return getBitmap();
    }

    InputStream is = getInputStream();
    if (is == null) {
        Log.w(TAG, "Could not open stream to get bitmap");
        return null;
    }

    Bitmap b = null;
    try {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inInputShareable = true;
        opts.inPurgeable = true;
        opts.inSampleSize = calcSampleSize(srcWidth, srcHeight, destWidth, destHeight);
        if (Log.isDebugModeEnabled()) {
            StringBuilder sb = new StringBuilder();
            sb.append("Bitmap calcSampleSize results: inSampleSize=");
            sb.append(opts.inSampleSize);
            sb.append("; srcWidth=");
            sb.append(srcWidth);
            sb.append("; srcHeight=");
            sb.append(srcHeight);
            sb.append("; finalWidth=");
            sb.append(opts.outWidth);
            sb.append("; finalHeight=");
            sb.append(opts.outHeight);
            Log.d(TAG, sb.toString());
        }

        Bitmap bTemp = null;
        try {
            oomOccurred = false;
            bTemp = BitmapFactory.decodeStream(is, null, opts);
            if (bTemp == null) {
                Log.w(TAG, "Decoded bitmap is null");
                return null;
            }

            if (Log.isDebugModeEnabled()) {
                StringBuilder sb = new StringBuilder();
                sb.append("decodeStream resulting bitmap: .getWidth()=" + bTemp.getWidth());
                sb.append("; .getHeight()=" + bTemp.getHeight());
                sb.append("; getDensity()=" + bTemp.getDensity());
                Log.d(TAG, sb.toString());
            }

            // Set the bitmap density to match the view density before scaling, so that scaling
            // algorithm takes destination density into account.
            DisplayMetrics displayMetrics = new DisplayMetrics();
            displayMetrics.setToDefaults();
            bTemp.setDensity(displayMetrics.densityDpi);

            // Orient the image when orientation is set.
            if (autoRotate) {
                // Only set the orientation if it is uninitialized
                if (orientation < 0) {
                    orientation = getOrientation();
                }
                if (orientation > 0) {
                    return getRotatedBitmap(bTemp, orientation);
                }
            }

            if (bTemp.getNinePatchChunk() != null) {
                // Don't scale nine-patches
                b = bTemp;
                bTemp = null;
            } else {
                Log.d(TAG, "Scaling bitmap to " + destWidth + "x" + destHeight, Log.DEBUG_MODE);

                // If anyDensity=false, meaning Android is automatically scaling
                // pixel dimensions, need to do that here as well, because Bitmap width/height
                // calculations do _not_ do that automatically.
                if (anyDensityFalse && displayMetrics.density != 1f) {
                    destWidth = (int) (destWidth * displayMetrics.density + 0.5f); // 0.5 is to force round up of dimension. Casting to int drops decimals.
                    destHeight = (int) (destHeight * displayMetrics.density + 0.5f);
                }

                // Created a scaled copy of the bitmap. Note we will get
                // back the same bitmap if no scaling is required.
                b = Bitmap.createScaledBitmap(bTemp, destWidth, destHeight, true);
            }

        } catch (OutOfMemoryError e) {
            oomOccurred = true;
            Log.e(TAG, "Unable to load bitmap. Not enough memory: " + e.getMessage(), e);

        } finally {
            // Recycle the temporary bitmap only if it isn't
            // the same instance as our scaled bitmap.
            if (bTemp != null && bTemp != b) {
                bTemp.recycle();
                bTemp = null;
            }
        }

    } finally {
        try {
            is.close();
        } catch (IOException e) {
            Log.e(TAG, "Problem closing stream: " + e.getMessage(), e);
        }
    }
    if (Log.isDebugModeEnabled()) {
        StringBuilder sb = new StringBuilder();
        sb.append("Details of returned bitmap: .getWidth()=" + b.getWidth());
        sb.append("; getHeight()=" + b.getHeight());
        sb.append("; getDensity()=" + b.getDensity());
        Log.d(TAG, sb.toString());
    }
    return b;
}

From source file:com.popdeem.sdk.uikit.activity.PDUIClaimActivity.java

public static void hideKeyboard(Activity activity) {
    if (activity != null && activity.getWindow() != null && activity.getWindow().getDecorView() != null) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0);
    }//from www  .j a v  a  2 s .  co  m
}

From source file:br.ufrgs.ufrgsmapas.libs.SearchBox.java

/***
 * Hide the searchbox using the circle animation. Can be called regardless of result list length
 * @param activity Activity/*  ww  w .  j a  v a2s .  co  m*/
 */
public void hideCircularly(Activity activity) {
    Display display = activity.getWindowManager().getDefaultDisplay();
    Point size = new Point();
    final FrameLayout layout = (FrameLayout) activity.getWindow().getDecorView()
            .findViewById(android.R.id.content);
    RelativeLayout root = (RelativeLayout) findViewById(R.id.search_root);
    display.getSize(size);
    Resources r = getResources();
    float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 96, r.getDisplayMetrics());
    int cx = layout.getLeft() + layout.getRight();
    int cy = layout.getTop();
    int finalRadius = (int) Math.max(layout.getWidth() * 1.5, px);

    SupportAnimator animator = ViewAnimationUtils.createCircularReveal(root, cx, cy, 0, finalRadius);
    animator.setInterpolator(new ReverseInterpolator());
    animator.setDuration(500);
    animator.start();
    animator.addListener(new SupportAnimator.AnimatorListener() {

        @Override
        public void onAnimationStart() {

        }

        @Override
        public void onAnimationEnd() {
            setVisibility(View.GONE);
        }

        @Override
        public void onAnimationCancel() {

        }

        @Override
        public void onAnimationRepeat() {

        }

    });
}

From source file:ch.uzh.supersede.feedbacklibrary.utils.Utils.java

@NonNull
private static String captureScreenshot(final Activity activity) {
    // Create the 'Screenshots' folder if it does not already exist
    File screenshotDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            SCREENSHOTS_DIR_NAME);// w  w w  . j av a 2 s.  com
    screenshotDir.mkdirs();

    // Image name 'Screenshot_YearMonthDay-HourMinuteSecondMillisecond.png'
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    String imageName = "Screenshot_" + calendar.get(Calendar.YEAR) + (calendar.get(Calendar.MONTH) + 1)
            + calendar.get(Calendar.DAY_OF_MONTH);
    imageName += "-" + calendar.get(Calendar.HOUR_OF_DAY) + calendar.get(Calendar.MINUTE)
            + calendar.get(Calendar.SECOND) + calendar.get(Calendar.MILLISECOND) + ".png";
    File screenshotFile = new File(screenshotDir, imageName);

    // Create the screenshot file
    try {
        if (screenshotFile.exists()) {
            screenshotFile.delete();
        }
        screenshotFile.createNewFile();
    } catch (IOException e) {
        Log.e(TAG, "Failed to create a new file", e);
    }

    // Capture the current screen
    View rootView = activity.getWindow().getDecorView().getRootView();
    rootView.setDrawingCacheEnabled(true);
    Bitmap imageBitmap = Bitmap.createBitmap(rootView.getDrawingCache());
    rootView.setDrawingCacheEnabled(false);

    FileOutputStream fos;
    try {
        fos = new FileOutputStream(screenshotFile);
        imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.flush();
        fos.close();
    } catch (Exception e) {
        Log.e(TAG, "Failed to write the bitmap to the file", e);
    }

    // Add the screenshot image to the Media Provider's database
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    Uri contentUri = Uri.fromFile(screenshotFile);
    mediaScanIntent.setData(contentUri);
    activity.sendBroadcast(mediaScanIntent);

    return screenshotFile.getAbsolutePath();
}