List of usage examples for android.net Uri getScheme
@Nullable public abstract String getScheme();
From source file:org.apache.cordova.core.FileTransfer.java
/** * Downloads a file form a given URL and saves it to the specified directory. * * @param source URL of the server to receive the file * @param target Full path of the file on the file system */// ww w .j a v a 2 s . c om private void download(final String source, final String target, JSONArray args, CallbackContext callbackContext) throws JSONException { Log.d(LOG_TAG, "download " + source + " to " + target); final CordovaResourceApi resourceApi = webView.getResourceApi(); final boolean trustEveryone = args.optBoolean(2); final String objectId = args.getString(3); final JSONObject headers = args.optJSONObject(4); final Uri sourceUri = resourceApi.remapUri(Uri.parse(source)); // Accept a path or a URI for the source. Uri tmpTarget = Uri.parse(target); final Uri targetUri = resourceApi .remapUri(tmpTarget.getScheme() != null ? tmpTarget : Uri.fromFile(new File(target))); int uriType = CordovaResourceApi.getUriType(sourceUri); final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS; final boolean isLocalTransfer = !useHttps && uriType != CordovaResourceApi.URI_TYPE_HTTP; if (uriType == CordovaResourceApi.URI_TYPE_UNKNOWN) { JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0); Log.e(LOG_TAG, "Unsupported URI: " + targetUri); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); return; } // TODO: refactor to also allow resources & content: if (!isLocalTransfer && !Config.isUrlWhiteListed(source)) { Log.w(LOG_TAG, "Source URL is not in white list: '" + source + "'"); JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, null, 401); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); return; } final RequestContext context = new RequestContext(source, target, callbackContext); synchronized (activeRequests) { activeRequests.put(objectId, context); } cordova.getThreadPool().execute(new Runnable() { public void run() { if (context.aborted) { return; } HttpURLConnection connection = null; HostnameVerifier oldHostnameVerifier = null; SSLSocketFactory oldSocketFactory = null; File file = null; PluginResult result = null; TrackingInputStream inputStream = null; OutputStream outputStream = null; try { OpenForReadResult readResult = null; outputStream = resourceApi.openOutputStream(targetUri); file = resourceApi.mapUriToFile(targetUri); context.targetFile = file; Log.d(LOG_TAG, "Download file:" + sourceUri); FileProgressResult progress = new FileProgressResult(); if (isLocalTransfer) { readResult = resourceApi.openForRead(sourceUri); if (readResult.length != -1) { progress.setLengthComputable(true); progress.setTotal(readResult.length); } inputStream = new SimpleTrackingInputStream(readResult.inputStream); } else { // connect to server // Open a HTTP connection to the URL based on protocol connection = resourceApi.createHttpConnection(sourceUri); if (useHttps && trustEveryone) { // Setup the HTTPS connection class to trust everyone HttpsURLConnection https = (HttpsURLConnection) connection; oldSocketFactory = trustAllHosts(https); // Save the current hostnameVerifier oldHostnameVerifier = https.getHostnameVerifier(); // Setup the connection not to verify hostnames https.setHostnameVerifier(DO_NOT_VERIFY); } connection.setRequestMethod("GET"); // TODO: Make OkHttp use this CookieManager by default. String cookie = CookieManager.getInstance().getCookie(sourceUri.toString()); if (cookie != null) { connection.setRequestProperty("cookie", cookie); } // This must be explicitly set for gzip progress tracking to work. connection.setRequestProperty("Accept-Encoding", "gzip"); // Handle the other headers if (headers != null) { addHeadersToRequest(connection, headers); } connection.connect(); if (connection.getContentEncoding() == null || connection.getContentEncoding().equalsIgnoreCase("gzip")) { // Only trust content-length header if we understand // the encoding -- identity or gzip progress.setLengthComputable(true); progress.setTotal(connection.getContentLength()); } inputStream = getInputStream(connection); } try { synchronized (context) { if (context.aborted) { return; } context.currentInputStream = inputStream; } // write bytes to file byte[] buffer = new byte[MAX_BUFFER_SIZE]; int bytesRead = 0; while ((bytesRead = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, bytesRead); // Send a progress event. progress.setLoaded(inputStream.getTotalRawBytesRead()); PluginResult progressResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject()); progressResult.setKeepCallback(true); context.sendPluginResult(progressResult); } } finally { context.currentInputStream = null; safeClose(inputStream); safeClose(outputStream); } Log.d(LOG_TAG, "Saved file: " + target); // create FileEntry object JSONObject fileEntry = FileUtils.getEntry(file); result = new PluginResult(PluginResult.Status.OK, fileEntry); } catch (FileNotFoundException e) { JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, connection); Log.e(LOG_TAG, error.toString(), e); result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error); } catch (IOException e) { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection); Log.e(LOG_TAG, error.toString(), e); result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); result = new PluginResult(PluginResult.Status.JSON_EXCEPTION); } catch (Throwable e) { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection); Log.e(LOG_TAG, error.toString(), e); result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error); } finally { safeClose(outputStream); synchronized (activeRequests) { activeRequests.remove(objectId); } if (connection != null) { // Revert back to the proper verifier and socket factories if (trustEveryone && useHttps) { HttpsURLConnection https = (HttpsURLConnection) connection; https.setHostnameVerifier(oldHostnameVerifier); https.setSSLSocketFactory(oldSocketFactory); } } if (result == null) { result = new PluginResult(PluginResult.Status.ERROR, createFileTransferError(CONNECTION_ERR, source, target, connection)); } // Remove incomplete download. if (result.getStatus() != PluginResult.Status.OK.ordinal() && file != null) { file.delete(); } context.sendPluginResult(result); } } }); }
From source file:de.schildbach.litecoinwallet.ui.SendCoinsFragment.java
@Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.send_coins_fragment, container); receivingAddressView = (AutoCompleteTextView) view.findViewById(R.id.send_coins_receiving_address); receivingAddressView.setAdapter(new AutoCompleteAddressAdapter(activity, null)); receivingAddressView.setOnFocusChangeListener(receivingAddressListener); receivingAddressView.addTextChangedListener(receivingAddressListener); receivingStaticView = view.findViewById(R.id.send_coins_receiving_static); receivingStaticAddressView = (TextView) view.findViewById(R.id.send_coins_receiving_static_address); receivingStaticLabelView = (TextView) view.findViewById(R.id.send_coins_receiving_static_label); receivingStaticView.setOnFocusChangeListener(new OnFocusChangeListener() { private ActionMode actionMode; @Override/*w w w . j ava 2s . c om*/ public void onFocusChange(final View v, final boolean hasFocus) { if (hasFocus) actionMode = activity.startActionMode(new ReceivingAddressActionMode()); else actionMode.finish(); } }); final CurrencyAmountView btcAmountView = (CurrencyAmountView) view.findViewById(R.id.send_coins_amount_btc); btcAmountView.setCurrencySymbol(btcShift == 0 ? Constants.CURRENCY_CODE_BTC : Constants.CURRENCY_CODE_MBTC); btcAmountView.setInputPrecision(btcShift == 0 ? Constants.BTC_MAX_PRECISION : Constants.MBTC_MAX_PRECISION); btcAmountView.setHintPrecision(btcPrecision); btcAmountView.setShift(btcShift); final CurrencyAmountView localAmountView = (CurrencyAmountView) view .findViewById(R.id.send_coins_amount_local); localAmountView.setInputPrecision(Constants.LOCAL_PRECISION); localAmountView.setHintPrecision(Constants.LOCAL_PRECISION); amountCalculatorLink = new CurrencyCalculatorLink(btcAmountView, localAmountView); bluetoothEnableView = (CheckBox) view.findViewById(R.id.send_coins_bluetooth_enable); bluetoothEnableView.setChecked(bluetoothAdapter != null && bluetoothAdapter.isEnabled()); bluetoothEnableView.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) { if (isChecked && !bluetoothAdapter.isEnabled()) { // try to enable bluetooth startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), REQUEST_CODE_ENABLE_BLUETOOTH); } } }); bluetoothMessageView = (TextView) view.findViewById(R.id.send_coins_bluetooth_message); sentTransactionView = (ListView) view.findViewById(R.id.send_coins_sent_transaction); sentTransactionListAdapter = new TransactionsListAdapter(activity, wallet, application.maxConnectedPeers(), false); sentTransactionView.setAdapter(sentTransactionListAdapter); viewGo = (Button) view.findViewById(R.id.send_coins_go); viewGo.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { validateReceivingAddress(true); validateAmounts(true); if (everythingValid()) handleGo(); } }); viewCancel = (Button) view.findViewById(R.id.send_coins_cancel); viewCancel.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { if (state == State.INPUT) activity.setResult(Activity.RESULT_CANCELED); activity.finish(); } }); popupMessageView = (TextView) inflater.inflate(R.layout.send_coins_popup_message, container); popupAvailableView = inflater.inflate(R.layout.send_coins_popup_available, container); if (savedInstanceState != null) { restoreInstanceState(savedInstanceState); } else { final Intent intent = activity.getIntent(); final String action = intent.getAction(); final Uri intentUri = intent.getData(); final String scheme = intentUri != null ? intentUri.getScheme() : null; if ((Intent.ACTION_VIEW.equals(action) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) && intentUri != null && "litecoin".equals(scheme)) initStateFromBitcoinUri(intentUri); else if (intent.hasExtra(SendCoinsActivity.INTENT_EXTRA_ADDRESS)) initStateFromIntentExtras(intent.getExtras()); } return view; }
From source file:com.adobe.phonegap.contentsync.Sync.java
private Uri getUriForArg(String arg) { Uri tmpTarget = Uri.parse(arg); return webView.getResourceApi() .remapUri(tmpTarget.getScheme() != null ? tmpTarget : Uri.fromFile(new File(arg))); }
From source file:com.baroq.pico.google.PlayServices.java
@Override public void onGamesLoaded(int statusCode, GameBuffer buffer) { JSONObject json = new JSONObject(); try {/*from w w w .j a v a 2 s . c om*/ json.put("type", GAMES_LOADED); json.put("statusCode", statusCode); switch (statusCode) { case GamesClient.STATUS_OK: // if data was successfully loaded and is up-to-date. JSONArray games = new JSONArray(); JSONObject game; for (int i = 0, l = buffer.getCount(); i < l; i++) { Game g = buffer.get(i); game = new JSONObject(); game.put("achievementTotalCount", g.getAchievementTotalCount()); game.put("applicationId", g.getApplicationId()); game.put("description", g.getDescription()); game.put("developerName", g.getDeveloperName()); game.put("displayName", g.getDisplayName()); Uri uri = g.getFeaturedImageUri(); if (null != uri) game.put("featuredImageUri", uri.getScheme() + ':' + uri.getSchemeSpecificPart()); uri = g.getHiResImageUri(); if (null != uri) game.put("hiResImageUri", uri.getScheme() + ':' + uri.getSchemeSpecificPart()); uri = g.getIconImageUri(); if (null != uri) game.put("iconImageUri", uri.getScheme() + ':' + uri.getSchemeSpecificPart()); game.put("leaderboardCount", g.getLeaderboardCount()); game.put("primaryCategory", g.getPrimaryCategory()); game.put("secondaryCategory", g.getSecondaryCategory()); games.put(game); } json.put("list", games); break; case GamesClient.STATUS_INTERNAL_ERROR: // if an unexpected error occurred in the service break; case GamesClient.STATUS_NETWORK_ERROR_STALE_DATA: // if the device was unable to communicate with the network. In this case, the operation is not retried automatically. break; case GamesClient.STATUS_CLIENT_RECONNECT_REQUIRED: // need to reconnect GamesClient mHelper.reconnectClients(clientTypes); break; case GamesClient.STATUS_LICENSE_CHECK_FAILED: // The game is not licensed to the user. Further calls will return the same code. break; default: // error break; } } catch (JSONException ex) { Log.e(TAG, "GAMES_LOADED [" + statusCode + "] exception: " + ex.getMessage()); return; } buffer.close(); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, json); pluginResult.setKeepCallback(true); connectionCB.sendPluginResult(pluginResult); }
From source file:edu.mit.mobile.android.locast.data.Sync.java
/** * Sync the given URI to the server. Will compare dates and do a two-way sync. * Does not yet handle the case where both server and and local are modified * (collisions)//from w ww.ja v a 2 s . c o m * * @param toSync URI of the object to sync. Generally, this should be the dir URI * @param sync A new object that extends JsonSyncableItem. This is needed for the JSON * serialization routine in it, as well as the sync map. * @throws IOException */ private void sync(Uri toSync, JsonSyncableItem sync, SyncProgressNotifier syncProgress, Bundle extras) throws SyncException, IOException { String netPath; boolean haveItemPubUri = false; if ("http".equals(toSync.getScheme()) || "https".equals(toSync.getScheme())) { netPath = toSync.getPath(); toSync = (Uri) extras.get(EXTRA_DESTINATION_URI); haveItemPubUri = true; } else { netPath = null; } final String contentType = getContentResolver().getType(toSync); final Cursor c = cr.query(toSync, sync.getFullProjection(), null, null, null); try { syncProgress.addPendingTasks(c.getCount()); // Handle a list of items. if (contentType.startsWith(CONTENT_TYPE_PREFIX_DIR)) { // load from the network first... if (netPath == null) { netPath = MediaProvider.getPublicPath(this, toSync); } syncNetworkList(toSync, netPath, sync, syncProgress); } else if (haveItemPubUri) { syncNetworkItem(toSync, netPath, sync, syncProgress); } // then load locally. if (DEBUG) { Log.d(TAG, "have " + c.getCount() + " local items to sync"); } for (c.moveToFirst(); (currentSyncTask != null && !currentSyncTask.isCancelled()) && !c.isAfterLast(); c .moveToNext()) { try { syncItem(toSync, c, null, sync, syncProgress, netPath); syncProgress.completeTask(); } catch (final SyncItemDeletedException side) { if (DEBUG) { Log.d(TAG, side.getLocalizedMessage() + " Deleting..."); } cr.delete(side.getItem(), null, null); //side.printStackTrace(); syncProgress.completeTask(); continue; } } } catch (final NoPublicPath npp) { // XXX this should be a hard error Log.e(TAG, "Sync Error: " + npp.getLocalizedMessage()); return; } finally { c.close(); } }
From source file:ja.keystore00.wallet.ui.SendCoinsFragment.java
@Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.send_coins_fragment, container); receivingAddressView = (AutoCompleteTextView) view.findViewById(R.id.send_coins_receiving_address); receivingAddressView.setAdapter(new AutoCompleteAddressAdapter(activity, null)); receivingAddressView.setOnFocusChangeListener(receivingAddressListener); receivingAddressView.addTextChangedListener(receivingAddressListener); receivingStaticView = view.findViewById(R.id.send_coins_receiving_static); receivingStaticAddressView = (TextView) view.findViewById(R.id.send_coins_receiving_static_address); receivingStaticLabelView = (TextView) view.findViewById(R.id.send_coins_receiving_static_label); receivingStaticView.setOnFocusChangeListener(new OnFocusChangeListener() { private ActionMode actionMode; @Override/* ww w .j a v a2 s . c o m*/ public void onFocusChange(final View v, final boolean hasFocus) { if (hasFocus) actionMode = activity.startActionMode(new ReceivingAddressActionMode()); else actionMode.finish(); } }); final CurrencyAmountView btcAmountView = (CurrencyAmountView) view.findViewById(R.id.send_coins_amount_btc); btcAmountView.setCurrencySymbol(btcShift == 0 ? Constants.CURRENCY_CODE_BTC : Constants.CURRENCY_CODE_MBTC); btcAmountView.setInputPrecision(btcShift == 0 ? Constants.BTC_MAX_PRECISION : Constants.MBTC_MAX_PRECISION); btcAmountView.setHintPrecision(btcPrecision); btcAmountView.setShift(btcShift); final CurrencyAmountView localAmountView = (CurrencyAmountView) view .findViewById(R.id.send_coins_amount_local); localAmountView.setInputPrecision(Constants.LOCAL_PRECISION); localAmountView.setHintPrecision(Constants.LOCAL_PRECISION); amountCalculatorLink = new CurrencyCalculatorLink(btcAmountView, localAmountView); bluetoothEnableView = (CheckBox) view.findViewById(R.id.send_coins_bluetooth_enable); bluetoothEnableView.setChecked(bluetoothAdapter != null && bluetoothAdapter.isEnabled()); bluetoothEnableView.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) { if (isChecked && !bluetoothAdapter.isEnabled()) { // try to enable bluetooth startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), REQUEST_CODE_ENABLE_BLUETOOTH); } } }); bluetoothMessageView = (TextView) view.findViewById(R.id.send_coins_bluetooth_message); sentTransactionView = (ListView) view.findViewById(R.id.send_coins_sent_transaction); sentTransactionListAdapter = new TransactionsListAdapter(activity, wallet, application.maxConnectedPeers(), false); sentTransactionView.setAdapter(sentTransactionListAdapter); viewGo = (Button) view.findViewById(R.id.send_coins_go); viewGo.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { validateReceivingAddress(true); validateAmounts(true); if (everythingValid()) handleGo(); } }); viewCancel = (Button) view.findViewById(R.id.send_coins_cancel); viewCancel.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { if (state == State.INPUT) activity.setResult(Activity.RESULT_CANCELED); activity.finish(); } }); popupMessageView = (TextView) inflater.inflate(R.layout.send_coins_popup_message, container); popupAvailableView = inflater.inflate(R.layout.send_coins_popup_available, container); if (savedInstanceState != null) { restoreInstanceState(savedInstanceState); } else { final Intent intent = activity.getIntent(); final String action = intent.getAction(); final Uri intentUri = intent.getData(); final String scheme = intentUri != null ? intentUri.getScheme() : null; if ((Intent.ACTION_VIEW.equals(action) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) && intentUri != null && "monacoin".equals(scheme)) initStateFromBitcoinUri(intentUri); else if (intent.hasExtra(SendCoinsActivity.INTENT_EXTRA_ADDRESS)) initStateFromIntentExtras(intent.getExtras()); } return view; }
From source file:com.baroq.pico.google.PlayServices.java
@Override public void onLeaderboardMetadataLoaded(int statusCode, LeaderboardBuffer leaderboard) { JSONObject json = new JSONObject(); try {//w w w .j a v a 2 s.co m json.put("type", GAME_LEADERBOARD_METADATA_LOADED); json.put("statusCode", statusCode); switch (statusCode) { case GamesClient.STATUS_OK: // if data was successfully loaded and is up-to-date. JSONArray list = new JSONArray(); JSONObject obj; JSONArray vList; JSONObject v; Leaderboard lb; ArrayList<LeaderboardVariant> variants; LeaderboardVariant variant; int i, l, j, k; for (i = 0, l = leaderboard.getCount(); i < l; i++) { obj = new JSONObject(); lb = leaderboard.get(i); obj.put("displayName", lb.getDisplayName()); Uri uri = lb.getIconImageUri(); if (null != uri) obj.put("iconImageUri", uri.getScheme() + ':' + uri.getSchemeSpecificPart()); obj.put("leaderboardId", lb.getLeaderboardId()); obj.put("scoreOrder", lb.getScoreOrder()); variants = lb.getVariants(); vList = new JSONArray(); for (j = 0, k = variants.size(); j < k; j++) { v = new JSONObject(); variant = variants.get(i); v.put("collection", variant.getCollection()); v.put("numScores", variant.getNumScores()); v.put("timeSpan", variant.getTimeSpan()); v.put("hasPlayerInfo", variant.hasPlayerInfo()); if (variant.hasPlayerInfo()) { v.put("displayPlayerRank", variant.getDisplayPlayerRank()); v.put("displayPlayerScore", variant.getDisplayPlayerScore()); v.put("playerRank", variant.getPlayerRank()); v.put("rawPlayerScore", variant.getRawPlayerScore()); } vList.put(v); obj.put("variants", vList); } list.put(obj); } json.put("leaderboard", list); break; case GamesClient.STATUS_INTERNAL_ERROR: // if an unexpected error occurred in the service break; case GamesClient.STATUS_NETWORK_ERROR_STALE_DATA: // if the device was unable to communicate with the network. in this case, the operation is not retried automatically. break; case GamesClient.STATUS_CLIENT_RECONNECT_REQUIRED: // need to reconnect GamesClient mHelper.reconnectClients(clientTypes); break; case GamesClient.STATUS_LICENSE_CHECK_FAILED: // the game is not licensed to the user. further calls will return the same code. break; default: // error break; } } catch (JSONException ex) { Log.e(TAG, "game_leaderboard_scores_loaded [" + statusCode + "] exception: " + ex.getMessage()); return; } leaderboard.close(); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, json); pluginResult.setKeepCallback(true); connectionCB.sendPluginResult(pluginResult); }
From source file:Main.java
public static String getAbsolutePath(final Context context, final Uri uri) { // DocumentProvider if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, uri)) { // ExternalStorageProvider if (isExternalStorageDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; if ("primary".equalsIgnoreCase(type)) { return Environment.getExternalStorageDirectory() + "/" + split[1]; }/* w w w .ja v a 2 s .c o m*/ } // DownloadsProvider else if (isDownloadsDocument(uri)) { final String id = DocumentsContract.getDocumentId(uri); final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); return getDataColumn(context, contentUri, null, null); } // MediaProvider else if (isMediaDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; Uri contentUri = null; if ("image".equals(type)) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } final String selection = "_id=?"; final String[] selectionArgs = new String[] { split[1] }; return getDataColumn(context, contentUri, selection, selectionArgs); } } // MediaStore (and general) else if ("content".equalsIgnoreCase(uri.getScheme())) { return getDataColumn(context, uri, null, null); } // File else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return null; }
From source file:com.baroq.pico.google.PlayServices.java
@Override public void onAchievementsLoaded(int statusCode, AchievementBuffer buffer) { JSONObject json = new JSONObject(); try {/*from w w w. ja v a 2s. co m*/ json.put("type", GAME_ACHIEVEMENT_LOADED); json.put("statusCode", statusCode); switch (statusCode) { case GamesClient.STATUS_OK: // if data was successfully loaded and is up-to-date JSONArray achievements = new JSONArray(); JSONObject achievement; Achievement a; for (int i = 0, l = buffer.getCount(); i < l; i++) { a = buffer.get(i); achievement = new JSONObject(); achievement.put("achievementId", a.getAchievementId()); achievement.put("description", a.getDescription()); achievement.put("lastUpdatedTimestamp", a.getLastUpdatedTimestamp()); achievement.put("name", a.getName()); achievement.put("achievementId", a.getPlayer().getPlayerId()); achievement.put("state", a.getState()); achievement.put("type", a.getType()); if (Achievement.TYPE_INCREMENTAL == a.getType()) { achievement.put("currentSteps", a.getCurrentSteps()); achievement.put("totalSteps", a.getTotalSteps()); achievement.put("formattedCurrentSteps", a.getFormattedCurrentSteps()); achievement.put("formattedTotalSteps", a.getFormattedTotalSteps()); } Uri uri = a.getRevealedImageUri(); if (null != uri) achievement.put("revealedImageUri", uri.getScheme() + ':' + uri.getSchemeSpecificPart()); uri = a.getUnlockedImageUri(); if (null != uri) achievement.put("unlockedImageUri", uri.getScheme() + ':' + uri.getSchemeSpecificPart()); achievements.put(achievement); } json.put("list", achievements); break; case GamesClient.STATUS_NETWORK_ERROR_NO_DATA: // A network error occurred while attempting to retrieve fresh data, and no data was available locally. break; case GamesClient.STATUS_INTERNAL_ERROR: // if an unexpected error occurred in the service break; case GamesClient.STATUS_NETWORK_ERROR_STALE_DATA: // if the device was unable to communicate with the network. In this case, the operation is not retried automatically. break; case GamesClient.STATUS_CLIENT_RECONNECT_REQUIRED: // need to reconnect GamesClient mHelper.reconnectClients(clientTypes); break; case GamesClient.STATUS_LICENSE_CHECK_FAILED: // The game is not licensed to the user. Further calls will return the same code. break; default: // error break; } } catch (JSONException ex) { Log.e(TAG, "GAME_ACHIEVEMENT_LOADED [" + statusCode + "] exception: " + ex.getMessage()); return; } buffer.close(); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, json); pluginResult.setKeepCallback(true); connectionCB.sendPluginResult(pluginResult); }
From source file:Main.java
/** * Get a file path from a Uri. This will get the the path for Storage Access * Framework Documents, as well as the _data field for the MediaStore and * other file-based ContentProviders.//from w ww .j a v a2 s . c om * * @param context The context. * @param uri The Uri to query. */ @SuppressLint("NewApi") public static String getPath(final Context context, final Uri uri) { final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; // DocumentProvider if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { // ExternalStorageProvider if (isExternalStorageDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; if ("primary".equalsIgnoreCase(type)) { return Environment.getExternalStorageDirectory() + "/" + split[1]; } } else if (isDownloadsDocument(uri)) { // DownloadsProvider final String id = DocumentsContract.getDocumentId(uri); final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); return getDataColumn(context, contentUri, null, null); } else if (isMediaDocument(uri)) { // MediaProvider final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; Uri contentUri = null; if ("image".equals(type)) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } final String selection = "_id=?"; final String[] selectionArgs = new String[] { split[1] }; return getDataColumn(context, contentUri, selection, selectionArgs); } } else if ("content".equalsIgnoreCase(uri.getScheme())) { // MediaStore (and general) // Return the remote address if (isGooglePhotosUri(uri)) { return uri.getLastPathSegment(); } return getDataColumn(context, uri, null, null); } else if ("file".equalsIgnoreCase(uri.getScheme())) { // File return uri.getPath(); } return null; }