Example usage for android.content Context WINDOW_SERVICE

List of usage examples for android.content Context WINDOW_SERVICE

Introduction

In this page you can find the example usage for android.content Context WINDOW_SERVICE.

Prototype

String WINDOW_SERVICE

To view the source code for android.content Context WINDOW_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.view.WindowManager for accessing the system's window manager.

Usage

From source file:com.yozio.android.YozioHelper.java

private void setScreenInfo() {
    try {/*from www  .  jav a2  s  .com*/
        // This is a backwards compatibility fix for Android 1.5 which has no
        // display metric API.
        // If this is 1.6 or higher, then load the class, otherwise the class
        // never loads and
        // no crash occurs.
        if (Integer.parseInt(android.os.Build.VERSION.SDK) > 3) {
            DisplayMetrics displayMetrics = new DisplayMetrics();
            WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            windowManager.getDefaultDisplay().getMetrics(displayMetrics);
            Configuration configuration = context.getResources().getConfiguration();

            deviceScreenDensity = "" + displayMetrics.densityDpi;
            deviceScreenLayoutSize = "" + (configuration.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK);
        }
    } catch (Exception e) {
    }
}

From source file:app.umitems.greenclock.widget.sgv.StaggeredGridView.java

public StaggeredGridView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

    final ViewConfiguration vc = ViewConfiguration.get(context);
    mTouchSlop = vc.getScaledTouchSlop();
    mMaximumVelocity = vc.getScaledMaximumFlingVelocity();
    mFlingVelocity = vc.getScaledMinimumFlingVelocity();
    mScroller = new OverScrollerSGV(context);

    mTopEdge = new EdgeEffectCompat(context);
    mBottomEdge = new EdgeEffectCompat(context);
    setWillNotDraw(false);/*from  w w w .  ja  v  a  2 s .c  o  m*/
    setClipToPadding(false);

    SgvAnimationHelper.initialize(context);

    mDragState = ReorderUtils.DRAG_STATE_NONE;
    mIsDragReorderingEnabled = true;
    mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    final ViewConfiguration configuration = ViewConfiguration.get(context);
    mOverscrollDistance = configuration.getScaledOverflingDistance();
    // Disable splitting event. Only one of the children can handle motion event.
    setMotionEventSplittingEnabled(false);
}

From source file:com.adflake.AdFlakeManager.java

/**
 * Parses the custom section from the specified json string.
 * // w w w .  j  av  a2s . c  o m
 * @param jsonString
 *            the json string
 * @return the custom
 */
