Example usage for android.util Log isLoggable

List of usage examples for android.util Log isLoggable

Introduction

In this page you can find the example usage for android.util Log isLoggable.

Prototype

public static native boolean isLoggable(String tag, int level);

Source Link

Document

Checks to see whether or not a log for the specified tag is loggable at the specified level.

Usage

From source file:com.samsung.android.remindme.SyncAdapter.java

@Override
public void onPerformSync(final Account account, Bundle extras, String authority,
        final ContentProviderClient provider, final SyncResult syncResult) {
    Log.i(TAG, "onPerformSync called!");
    TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
    String clientDeviceId = tm.getDeviceId();

    final long newSyncTime = System.currentTimeMillis();

    final boolean uploadOnly = extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false);
    final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
    final boolean initialize = extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false);

    C2DMReceiver.refreshAppC2DMRegistrationState(mContext);

    Log.i(TAG, "Beginning " + (uploadOnly ? "upload-only" : "full") + " sync for account " + account.name);

    // Read this account's sync metadata
    final SharedPreferences syncMeta = mContext.getSharedPreferences("sync:" + account.name, 0);
    long lastSyncTime = syncMeta.getLong(LAST_SYNC, 0);
    long lastServerSyncTime = syncMeta.getLong(SERVER_LAST_SYNC, 0);

    // Check for changes in either app-wide auto sync registration information, or changes in
    // the user's preferences for auto sync on this account; if either changes, piggy back the
    // new registration information in this sync.
    long lastRegistrationChangeTime = C2DMessaging.getLastRegistrationChange(mContext);

    boolean autoSyncDesired = ContentResolver.getMasterSyncAutomatically()
            && ContentResolver.getSyncAutomatically(account, RemindMeContract.AUTHORITY);
    boolean autoSyncEnabled = syncMeta.getBoolean(DM_REGISTERED, false);

    // Will be 0 for no change, -1 for unregister, 1 for register.
    final int deviceRegChange;
    JsonRpcClient.Call deviceRegCall = null;
    if (autoSyncDesired != autoSyncEnabled || lastRegistrationChangeTime > lastSyncTime || initialize
            || manualSync) {/* w  w  w. j  av a2  s  .  c o  m*/

        String registrationId = C2DMessaging.getRegistrationId(mContext);
        deviceRegChange = (autoSyncDesired && registrationId != null) ? 1 : -1;

        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG,
                    "Auto sync selection or registration information has changed, "
                            + (deviceRegChange == 1 ? "registering" : "unregistering")
                            + " messaging for this device, for account " + account.name);
        }

        try {
            if (deviceRegChange == 1) {
                // Register device for auto sync on this account.
                deviceRegCall = new JsonRpcClient.Call(RemindMeProtocol.DevicesRegister.METHOD);
                JSONObject params = new JSONObject();

                DeviceRegistration device = new DeviceRegistration(clientDeviceId, DEVICE_TYPE, registrationId);
                params.put(RemindMeProtocol.DevicesRegister.ARG_DEVICE, device.toJSON());
                deviceRegCall.setParams(params);
            } else {
                // Unregister device for auto sync on this account.
                deviceRegCall = new JsonRpcClient.Call(RemindMeProtocol.DevicesUnregister.METHOD);
                JSONObject params = new JSONObject();
                params.put(RemindMeProtocol.DevicesUnregister.ARG_DEVICE_ID, clientDeviceId);
                deviceRegCall.setParams(params);
            }
        } catch (JSONException e) {
            logErrorMessage("Error generating device registration remote RPC parameters.", manualSync);
            e.printStackTrace();
            return;
        }
    } else {
        deviceRegChange = 0;
    }

    // Get the list of locally changed alerts. If this is an upload-only sync and there were
    // no local changes, cancel the sync.
    List<ModelJava.Alert> locallyChangedAlerts = null;
    try {
        locallyChangedAlerts = getLocallyChangedAlerts(provider, account, new Date(lastSyncTime));
    } catch (RemoteException e) {
        logErrorMessage("Remote exception accessing content provider: " + e.getMessage(), manualSync);
        e.printStackTrace();
        syncResult.stats.numIoExceptions++;
        return;
    }

    if (uploadOnly && locallyChangedAlerts.isEmpty() && deviceRegCall == null) {
        Log.i(TAG, "No local changes; upload-only sync canceled.");
        return;
    }

    // Set up the RPC sync calls
    final AuthenticatedJsonRpcJavaClient jsonRpcClient = new AuthenticatedJsonRpcJavaClient(mContext,
            Config.SERVER_AUTH_URL_TEMPLATE, Config.SERVER_RPC_URL);
    try {
        jsonRpcClient.blockingAuthenticateAccount(account,
                manualSync ? AuthenticatedJsonRpcJavaClient.NEED_AUTH_INTENT
                        : AuthenticatedJsonRpcJavaClient.NEED_AUTH_NOTIFICATION,
                false);
    } catch (AuthenticationException e) {
        logErrorMessage("Authentication exception when attempting to sync. root cause: " + e.getMessage(),
                manualSync);
        e.printStackTrace();

        syncResult.stats.numAuthExceptions++;
        return;
    } catch (OperationCanceledException e) {
        Log.i(TAG, "Sync for account " + account.name + " manually canceled.");
        return;
    } catch (RequestedUserAuthenticationException e) {
        syncResult.stats.numAuthExceptions++;
        return;
    } catch (InvalidAuthTokenException e) {
        logErrorMessage("Invalid auth token provided by AccountManager when attempting to " + "sync.",
                manualSync);
        e.printStackTrace();
        syncResult.stats.numAuthExceptions++;
        return;
    }

    // Set up the alerts sync call.
    JsonRpcClient.Call alertsSyncCall = new JsonRpcClient.Call(RemindMeProtocol.AlertsSync.METHOD);
    try {
        JSONObject params = new JSONObject();
        params.put(RemindMeProtocol.ARG_CLIENT_DEVICE_ID, clientDeviceId);
        params.put(RemindMeProtocol.AlertsSync.ARG_SINCE_DATE,
                Util.formatDateISO8601(new Date(lastServerSyncTime)));

        JSONArray locallyChangedAlertsJson = new JSONArray();
        for (ModelJava.Alert locallyChangedAlert : locallyChangedAlerts) {
            locallyChangedAlertsJson.put(locallyChangedAlert.toJSON());
        }

        params.put(RemindMeProtocol.AlertsSync.ARG_LOCAL_NOTES, locallyChangedAlertsJson);
        alertsSyncCall.setParams(params);
    } catch (JSONException e) {
        logErrorMessage("Error generating sync remote RPC parameters.", manualSync);
        e.printStackTrace();
        syncResult.stats.numParseExceptions++;
        return;
    }

    List<JsonRpcClient.Call> jsonRpcCalls = new ArrayList<JsonRpcClient.Call>();
    jsonRpcCalls.add(alertsSyncCall);
    if (deviceRegChange != 0)
        jsonRpcCalls.add(deviceRegCall);

    jsonRpcClient.callBatch(jsonRpcCalls, new JsonRpcClient.BatchCallback() {
        public void onData(Object[] data) {
            if (data[0] != null) {
                // Read alerts sync data.
                JSONObject dataJson = (JSONObject) data[0];
                try {
                    List<ModelJava.Alert> changedAlerts = new ArrayList<ModelJava.Alert>();
                    JSONArray alertsJson = dataJson.getJSONArray(RemindMeProtocol.AlertsSync.RET_NOTES);
                    for (int i = 0; i < alertsJson.length(); i++) {
                        changedAlerts.add(new ModelJava.Alert(alertsJson.getJSONObject(i)));
                    }

                    reconcileSyncedAlerts(provider, account, changedAlerts, syncResult.stats);

                    // If sync is successful (no exceptions thrown), update sync metadata
                    long newServerSyncTime = Util
                            .parseDateISO8601(
                                    dataJson.getString(RemindMeProtocol.AlertsSync.RET_NEW_SINCE_DATE))
                            .getTime();
                    syncMeta.edit().putLong(LAST_SYNC, newSyncTime).commit();
                    syncMeta.edit().putLong(SERVER_LAST_SYNC, newServerSyncTime).commit();
                    Log.i(TAG, "Sync complete, setting last sync time to " + Long.toString(newSyncTime));
                } catch (JSONException e) {
                    logErrorMessage("Error parsing alert sync RPC response", manualSync);
                    e.printStackTrace();
                    syncResult.stats.numParseExceptions++;
                    return;
                } catch (ParseException e) {
                    logErrorMessage("Error parsing alert sync RPC response", manualSync);
                    e.printStackTrace();
                    syncResult.stats.numParseExceptions++;
                    return;
                } catch (RemoteException e) {
                    logErrorMessage("RemoteException in reconcileSyncedAlerts: " + e.getMessage(), manualSync);
                    e.printStackTrace();
                    return;
                } catch (OperationApplicationException e) {
                    logErrorMessage("Could not apply batch operations to content provider: " + e.getMessage(),
                            manualSync);
                    e.printStackTrace();
                    return;
                } finally {
                    provider.release();
                }
            }

            // Read device reg data.
            if (deviceRegChange != 0) {
                // data[1] will be null in case of an error (successful unregisters
                // will have an empty JSONObject, not null).
                boolean registered = (data[1] != null && deviceRegChange == 1);
                syncMeta.edit().putBoolean(DM_REGISTERED, registered).commit();
                if (Log.isLoggable(TAG, Log.DEBUG)) {
                    Log.d(TAG, "Stored account auto sync registration state: " + Boolean.toString(registered));
                }
            }
        }

        public void onError(int callIndex, JsonRpcException e) {
            if (e.getHttpCode() == 403) {
                Log.w(TAG, "Got a 403 response, invalidating App Engine ACSID token");
                jsonRpcClient.invalidateAccountAcsidToken(account);
            }

            provider.release();
            logErrorMessage("Error calling remote alert sync RPC", manualSync);
            e.printStackTrace();
        }
    });
}