private Custom parseCustomJsonString(String jsonString) {
    Log.d(AdFlakeUtil.ADFLAKE, "Received custom jsonString: " + jsonString);

    Custom custom = new Custom();
    try {
        JSONObject json = new JSONObject(jsonString);

        custom.type = json.getInt("ad_type");
        custom.imageLink = json.getString("img_url");
        custom.link = json.getString("redirect_url");
        custom.description = json.getString("ad_text");

        try {
            custom.imageLink640x100 = json.getString("img_url_640x100");
        } catch (JSONException e) {
            custom.imageLink640x100 = null;
        }
        try {
            custom.imageLink480x75 = json.getString("img_url_480x75");
        } catch (JSONException e) {
            custom.imageLink480x75 = null;
        }

        DisplayMetrics metrics = new DisplayMetrics();
        ((WindowManager) _contextReference.get().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
                .getMetrics(metrics);

        if (metrics.density >= 2.0 && custom.type == AdFlakeUtil.CUSTOM_TYPE_BANNER
                && custom.imageLink640x100 != null && custom.imageLink640x100.length() != 0) {
            custom.image = fetchImageWithURL(custom.imageLink640x100);
        } else if (metrics.density >= 1.5 && custom.type == AdFlakeUtil.CUSTOM_TYPE_BANNER
                && custom.imageLink480x75 != null && custom.imageLink480x75.length() != 0) {
            custom.image = fetchImageWithURL(custom.imageLink480x75);
        } else {
            custom.image = fetchImageWithURL(custom.imageLink);
        }
    } catch (JSONException e) {
        Log.e(AdFlakeUtil.ADFLAKE, "Caught JSONException in parseCustomJsonString()", e);
        return null;
    }

    return custom;
}

From source file:com.irccloud.android.NetworkConnection.java

@SuppressWarnings("deprecation")
public NetworkConnection() {
    String version;/*from   www  .  ja v  a 2s.c o  m*/
    String network_type = null;
    try {
        version = "/" + IRCCloudApplication.getInstance().getPackageManager().getPackageInfo(
                IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), 0).versionName;
    } catch (Exception e) {
        version = "";
    }

    try {
        ConnectivityManager cm = (ConnectivityManager) IRCCloudApplication.getInstance()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni != null)
            network_type = ni.getTypeName();
    } catch (Exception e) {
    }

    try {
        config = new JSONObject(PreferenceManager
                .getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext())
                .getString("config", "{}"));
    } catch (JSONException e) {
        e.printStackTrace();
        config = new JSONObject();
    }

    useragent = "IRCCloud" + version + " (" + android.os.Build.MODEL + "; "
            + Locale.getDefault().getCountry().toLowerCase() + "; " + "Android "
            + android.os.Build.VERSION.RELEASE;

    WindowManager wm = (WindowManager) IRCCloudApplication.getInstance()
            .getSystemService(Context.WINDOW_SERVICE);
    useragent += "; " + wm.getDefaultDisplay().getWidth() + "x" + wm.getDefaultDisplay().getHeight();

    if (network_type != null)
        useragent += "; " + network_type;

    useragent += ")";

    WifiManager wfm = (WifiManager) IRCCloudApplication.getInstance().getApplicationContext()
            .getSystemService(Context.WIFI_SERVICE);
    wifiLock = wfm.createWifiLock(TAG);

    kms = new X509ExtendedKeyManager[1];
    kms[0] = new X509ExtendedKeyManager() {
        @Override
        public String chooseClientAlias(String[] keyTypes, Principal[] issuers, Socket socket) {
            return SSLAuthAlias;
        }

        @Override
        public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
            throw new UnsupportedOperationException();
        }

        @Override
        public X509Certificate[] getCertificateChain(String alias) {
            return SSLAuthCertificateChain;
        }

        @Override
        public String[] getClientAliases(String keyType, Principal[] issuers) {
            throw new UnsupportedOperationException();
        }

        @Override
        public String[] getServerAliases(String keyType, Principal[] issuers) {
            throw new UnsupportedOperationException();
        }

        @Override
        public PrivateKey getPrivateKey(String alias) {
            return SSLAuthKey;
        }
    };

    tms = new TrustManager[1];
    tms[0] = new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            throw new CertificateException("Not implemented");
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            try {
                TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
                trustManagerFactory.init((KeyStore) null);

                for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
                    if (trustManager instanceof X509TrustManager) {
                        X509TrustManager x509TrustManager = (X509TrustManager) trustManager;
                        x509TrustManager.checkServerTrusted(chain, authType);
                    }
                }
            } catch (KeyStoreException e) {
                throw new CertificateException(e);
            } catch (NoSuchAlgorithmException e) {
                throw new CertificateException(e);
            }

            if (BuildConfig.SSL_FPS != null && BuildConfig.SSL_FPS.length > 0) {
                try {
                    MessageDigest md = MessageDigest.getInstance("SHA-1");
                    byte[] sha1 = md.digest(chain[0].getEncoded());
                    // http://stackoverflow.com/questions/9655181/convert-from-byte-array-to-hex-string-in-java
                    final char[] hexArray = "0123456789ABCDEF".toCharArray();
                    char[] hexChars = new char[sha1.length * 2];
                    for (int j = 0; j < sha1.length; j++) {
                        int v = sha1[j] & 0xFF;
                        hexChars[j * 2] = hexArray[v >>> 4];
                        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
                    }
                    String hexCharsStr = new String(hexChars);
                    boolean matched = false;
                    for (String fp : BuildConfig.SSL_FPS) {
                        if (fp.equals(hexCharsStr)) {
                            matched = true;
                            break;
                        }
                    }
                    if (!matched)
                        throw new CertificateException("Incorrect CN in cert chain");
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    WebSocketClient.setTrustManagers(tms);
}

From source file:com.ferdi2005.secondgram.AndroidUtilities.java

public static void checkDisplaySize(Context context, Configuration newConfiguration) {
    try {/* w  ww. j  a  va2s  .  c  o  m*/
        density = context.getResources().getDisplayMetrics().density;
        Configuration configuration = newConfiguration;
        if (configuration == null) {
            configuration = context.getResources().getConfiguration();
        }
        usingHardwareInput = configuration.keyboard != Configuration.KEYBOARD_NOKEYS
                && configuration.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO;
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        if (manager != null) {
            Display display = manager.getDefaultDisplay();
            if (display != null) {
                display.getMetrics(displayMetrics);
                display.getSize(displaySize);
            }
        }
        if (configuration.screenWidthDp != Configuration.SCREEN_WIDTH_DP_UNDEFINED) {
            int newSize = (int) Math.ceil(configuration.screenWidthDp * density);
            if (Math.abs(displaySize.x - newSize) > 3) {
                displaySize.x = newSize;
            }
        }
        if (configuration.screenHeightDp != Configuration.SCREEN_HEIGHT_DP_UNDEFINED) {
            int newSize = (int) Math.ceil(configuration.screenHeightDp * density);
            if (Math.abs(displaySize.y - newSize) > 3) {
                displaySize.y = newSize;
            }
        }
        FileLog.e("display size = " + displaySize.x + " " + displaySize.y + " " + displayMetrics.xdpi + "x"
                + displayMetrics.ydpi);
    } catch (Exception e) {
        FileLog.e(e);
    }
}

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

/**
 * Creates a view appropriate for displaying a list of GuidedActions, using the provided
 * inflater and container./*  w w  w  .  j  a v  a  2s .  co m*/
 * <p>
 * <i>Note: Does not actually add the created view to the container; the caller should do
 * this.</i>
 * @param inflater The layout inflater to be used when constructing the view.
 * @param container The view group to be passed in the call to
 * <code>LayoutInflater.inflate</code>.
 * @return The view to be added to the caller's view hierarchy.
 */
public View onCreateView(LayoutInflater inflater, final ViewGroup container) {
    TypedArray ta = inflater.getContext().getTheme()
            .obtainStyledAttributes(R.styleable.LeanbackGuidedStepTheme);
    float keylinePercent = ta.getFloat(R.styleable.LeanbackGuidedStepTheme_guidedStepKeyline, 40);
    mMainView = (ViewGroup) inflater.inflate(onProvideLayoutId(), container, false);
    mContentView = mMainView
            .findViewById(mButtonActions ? R.id.guidedactions_content2 : R.id.guidedactions_content);
    mBgView = mMainView.findViewById(
            mButtonActions ? R.id.guidedactions_list_background2 : R.id.guidedactions_list_background);
    if (mMainView instanceof VerticalGridView) {
        mActionsGridView = (VerticalGridView) mMainView;
    } else {
        mActionsGridView = (VerticalGridView) mMainView
                .findViewById(mButtonActions ? R.id.guidedactions_list2 : R.id.guidedactions_list);
        if (mActionsGridView == null) {
            throw new IllegalStateException("No ListView exists.");
        }
        mActionsGridView.setWindowAlignmentOffsetPercent(keylinePercent);
        mActionsGridView.setWindowAlignment(VerticalGridView.WINDOW_ALIGN_NO_EDGE);
        if (!mButtonActions) {
            mSubActionsGridView = (VerticalGridView) mMainView.findViewById(R.id.guidedactions_sub_list);
        }
    }
    mActionsGridView.setFocusable(false);
    mActionsGridView.setFocusableInTouchMode(false);

    // Cache widths, chevron alpha values, max and min text lines, etc
    Context ctx = mMainView.getContext();
    TypedValue val = new TypedValue();
    mEnabledChevronAlpha = getFloat(ctx, val, R.attr.guidedActionEnabledChevronAlpha);
    mDisabledChevronAlpha = getFloat(ctx, val, R.attr.guidedActionDisabledChevronAlpha);
    mTitleMinLines = getInteger(ctx, val, R.attr.guidedActionTitleMinLines);
    mTitleMaxLines = getInteger(ctx, val, R.attr.guidedActionTitleMaxLines);
    mDescriptionMinLines = getInteger(ctx, val, R.attr.guidedActionDescriptionMinLines);
    mVerticalPadding = getDimension(ctx, val, R.attr.guidedActionVerticalPadding);
    mDisplayHeight = ((WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
            .getHeight();

    mEnabledTextAlpha = Float
            .valueOf(ctx.getResources().getString(R.string.lb_guidedactions_item_unselected_text_alpha));
    mDisabledTextAlpha = Float
            .valueOf(ctx.getResources().getString(R.string.lb_guidedactions_item_disabled_text_alpha));
    mEnabledDescriptionAlpha = Float.valueOf(
            ctx.getResources().getString(R.string.lb_guidedactions_item_unselected_description_text_alpha));
    mDisabledDescriptionAlpha = Float.valueOf(
            ctx.getResources().getString(R.string.lb_guidedactions_item_disabled_description_text_alpha));
    return mMainView;
}

From source file:androidx.media.widget.MediaControlView2.java

@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    // Update layout when this view's width changes in order to avoid any UI overlap between
    // transport controls.
    if (mPrevWidth != getMeasuredWidth() || mPrevHeight != getMeasuredHeight() || mNeedUXUpdate) {
        // Dismiss SettingsWindow if it is showing.
        mSettingsWindow.dismiss();/*  w  w w  .j a  va2 s . com*/

        // These views may not have been initialized yet.
        if (mTransportControls.getWidth() == 0 || mTimeView.getWidth() == 0) {
            return;
        }

        int currWidth = getMeasuredWidth();
        int currHeight = getMeasuredHeight();
        WindowManager manager = (WindowManager) getContext().getApplicationContext()
                .getSystemService(Context.WINDOW_SERVICE);
        Point screenSize = new Point();
        manager.getDefaultDisplay().getSize(screenSize);
        int screenWidth = screenSize.x;
        int screenHeight = screenSize.y;
        int fullIconSize = mResources.getDimensionPixelSize(R.dimen.mcv2_full_icon_size);
        int embeddedIconSize = mResources.getDimensionPixelSize(R.dimen.mcv2_embedded_icon_size);
        int marginSize = mResources.getDimensionPixelSize(R.dimen.mcv2_icon_margin);

        // TODO: add support for Advertisement Mode.
        if (mMediaType == MEDIA_TYPE_DEFAULT) {
            // Max number of icons inside BottomBarRightView for Music mode is 4.
            int maxIconCount = 4;
            updateLayout(maxIconCount, fullIconSize, embeddedIconSize, marginSize, currWidth, currHeight,
                    screenWidth, screenHeight);

        } else if (mMediaType == MEDIA_TYPE_MUSIC) {
            if (mNeedUXUpdate) {
                // One-time operation for Music media type
                mBasicControls.removeView(mMuteButton);
                mExtraControls.addView(mMuteButton, 0);
                mVideoQualityButton.setVisibility(View.GONE);
                if (mFfwdButton != null) {
                    mFfwdButton.setVisibility(View.GONE);
                }
                if (mRewButton != null) {
                    mRewButton.setVisibility(View.GONE);
                }
            }
            mNeedUXUpdate = false;

            // Max number of icons inside BottomBarRightView for Music mode is 3.
            int maxIconCount = 3;
            updateLayout(maxIconCount, fullIconSize, embeddedIconSize, marginSize, currWidth, currHeight,
                    screenWidth, screenHeight);
        }
        mPrevWidth = currWidth;
        mPrevHeight = currHeight;
    }
    // TODO: move this to a different location.
    // Update title bar parameters in order to avoid overlap between title view and the right
    // side of the title bar.
    updateTitleBarLayout();
}

From source file:com.xmobileapp.rockplayer.RockPlayer.java

/**********************************************
 * //from   w  ww  .java  2  s .co m
 *  Called when the activity is first created
 *  
 **********************************************/
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = this;
    System.gc();

    //Log.i("PRFMC", "1");
    /*
    * Window Properties
    */
    //requestWindowFeature(Window.FEATURE_PROGRESS);
    //requestWindowFeature(Window.PROGRESS_VISIBILITY_ON);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    /*
     * Blur&Dim the BG
     */
    // Have the system blur any windows behind this one.
    //        getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
    //                WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
    ////        getWindow().setFlags(WindowManager.LayoutParams.FLAG_DITHER, 
    ////              WindowManager.LayoutParams.FLAG_DITHER);
    //        getWindow().setFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND, 
    //              WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    //        WindowManager.LayoutParams params = getWindow().getAttributes();
    //        params.dimAmount = 0.625f;
    //        getWindow().setAttributes(params);

    //        Resources.Theme theme = getTheme();
    //        theme.dump(arg0, arg1, arg2)

    //setContentView(R.layout.songfest_main);
    //Log.i("PRFMC", "2");

    /*
     * Initialize Display
     */
    WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
    this.display = windowManager.getDefaultDisplay();
    //Log.i("PRFMC", "3");

    /*
     * Set Bug Report Handler
     */
    fdHandler = new FilexDefaultExceptionHandler(this);

    /*
     * Check if Album Art Directory exists
     */
    checkAlbumArtDirectory();
    checkConcertDirectory();
    checkPreferencesDirectory();
    checkBackgroundDirectory();
    //Log.i("PRFMC", "7");

    /*
     * Get Preferences
     */
    readPreferences();

    /*
     * Force landscape or auto-rotate orientation if user requested
     */
    if (alwaysLandscape)
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    else if (autoRotate)
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);

    /*
      * Create UI and initialize UI vars
      */
    setContentView(R.layout.songfest_main);

    //getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    //if (true) return;

    //if(true)
    //   return;
    //Log.i("PRFMC", "4");
    initializeAnimations();
    //Log.i("PRFMC", "5");
    initializeUiVariables();
    //Log.i("PRFMC", "6");

    /*
     * Set Background
     */
    setBackground();

    /*
     * Set Current View
     */
    switch (VIEW_STATE) {
    case LIST_EXPANDED_VIEW:
        setListExpandedView();
        break;
    case FULLSCREEN_VIEW:
        setFullScreenView();
        break;
    default:
        setNormalView();
        break;
    }

    //        AlphaAnimation aAnim = new AlphaAnimation(0.0f, 0.92f);
    //        aAnim.setFillAfter(true);
    //        aAnim.setDuration(200);
    //        mainUIContainer.startAnimation(aAnim);

    /*
     * Check for SD Card
     */
    if (!android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
        Dialog noSDDialog = new Dialog(this);
        noSDDialog.setTitle("SD Card Error!");
        noSDDialog.setContentView(R.layout.no_sd_alert_layout);
        noSDDialog.show();
        return;
    }

    /*
     * Get a Content Resolver to browse
     * the phone audio database
     */
    contentResolver = getContentResolver();

    /*
     * Get Preferences
     */
    //SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    RockOnPreferenceManager settings = new RockOnPreferenceManager(FILEX_PREFERENCES_PATH);
    settings = new RockOnPreferenceManager(this.FILEX_PREFERENCES_PATH);
    // Shuffle
    boolean shuffle = settings.getBoolean("Shuffle", false);
    this.SHUFFLE = shuffle;
    //Playlist
    if (playlist == constants.PLAYLIST_NONE)
        playlist = settings.getLong(constants.PREF_KEY_PLAYLIST, constants.PLAYLIST_ALL);
    Log.i("PLAYLIST PREF", constants.PREF_KEY_PLAYLIST + " " + constants.PLAYLIST_ALL + " " + playlist);

    /*
     * Check if the MediaScanner is scanning
     */
    //        ProgressDialog pD = null;
    //        while(isMediaScannerScanning(this, contentResolver) == true){
    //           if(pD == null){
    //              pD = new ProgressDialog(this);
    //              pD.setTitle("Scanning Media");
    //              pD.setMessage("Wait please...");
    //              pD.show();
    //           }
    //           try {
    //            wait(2000);
    //         } catch (InterruptedException e) {
    //            e.printStackTrace();
    //         }
    //        }
    //        if(pD != null)
    //           pD.dismiss();

    /*
     * Initialize mediaPlayer
     */
    //this.mediaPlayer = new MediaPlayer();
    //this.mediaPlayer.setOnCompletionListener(songCompletedListener);

    /*
     * Initialize (or connect to) BG Service
     *  - when connected it will call the method getCurrentPlaying()
     *     and will cause the Service to reset its albumCursor
     */
    initializeService();
    //Log.i("PRFMC", "8");
    musicChangedIntentReceiver = new MusicChangedIntentReceiver();
    albumChangedIntentReceiver = new AlbumChangedIntentReceiver();
    mediaButtonPauseIntentReceiver = new MediaButtonPauseIntentReceiver();
    mediaButtonPlayIntentReceiver = new MediaButtonPlayIntentReceiver();
    registerReceiver(musicChangedIntentReceiver, musicChangedIntentFilter);
    //Log.i("PRFMC", "9");
    registerReceiver(albumChangedIntentReceiver, albumChangedIntentFilter);
    //Log.i("PRFMC", "10");
    registerReceiver(mediaButtonPauseIntentReceiver, mediaButtonPauseIntentFilter);
    registerReceiver(mediaButtonPlayIntentReceiver, mediaButtonPlayIntentFilter);
    // calls also getCurrentPlaying() upon connection

    /*
     * Register Media Button Receiver
     */
    //        mediaButtonIntentReceiver = new MediaButtonIntentReceiver();
    //        registerReceiver(mediaButtonIntentReceiver, new IntentFilter("android.intent.action.MEDIA_BUTTON"));

    /*
      * Get album information on a new
      * thread
      */
    //new Thread(){
    //   public void run(){
    getAlbums(false);
    //Log.i("PRFMC", "11");
    //   }
    //}.start();

    /*
     * Check for first time run ----------
     * 
     * Save Software Version
     *    &
     * Show Help Screen
     */
    //            if(!settings.contains("Version")){
    //               Editor settingsEditor = settings.edit();
    //               settingsEditor.putLong("Version", VERSION);
    //               settingsEditor.commit();
    //               this.hideMainUI();
    //               this.showHelpUI();
    //            }
    Log.i("DBG", "Version - " + (new RockOnPreferenceManager(this.FILEX_PREFERENCES_PATH)).getLong("Version", 0)
            + " - " + VERSION);
    if (!(new RockOnPreferenceManager(this.FILEX_PREFERENCES_PATH)).contains("Version")
            || (new RockOnPreferenceManager(this.FILEX_PREFERENCES_PATH)).getLong("Version", 0) < VERSION) {

        (new RockOnPreferenceManager(this.FILEX_PREFERENCES_PATH)).putLong("Version", VERSION);

        /*
        * Clear previous Album Art
        */
        Builder aD = new AlertDialog.Builder(context);
        aD.setTitle("New Version");
        aD.setMessage(
                "The new version of RockOn supports album art download from higher quality sources. Do you want to download art now? "
                        + "Every 10 albums will take aproximately 1 minute to download. "
                        + "(You can always do this later by choosing the 'Get Art' menu option)");
        aD.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                //(new RockOnPreferenceManager(FILEX_PREFERENCES_PATH)).putLong("artImportDate", 0);
                try {
                    File albumArtDir = new File(FILEX_ALBUM_ART_PATH);
                    String[] fileList = albumArtDir.list();
                    File albumArtFile;
                    for (int i = 0; i < fileList.length; i++) {
                        albumArtFile = new File(albumArtDir.getAbsolutePath() + "/" + fileList[i]);
                        albumArtFile.delete();
                    }
                    checkAlbumArtDirectory();
                    triggerAlbumArtFetching();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        });
        aD.setNegativeButton("No", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

            }

        });
        aD.show();

        /*
        * Version 2 specific default preference changes
        */
        // version 2 specific
        if (albumCursor.getCount() > 100)
            (new RockOnPreferenceManager(this.FILEX_PREFERENCES_PATH))
                    .putBoolean(PREFS_SHOW_ART_WHILE_SCROLLING, false);
        else
            (new RockOnPreferenceManager(this.FILEX_PREFERENCES_PATH))
                    .putBoolean(PREFS_SHOW_ART_WHILE_SCROLLING, true);

        readPreferences();
        albumAdapter.showArtWhileScrolling = showArtWhileScrolling;
        albumAdapter.showFrame = showFrame;
        //

        /*
        * Show help screen
        */
        this.hideMainUI();
        this.showHelpUI();
    } else {
        /*
         * Run albumArt getter in background
         */
        long lastAlbumArtImportDate = settings.getLong("artImportDate", 0);
        Log.i("SYNCTIME",
                lastAlbumArtImportDate + " + " + this.ART_IMPORT_INTVL + " < " + System.currentTimeMillis());
        if (lastAlbumArtImportDate + this.ART_IMPORT_INTVL < System.currentTimeMillis()) {
            triggerAlbumArtFetching();
        }
        //Log.i("PRFMC", "13");
    }
}

From source file:de.madvertise.android.sdk.MadvertiseView.java

/**
 * Starts a background thread to fetch a new ad. Method is called from the
 * refresh timer task//from w  w w. j a  v  a 2s . c om
 */
private void requestNewAd(final boolean isTimerRequest) {
    if (!mFetchAdsEnabled) {
        MadvertiseUtil.logMessage(null, Log.DEBUG, "Fetching ads is disabled");
        return;
    }

    MadvertiseUtil.logMessage(null, Log.DEBUG, "Trying to fetch a new ad");

    mRequestThread = new Thread(new Runnable() {
        public void run() {
            // read all parameters, that we need for the request
            // get site token from manifest xml file
            String siteToken = MadvertiseUtil.getToken(getContext().getApplicationContext(), mCallbackListener);
            if (siteToken == null) {
                siteToken = "";
                MadvertiseUtil.logMessage(null, Log.DEBUG, "Cannot show ads, since the appID ist null");
            } else {
                MadvertiseUtil.logMessage(null, Log.DEBUG, "appID = " + siteToken);
            }

            // create post request
            HttpPost postRequest = new HttpPost(MadvertiseUtil.MAD_SERVER + "/site/" + siteToken);
            postRequest.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            // new ad response version, that supports rich media
            postRequest.addHeader("Accept", "application/vnd.madad+json; version=3");
            List<NameValuePair> parameterList = new ArrayList<NameValuePair>();
            parameterList.add(new BasicNameValuePair("ua", MadvertiseUtil.getUA()));
            parameterList.add(new BasicNameValuePair("app", "true"));
            parameterList.add(new BasicNameValuePair("debug", Boolean.toString(mTestMode)));
            parameterList
                    .add(new BasicNameValuePair("ip", MadvertiseUtil.getLocalIpAddress(mCallbackListener)));
            parameterList.add(new BasicNameValuePair("format", "json"));
            parameterList.add(new BasicNameValuePair("requester", "android_sdk"));
            parameterList.add(new BasicNameValuePair("version", "3.1.3"));
            parameterList.add(new BasicNameValuePair("banner_type", mBannerType));
            parameterList.add(new BasicNameValuePair("deliver_only_text", Boolean.toString(mDeliverOnlyText)));
            if (sAge != null && !sAge.equals("")) {
                parameterList.add(new BasicNameValuePair("age", sAge));
            }

            parameterList.add(new BasicNameValuePair("mraid", Boolean.toString(mIsMraid)));

            if (sGender != null && !sGender.equals("")) {
                parameterList.add(new BasicNameValuePair("gender", sGender));
            }
            final Display display = ((WindowManager) getContext().getApplicationContext()
                    .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
            String orientation;
            if (display.getWidth() > display.getHeight()) {
                orientation = "landscape";
            } else {
                orientation = "portrait";
            }

            parameterList.add(new BasicNameValuePair("device_height", Integer.toString(display.getHeight())));
            parameterList.add(new BasicNameValuePair("device_width", Integer.toString(display.getWidth())));

            // When the View is first created, the parent does not exist
            // when this call is made. Hence, we assume that the parent
            // size is equal the screen size for the first call.
            if (mParentWidth == 0 && mParentHeight == 0) {
                mParentWidth = display.getWidth();
                mParentHeight = display.getHeight();
            }

            parameterList.add(new BasicNameValuePair("parent_height", Integer.toString(mParentHeight)));
            parameterList.add(new BasicNameValuePair("parent_width", Integer.toString(mParentWidth)));

            parameterList.add(new BasicNameValuePair("device_orientation", orientation));
            MadvertiseUtil.refreshCoordinates(getContext().getApplicationContext());
            if (MadvertiseUtil.getLocation() != null) {
                parameterList.add(new BasicNameValuePair("lat",
                        Double.toString(MadvertiseUtil.getLocation().getLatitude())));
                parameterList.add(new BasicNameValuePair("lng",
                        Double.toString(MadvertiseUtil.getLocation().getLongitude())));
            }

            parameterList.add(new BasicNameValuePair("app_name",
                    MadvertiseUtil.getApplicationName(getContext().getApplicationContext())));
            parameterList.add(new BasicNameValuePair("app_version",
                    MadvertiseUtil.getApplicationVersion(getContext().getApplicationContext())));

            parameterList.add(new BasicNameValuePair("udid_md5",
                    MadvertiseUtil.getHashedAndroidID(getContext(), MadvertiseUtil.HashType.MD5)));
            parameterList.add(new BasicNameValuePair("udid_sha1",
                    MadvertiseUtil.getHashedAndroidID(getContext(), MadvertiseUtil.HashType.SHA1)));

            parameterList.add(new BasicNameValuePair("mac_md5",
                    MadvertiseUtil.getHashedMacAddress(getContext(), MadvertiseUtil.HashType.MD5)));
            parameterList.add(new BasicNameValuePair("mac_sha1",
                    MadvertiseUtil.getHashedMacAddress(getContext(), MadvertiseUtil.HashType.SHA1)));

            UrlEncodedFormEntity urlEncodedEntity = null;
            try {
                urlEncodedEntity = new UrlEncodedFormEntity(parameterList);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }

            postRequest.setEntity(urlEncodedEntity);

            MadvertiseUtil.logMessage(null, Log.DEBUG, "Post request created");
            MadvertiseUtil.logMessage(null, Log.DEBUG, "Uri : " + postRequest.getURI().toASCIIString());
            MadvertiseUtil.logMessage(null, Log.DEBUG,
                    "All headers : " + MadvertiseUtil.getAllHeadersAsString(postRequest.getAllHeaders()));
            MadvertiseUtil.logMessage(null, Log.DEBUG,
                    "All request parameters :" + MadvertiseUtil.printRequestParameters(parameterList));

            synchronized (this) {
                // send blocking request to ad server
                HttpClient httpClient = new DefaultHttpClient();
                HttpResponse httpResponse = null;
                InputStream inputStream = null;
                JSONObject json = null;

                try {
                    HttpParams clientParams = httpClient.getParams();
                    HttpConnectionParams.setConnectionTimeout(clientParams, MadvertiseUtil.CONNECTION_TIMEOUT);
                    HttpConnectionParams.setSoTimeout(clientParams, MadvertiseUtil.CONNECTION_TIMEOUT);

                    MadvertiseUtil.logMessage(null, Log.DEBUG, "Sending request");
                    httpResponse = httpClient.execute(postRequest);

                    MadvertiseUtil.logMessage(null, Log.DEBUG,
                            "Response Code => " + httpResponse.getStatusLine().getStatusCode());

                    String message = "";
                    if (httpResponse.getLastHeader("X-Madvertise-Debug") != null) {
                        message = httpResponse.getLastHeader("X-Madvertise-Debug").toString();
                    }

                    if (mTestMode) {
                        MadvertiseUtil.logMessage(null, Log.DEBUG, "Madvertise Debug Response: " + message);
                    }

                    int responseCode = httpResponse.getStatusLine().getStatusCode();

                    HttpEntity entity = httpResponse.getEntity();

                    if (responseCode == 200 && entity != null) {
                        inputStream = entity.getContent();
                        String resultString = MadvertiseUtil.convertStreamToString(inputStream);
                        MadvertiseUtil.logMessage(null, Log.DEBUG, "Response => " + resultString);
                        json = new JSONObject(resultString);

                        // create ad
                        mCurrentAd = new MadvertiseAd(getContext().getApplicationContext(), json,
                                mCallbackListener);

                        calculateBannerDimensions();

                        mHandler.post(mUpdateResults);
                    } else {
                        if (mCallbackListener != null) {
                            mCallbackListener.onIllegalHttpStatusCode(responseCode, message);
                        }
                    }
                } catch (ClientProtocolException e) {
                    MadvertiseUtil.logMessage(null, Log.DEBUG, "Error in HTTP request / protocol", e);
                    if (mCallbackListener != null) {
                        mCallbackListener.onError(e);
                    }
                } catch (IOException e) {
                    MadvertiseUtil.logMessage(null, Log.DEBUG,
                            "Could not receive a http response on an ad request", e);
                    if (mCallbackListener != null) {
                        mCallbackListener.onError(e);
                    }
                } catch (JSONException e) {
                    MadvertiseUtil.logMessage(null, Log.DEBUG, "Could not parse json object", e);
                    if (mCallbackListener != null) {
                        mCallbackListener.onError(e);
                    }
                } catch (Exception e) {
                    MadvertiseUtil.logMessage(null, Log.DEBUG,
                            "Could not receive a http response on an ad request", e);
                    if (mCallbackListener != null) {
                        mCallbackListener.onError(e);
                    }
                } finally {
                    if (inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            if (mCallbackListener != null) {
                                mCallbackListener.onError(e);
                            }
                        }
                    }
                }
            }
        }
    }, "MadvertiseRequestThread");
    mRequestThread.start();
}