From source file:com.github.vseguip.sweet.rest.SugarRestAPI.java

public String getToken(String username, String passwd, Context context, Handler handler) {
    final HttpResponse resp;
    JSONObject jso_content = new JSONObject();
    try {/* w ww  .ja  v a 2 s .  co m*/
        JSONObject jso_user = new JSONObject();
        String sendpasswd = passwd;
        if (mEncryptPasswd)
            sendpasswd = encryptor(passwd);
        jso_user.put("user_name", username).put("password", sendpasswd);

        jso_content.put("user_auth", jso_user).put("application", "Sweet");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    final HttpPost post = prepareJSONRequest(jso_content.toString(), LOGIN_METHOD);
    HttpClient httpClient = getConnection();
    try {
        resp = httpClient.execute(post);
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Successful authentication");
            }

            String message = getResponseString(resp);
            String authToken;
            JSONObject json = null;
            try {
                // TODO: Convert JSON to contacts
                json = (JSONObject) new JSONTokener(message).nextValue();
                authToken = json.getString("id");
            } catch (JSONException e) {
                Log.i(TAG, "Error during login" + message);
                if (json != null) {
                    if (json.has("description")) {
                        try {
                            message = json.getString("description");// get
                            // errot
                            // message!
                        } catch (JSONException ex) {
                            e.printStackTrace();
                            Log.e(TAG, "JSON exception, should never have gotten here!");
                        }
                        ;
                    }
                }
                sendResult(false, handler, context, "Error during login " + message);
                return null;
            }
            sendResult(true, handler, context, authToken);
            return authToken;
        } else {
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Error authenticating" + resp.getStatusLine());
            }
            sendResult(false, handler, context, "Error authenticating" + resp.getStatusLine());
            return null;
        }
    } catch (final IOException e) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "IOException when getting authtoken", e);
        }
        sendResult(false, handler, context, "Error trying to connect to " + mServer.toString());
        return null;
    } catch (Exception e) {
        e.printStackTrace();
        sendResult(false, handler, context,
                "Error trying to validate your credentials. Check you server name and net connectivity.");
        return null;
    } finally {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "getAuthtoken completing");
        }
    }

}

From source file:com.gosuncn.core.percentlayout.PercentLayoutHelper.java

/**
 * Constructs a PercentLayoutInfo from attributes associated with a View.
 * Call this method from {@code LayoutParams(Context c, AttributeSet attrs)}
 * constructor./*from  w w  w.  j  av a 2 s  .c  om*/
 */
public static PercentLayoutInfo getPercentLayoutInfo(Context context, AttributeSet attrs) {
    PercentLayoutInfo info = null;
    TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.PercentLayout_Layout);

    // float value =
    // array.getFraction(R.styleable.PercentLayout_Layout_layout_widthPercent,
    // 1, 1,
    // -1f);
    String sizeStr = array.getString(R.styleable.PercentLayout_Layout_layout_widthPercent);
    PercentLayoutInfo.PercentVal percentVal = getPercentVal(sizeStr, true);
    if (percentVal != null) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "percent width: " + percentVal.percent);
        }
        info = info != null ? info : new PercentLayoutInfo();
        info.widthPercent = percentVal;
    }
    // value =
    // array.getFraction(R.styleable.PercentLayout_Layout_layout_heightPercent,
    // 1, 1, -1f);
    sizeStr = array.getString(R.styleable.PercentLayout_Layout_layout_heightPercent);
    percentVal = getPercentVal(sizeStr, false);

    if (sizeStr != null) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "percent height: " + percentVal.percent);
        }
        info = info != null ? info : new PercentLayoutInfo();
        info.heightPercent = percentVal;
    }

    // value =
    // array.getFraction(R.styleable.PercentLayout_Layout_layout_marginPercent,
    // 1, 1, -1f);
    sizeStr = array.getString(R.styleable.PercentLayout_Layout_layout_marginPercent);
    // just for judge
    percentVal = getPercentVal(sizeStr, false);

    if (percentVal != null) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "percent margin: " + percentVal.percent);
        }
        info = info != null ? info : new PercentLayoutInfo();
        info.leftMarginPercent = getPercentVal(sizeStr, true);
        info.topMarginPercent = getPercentVal(sizeStr, false);
        info.rightMarginPercent = getPercentVal(sizeStr, true);
        info.bottomMarginPercent = getPercentVal(sizeStr, false);
    }
    // value =
    // array.getFraction(R.styleable.PercentLayout_Layout_layout_marginLeftPercent,
    // 1, 1,
    // -1f);
    sizeStr = array.getString(R.styleable.PercentLayout_Layout_layout_marginLeftPercent);
    percentVal = getPercentVal(sizeStr, true);
    if (percentVal != null) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "percent left margin: " + percentVal.percent);
        }
        info = info != null ? info : new PercentLayoutInfo();
        info.leftMarginPercent = percentVal;
    }

    // value =
    // array.getFraction(R.styleable.PercentLayout_Layout_layout_marginTopPercent,
    // 1, 1,
    // -1f);
    sizeStr = array.getString(R.styleable.PercentLayout_Layout_layout_marginTopPercent);
    percentVal = getPercentVal(sizeStr, false);
    if (percentVal != null) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "percent top margin: " + percentVal.percent);
        }
        info = info != null ? info : new PercentLayoutInfo();
        info.topMarginPercent = percentVal;
    }
    // value =
    // array.getFraction(R.styleable.PercentLayout_Layout_layout_marginRightPercent,
    // 1, 1,
    // -1f);
    sizeStr = array.getString(R.styleable.PercentLayout_Layout_layout_marginRightPercent);
    percentVal = getPercentVal(sizeStr, true);
    if (percentVal != null) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "percent right margin: " + percentVal.percent);
        }
        info = info != null ? info : new PercentLayoutInfo();
        info.rightMarginPercent = percentVal;
    }
    // value =
    // array.getFraction(R.styleable.PercentLayout_Layout_layout_marginBottomPercent,
    // 1, 1,
    // -1f);
    sizeStr = array.getString(R.styleable.PercentLayout_Layout_layout_marginBottomPercent);
    percentVal = getPercentVal(sizeStr, false);
    if (percentVal != null) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "percent bottom margin: " + percentVal.percent);
        }
        info = info != null ? info : new PercentLayoutInfo();
        info.bottomMarginPercent = percentVal;
    }
    // value =
    // array.getFraction(R.styleable.PercentLayout_Layout_layout_marginStartPercent,
    // 1, 1,
    // -1f);
    sizeStr = array.getString(R.styleable.PercentLayout_Layout_layout_marginStartPercent);
    percentVal = getPercentVal(sizeStr, true);
    if (percentVal != null) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "percent start margin: " + percentVal.percent);
        }
        info = info != null ? info : new PercentLayoutInfo();
        info.startMarginPercent = percentVal;
    }
    // value =
    // array.getFraction(R.styleable.PercentLayout_Layout_layout_marginEndPercent,
    // 1, 1,
    // -1f);
    sizeStr = array.getString(R.styleable.PercentLayout_Layout_layout_marginEndPercent);
    percentVal = getPercentVal(sizeStr, true);
    if (percentVal != null) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "percent end margin: " + percentVal.percent);
        }
        info = info != null ? info : new PercentLayoutInfo();
        info.endMarginPercent = percentVal;
    }

    // textSizePercent
    sizeStr = array.getString(R.styleable.PercentLayout_Layout_layout_textSizePercent);
    percentVal = getPercentVal(sizeStr, false);
    if (percentVal != null) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "percent text size: " + percentVal.percent);
        }
        info = info != null ? info : new PercentLayoutInfo();
        info.textSizePercent = percentVal;
    }
    array.recycle();
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "constructed: " + info);
    }
    return info;
}

From source file:com.android.contacts.DynamicShortcuts.java

@VisibleForTesting
void refresh() {//from  w  ww . ja  va 2s .c  o  m
    // Guard here in addition to initialize because this could be run by the JobScheduler
    // after permissions are revoked (maybe)
    if (!hasRequiredPermissions())
        return;

    final List<ShortcutInfo> shortcuts = getStrequentShortcuts();
    mShortcutManager.setDynamicShortcuts(shortcuts);
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "set dynamic shortcuts " + shortcuts);
    }
    updatePinned();
}

From source file:org.kotemaru.android.sample.webview.XMLHttpRequestXS.java

private void doRequest(String body) throws Throwable {
    try {//w  ww .ja  va  2s  . c  o  m
        if (POST.equals(_request.getMethod())) {
            HttpPost httpPost = (HttpPost) _request;
            Header header = httpPost.getFirstHeader(CONTENT_TYPE);
            String ctype = header != null ? header.getValue() : "plain/text; charset=" + HTTP.UTF_8;
            httpPost.setEntity(new StringEntity(body, ctype));
        }
        _response = _client.execute(_request);
        _responseCode = _response.getStatusLine().getStatusCode();

        CookieManager cookieManager = CookieManager.getInstance();
        Header[] cookies = _response.getHeaders("Set-Cookie");
        for (int i = 0; i < cookies.length; i++) {
            cookieManager.setCookie(_request.getURI().toString(), cookies[i].getValue());
        }

        if (Log.isLoggable(TAG, Log.DEBUG))
            debugLog();
    } catch (Throwable t) {
        Log.e(TAG, t.getMessage(), t);
        _request.abort();
        throw t;
    }
}

From source file:com.emorym.android_pusher.Pusher.java

public void connect() {
    String prefix = mEncrypted ? HTTPS_PREFIX : HTTP_PREFIX;
    int port = mEncrypted ? WSS_PORT : WS_PORT;

    String path = "/app/" + mApplicationkey + "?client=js&version=" + VERSION;

    try {/*ww  w .j a  va  2s.  c  om*/
        URI url = new URI(prefix + HOST + ":" + port + path);
        if (Log.isLoggable(TAG, DEBUG))
            Log.d(TAG, "Connecting to: " + url.toString());
        mWebSocket = new WebSocketConnection(url);
        mWebSocket.setTrustAllCerts(trustAllCerts);
        mWebSocket.setEventHandler(new WebSocketEventHandler() {
            public void onOpen() {
                if (Log.isLoggable(TAG, DEBUG))
                    Log.d(TAG, "WebSocket Open");
                subscribeToAllChannels();
            }

            public void onMessage(WebSocketMessage message) {
                try {
                    if (Log.isLoggable(TAG, DEBUG))
                        Log.d(TAG, "Message: " + message.getText());

                    JSONObject jsonMessage = new JSONObject(message.getText());

                    String event = jsonMessage.optString("event", null);

                    if (event.equals("pusher:connection_established")) {
                        JSONObject data = new JSONObject(jsonMessage.getString("data"));

                        mSocketId = data.getString("socket_id");

                        if (Log.isLoggable(TAG, DEBUG))
                            Log.d(TAG, "Connection Established with Socket Id: " + mSocketId);
                    } else {
                        Bundle b = new Bundle();

                        b.putString("event", event);
                        b.putString("data", jsonMessage.getString("data"));

                        // backwards compatibility
                        b.putString("type", "pusher");
                        b.putString("message", message.getText());

                        if (jsonMessage.has("channel")) {
                            b.putString("channel", jsonMessage.getString("channel"));
                        }

                        Message msg = new Message();
                        msg.setData(b);

                        mHandler.sendMessage(msg);
                    }
                } catch (JSONException e) {
                    if (Log.isLoggable(TAG, DEBUG))
                        Log.d(TAG, "JSON exception", e);
                }
            }

            public void onClose() {
                if (Log.isLoggable(TAG, DEBUG))
                    Log.d(TAG, "WebSocket Closed");
            }
        });

        mWatchdog = new Thread(new Runnable() {
            public void run() {
                boolean interrupted = false;
                while (!interrupted) {
                    try {
                        Thread.sleep(WATCHDOG_SLEEP_TIME_MS);
                        if (!mWebSocket.isConnected())
                            mWebSocket.connect();
                    } catch (InterruptedException e) {
                        interrupted = true;
                    } catch (Exception e) {
                        if (Log.isLoggable(TAG, DEBUG))
                            Log.d(TAG, "Exception connecting", e);
                    }
                }
            }
        });

        mWatchdog.start();
    } catch (WebSocketException e) {
        if (Log.isLoggable(TAG, DEBUG))
            Log.d(TAG, "Web socket exception", e);
    } catch (URISyntaxException e) {
        if (Log.isLoggable(TAG, DEBUG))
            Log.d(TAG, "URI syntax exception", e);
    }
}

From source file:com.dirkgassen.wator.ui.fragment.WatorDisplay.java

/**
 * Called when the {@link WorldHost} has updated its simulator. This method repaints the bitmap for the view.
 *
 * @param world {@link com.dirkgassen.wator.simulator.Simulator.WorldInspector} of the {@link Simulator} that was
 *              updated/*ww w.j  ava 2s.c om*/
 */
@Override
public void worldUpdated(Simulator.WorldInspector world) {
    if (Log.isLoggable("Wa-Tor", Log.VERBOSE)) {
        Log.v("Wa-Tor", "Updating image");
    }
    long startUpdate = System.currentTimeMillis();

    int worldWidth = world.getWorldWidth();
    int worldHeight = world.getWorldHeight();
    int fishBreedTime = world.getFishBreedTime();
    int sharkStarveTime = world.getSharkStarveTime();

    if (planetBitmap == null || planetBitmap.getWidth() != worldWidth
            || planetBitmap.getHeight() != worldHeight) {
        if (Log.isLoggable("Wa-Tor", Log.DEBUG)) {
            Log.d("Wa-Tor", "(Re)creating bitmap/pixels");
        }
        planetBitmap = Bitmap.createBitmap(worldWidth, worldHeight, Bitmap.Config.ARGB_8888);
        pixels = new int[worldWidth * worldHeight];
    }
    if (fishAgeColors == null || fishAgeColors.length != fishBreedTime) {
        if (Log.isLoggable("Wa-Tor", Log.DEBUG)) {
            Log.d("Wa-Tor", "(Re)creating fish colors");
        }
        fishAgeColors = calculateIndividualAgeColors(fishBreedTime,
                ContextCompat.getColor(getContext(), R.color.fish_young),
                ContextCompat.getColor(getContext(), R.color.fish_old));
    }
    if (sharkAgeColors == null || sharkAgeColors.length != sharkStarveTime) {
        if (Log.isLoggable("Wa-Tor", Log.DEBUG)) {
            Log.d("Wa-Tor", "(Re)creating shark colors");
        }
        sharkAgeColors = calculateIndividualAgeColors(sharkStarveTime,
                ContextCompat.getColor(getContext(), R.color.shark_young),
                ContextCompat.getColor(getContext(), R.color.shark_old));
    }

    do {
        if (world.isEmpty()) {
            pixels[world.getCurrentPosition()] = waterColor;
        } else if (world.isFish()) {
            pixels[world.getCurrentPosition()] = fishAgeColors[world.getFishAge() - 1];
        } else {
            pixels[world.getCurrentPosition()] = sharkAgeColors[world.getSharkHunger() - 1];
        }
    } while (world.moveToNext() != Simulator.WorldInspector.RESET);
    if (Log.isLoggable("Wa-Tor", Log.VERBOSE)) {
        Log.v("Wa-Tor", "Generating pixels " + (System.currentTimeMillis() - startUpdate) + " ms");
    }
    synchronized (WatorDisplay.this) {
        if (planetBitmap != null) {
            int width = planetBitmap.getWidth();
            int height = planetBitmap.getHeight();
            planetBitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        }
    }
    handler.post(updateImageRunner);
    if (Log.isLoggable("Wa-Tor", Log.VERBOSE)) {
        Log.v("Wa-Tor", "Repainting took " + (System.currentTimeMillis() - startUpdate) + " ms");
    }
}

From source file:com.samsung.multiwindow.MultiWindow.java

/**
 * Executes the request and returns PluginResult.
 * /*from w w  w.  j a va2 s. c  o  m*/
 * @param action
 *            The action to be executed.
 * @param args
 *            JSONArray of arguments for the plugin.
 * @param callbackContext
 *            The callback id used when calling back into JavaScript.
 * @return A PluginResult object with a status and message.
 */
public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext)
        throws JSONException {

    int ret = -1;

    try {
        // window type argument index is same in all cases of
        // createmultiwindow
        windowType = args.getString(mainFsOptions.WINDOW_TYPE.ordinal());

        // Do not allow apis if metadata is missing
        if (!pluginMetadata) {
            callbackContext.error("METADATA_MISSING");
            Log.e("MultiWindow", "Metadata is missing");
            return false;
        }

        // Verify the multiwindow capability of the device
        ret = intializeMultiwindow();
        if (ret != INIT_SUCCESS) {

            switch (ret) {

            case SsdkUnsupportedException.VENDOR_NOT_SUPPORTED:
                callbackContext.error("VENDOR_NOT_SUPPORTED");
                break;
            case SsdkUnsupportedException.DEVICE_NOT_SUPPORTED:
                callbackContext.error("DEVICE_NOT_SUPPORTED");
                break;
            default:
                callbackContext.error("MUTLI_WINDOW_INITIALIZATION_FAILED");
                break;
            }

            return false;
        }

        if (Log.isLoggable(MULTIWINDOW, Log.DEBUG)) {
            Log.d(TAG, "Multiwindow initialization is successful" + ret);
        }

        // Check window support
        windowSupport = isMultiWindowSupported(windowType);
        if (windowType.equalsIgnoreCase("freestyle")) {

            if (!windowSupport) {
                callbackContext.error("FREE_STYLE_NOT_SUPPORTED");
            }

        } else if (windowType.equalsIgnoreCase("splitstyle")) {

            if (!windowSupport) {
                callbackContext.error("SPLIT_STYLE_NOT_SUPPORTED");
            }
        } else {

            callbackContext.error("INVALID_WINDOW_TYPE");
        }

        if (Log.isLoggable(MULTIWINDOW, Log.DEBUG)) {
            Log.d(TAG, "MultiWindow window type Supported:" + windowSupport);
        }

        // Get zone info in case of split style
        if (windowSupport && (action.equals("action_main") || action.equals("action_view"))) {

            if (windowType.equalsIgnoreCase("splitstyle")) {

                switch (args.optInt(mainSsOptions.ZONE_INFO.ordinal())) {
                case ZONE_A:
                    Log.d(TAG, "Zone A selected");
                    zoneInfo = SMultiWindowActivity.ZONE_A;
                    break;
                case ZONE_B:
                    Log.d(TAG, "Zone B selected");
                    zoneInfo = SMultiWindowActivity.ZONE_B;
                    break;
                case ZONE_FULL:
                    Log.d(TAG, "Zone Full selected");
                    zoneInfo = SMultiWindowActivity.ZONE_FULL;
                    break;
                default:
                    Log.d(TAG, "Zone is not selected");
                    callbackContext.error("INVALID_ZONEINFO");
                    return false;
                }
            }
        }
    } catch (Exception e) {

        callbackContext.error(e.getMessage());
    }

    if (action.equals("action_main")) {

        if (Log.isLoggable(MULTIWINDOW, Log.DEBUG)) {
            Log.d(TAG, "Action is action_main");
        }
        if (!windowSupport) {
            return false;
        }

        cordova.getThreadPool().execute(new Runnable() {

            public void run() {

                Intent intent = new Intent(Intent.ACTION_MAIN);
                int packageNameIndex = 0;
                int activityNameIndex = 0;
                float scaleInfo = 0;
                int zoneInfo = getZoneInfo();
                String windowType = getWindowType();

                if (windowType.equalsIgnoreCase("splitstyle")) {
                    packageNameIndex = mainSsOptions.PACKAGE_NAME.ordinal();
                    activityNameIndex = mainSsOptions.ACTIVITY_NAME.ordinal();
                } else {
                    packageNameIndex = mainFsOptions.PACKAGE_NAME.ordinal();
                    activityNameIndex = mainFsOptions.ACTIVITY_NAME.ordinal();
                }

                try {
                    intent.setComponent(new ComponentName(args.getString(packageNameIndex),
                            args.getString(activityNameIndex)));

                    if (windowType.equalsIgnoreCase("splitstyle")) {
                        SMultiWindowActivity.makeMultiWindowIntent(intent, zoneInfo);
                    } else {

                        scaleInfo = ((float) args.getDouble(mainFsOptions.SCALE_INFO.ordinal())) / 100;
                        if (scaleInfo < 0.6 || scaleInfo > 1.0) {
                            callbackContext.error("INVALID_SCALEINFO");
                            return;
                        }
                        SMultiWindowActivity.makeMultiWindowIntent(intent, scaleInfo);
                    }
                } catch (Exception e) { // May be JSONException

                    callbackContext.error(e.getMessage());
                }
                try {
                    cordova.getActivity().startActivity(intent);
                } catch (ActivityNotFoundException activityNotFound) {
                    callbackContext.error("ACTIVITY_NOT_FOUND");
                }

                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
            }
        });
        return true;

    } else if (action.equals("action_view")) {

        if (Log.isLoggable(MULTIWINDOW, Log.DEBUG)) {
            Log.d(TAG, "Action is action_view");
        }
        if (!windowSupport) {
            return false;
        }

        cordova.getThreadPool().execute(new Runnable() {

            public void run() {

                int dataUriIndex = 0;
                float scaleInfo = 0;
                Intent dataUrl = null;
                String windowType = getWindowType();
                int zoneInfo = getZoneInfo();

                if (windowType.equalsIgnoreCase("splitstyle")) {
                    dataUriIndex = viewSsOptions.DATA_URI.ordinal();

                } else {
                    dataUriIndex = viewFsOptions.DATA_URI.ordinal();
                }
                String dataUri = null;
                try {
                    dataUri = args.getString(dataUriIndex);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (dataUri == null || dataUri.equals("") || dataUri.equals("null")) {
                    callbackContext.error("INVALID_DATA_URI");
                    return;
                } else {
                    boolean isUriProper = false;
                    for (String schema : URI_SCHEMA_SUPPORTED) {
                        if (dataUri.startsWith(schema)) {
                            isUriProper = true;
                            break;
                        }
                    }
                    if (!isUriProper) {
                        callbackContext.error("INVALID_DATA_URI");
                        return;
                    }
                }
                try {
                    dataUrl = new Intent(Intent.ACTION_VIEW, Uri.parse(dataUri));

                    if (windowType.equalsIgnoreCase("splitstyle")) {
                        SMultiWindowActivity.makeMultiWindowIntent(dataUrl, zoneInfo);
                    } else {
                        scaleInfo = ((float) args.getDouble(viewFsOptions.SCALE_INFO.ordinal())) / 100;
                        if (scaleInfo < 0.6 || scaleInfo > 1.0) {
                            callbackContext.error("INVALID_SCALEINFO");
                            return;
                        }
                        SMultiWindowActivity.makeMultiWindowIntent(dataUrl, scaleInfo);
                    }
                } catch (Exception e) { // May be JSONException

                    callbackContext.error(e.getMessage());
                }

                try {

                    if (dataUrl != null) {
                        cordova.getActivity().startActivity(dataUrl);
                    }

                } catch (ActivityNotFoundException activityNotFound) {
                    callbackContext.error("ACTIVITY_NOT_FOUND");
                }
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
            }
        });
        return true;

    } else if (action.equals("action_check")) {

        if (Log.isLoggable(MULTIWINDOW, Log.DEBUG)) {
            Log.d(TAG, "Action is action_check");
        }

        if (windowSupport) {

            callbackContext.success();
        }
        return true;

    } else if (action.equals("action_getapps")) {

        if (Log.isLoggable(MULTIWINDOW, Log.DEBUG)) {
            Log.d(TAG, "Action is action_getapps");
        }

        if (!windowSupport) {

            return false;
        }

        getMultiWindowApps(windowType, callbackContext);
        return true;

    }

    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, 0));
    return false;
}

From source file:com.locadz.AdUnitAllocationService.java

/**
 * load the allocation configuration for the adunit from external source.
 *
 * @param adUnitContext the context of the adunit.
 * @return the allocation configuration for the adunit as a json string.
 *///w  w w . j  a  v  a2 s  .  c  o  m
String loadFromRemote(AdUnitContext adUnitContext) {

    Log.d(LOG_TAG, String.format("Fetching config with %s", adUnitContext));

    HttpClient httpClient = HttpClientFactory.getInstance();
    URI uri = LocadzUtils.getInfoUri(adUnitContext);
    HttpGet httpGet = new HttpGet(uri);

    String ret = null;
    try {

        HttpResponse httpResponse = httpClient.execute(httpGet);

        // if response is 1xx, 2xx or 3xx, we would return the response body
        if (httpResponse.getStatusLine().getStatusCode() < HttpStatus.SC_BAD_REQUEST) {
            Log.d(LOG_TAG, httpResponse.getStatusLine().toString());

            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                ret = EntityUtils.toString(entity);
            }
        }
    } catch (ClientProtocolException e) {
        Log.e(LOG_TAG, "Caught ClientProtocolException in loadFromRemote()", e);
    } catch (IOException e) {
        Log.e(LOG_TAG, "Caught IOException in loadFromRemote()", e);
    }

    if (Log.isLoggable(LOG_TAG, Log.DEBUG)) {
        Log.d(LOG_TAG, String.format("Fetched Allocations is %s", ret));
    }
    return ret;
}

From source file:com.ibm.commerce.worklight.android.maps.StoreMapActivity.java

/**
 * Back button press exits the activity and returns to the store
 * @see android.support.v4.app.FragmentActivity#onBackPressed()
 *//*w  w w . j a  va2  s  . c om*/
@Override
public void onBackPressed() {
    final String METHOD_NAME = CLASS_NAME + ".onBackPressed()";
    boolean loggingEnabled = Log.isLoggable(LOG_TAG, Log.DEBUG);
    if (loggingEnabled) {
        Log.d(METHOD_NAME, "ENTRY");
    }
    setResult(RESULT_OK, new Intent());
    finish();
    if (loggingEnabled) {
        Log.d(METHOD_NAME, "EXIT");
    }
}