Java Code Examples for android.net.Uri

The following are top voted examples for showing how to use android.net.Uri. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: hacktoolkit-android_lib   File: ContactsUtils.java View source code 8 votes vote down vote up
public static InputStream openPhoto(Activity currentActivity, long contactId) {
	if (HTKUtils.getCurrentAPIVersion() < android.os.Build.VERSION_CODES.HONEYCOMB) {
		return null;
	}
	Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
	Uri photoUri = Uri.withAppendedPath(contactUri, Contacts.Photo.CONTENT_DIRECTORY);
	Cursor cursor = currentActivity.getContentResolver().query(photoUri,
			new String[] { Contacts.Photo.PHOTO}, null, null, null);
	if (cursor == null) {
		return null;
	}
	try {
		if (cursor.moveToFirst()) {
			byte[] data = cursor.getBlob(0);
			if (data != null) {
				return new ByteArrayInputStream(data);
			}
		}
	} finally {
		cursor.close();
	}
	return null;
}
 
Example 2
Project: dlna   File: YouUtility.java View source code 8 votes vote down vote up
public static void toShareToSystem(Context context,String imagepath,String url, String shareContent){
LOG.v("youUtility", "toShareToSystem", "imagepath:"+imagepath);   
      Intent intent=new Intent(Intent.ACTION_SEND);
      intent.setType("text/plain");
      if( imagepath != null ){
          
          File f = new File(imagepath);        
          if( f.exists() ){
              intent.setType("image/png");
              Uri u = Uri.fromFile(f);
              intent.putExtra(Intent.EXTRA_STREAM, u);
          }
      }
       intent.putExtra(Intent.EXTRA_SUBJECT, context.getResources().getText(R.string.share_blog_title));
       if( url == null ) url = "";
       String shareText = context.getResources().getText(R.string.share_text_start).toString();
       shareText += (shareContent == null ? "" : shareContent); 
       intent.putExtra(Intent.EXTRA_TEXT, shareText +"\n"+ url);
       intent.putExtra("sms_body", shareText +"\n"+ url);
       context.startActivity(Intent.createChooser(intent, context.getResources().getText(R.string.share_blog_title)));
}
 
Example 3
Project: ExcusePro   File: SuggestionsAdapter.java View source code 7 votes vote down vote up
public Drawable getTheDrawable(Uri uri) throws FileNotFoundException {
    String authority = uri.getAuthority();
    Resources r;
    if (TextUtils.isEmpty(authority)) {
        throw new FileNotFoundException("No authority: " + uri);
    } else {
        try {
            r = mContext.getPackageManager().getResourcesForApplication(authority);
        } catch (NameNotFoundException ex) {
            throw new FileNotFoundException("No package found for authority: " + uri);
        }
    }
    List<String> path = uri.getPathSegments();
    if (path == null) {
        throw new FileNotFoundException("No path: " + uri);
    }
    int len = path.size();
    int id;
    if (len == 1) {
        try {
            id = Integer.parseInt(path.get(0));
        } catch (NumberFormatException e) {
            throw new FileNotFoundException("Single path segment is not a resource ID: " + uri);
        }
    } else if (len == 2) {
        id = r.getIdentifier(path.get(1), path.get(0), authority);
    } else {
        throw new FileNotFoundException("More than two path segments: " + uri);
    }
    if (id == 0) {
        throw new FileNotFoundException("No resource found for: " + uri);
    }
    return r.getDrawable(id);
}
 
Example 4
Project: dlna   File: YouUtility.java View source code 6 votes vote down vote up
public static void switchLinkType(Context context, Intent intent,
	String weibourl, String ourl, String url, Boolean showPlayButton,
	String definition, String pic, String linkType, String name,
	String desc) {
   switch (Integer.parseInt(linkType)) {
    case 0: // fullplayer
    	LOG.v(TAG,"switchLinkType","fullplayer");
    	intent.setAction(YouPlayerConstant.YOU_ACTION_FULLPLAY);
    	intent.putExtra(YouPlayerConstant.YOU_ACTION_URL,url);
    	//skipIntent.putExtra(Constant.ACTION_PAGE, fn_Core.FN_PAGE_FULL_SCREEN_PLAYER);
    	break;
    case 3:  //open webview
    	LOG.v(TAG,"switchLinkType","open webview");
    	 intent.setAction("android.intent.action.VIEW");
    	 Uri content_url1 = Uri.parse(url);   
 		 intent.setData(content_url1);
 		 if (android.os.Build.VERSION.SDK_INT < 16) { 
 			 intent.setClassName("com.android.browser","com.android.browser.BrowserActivity"); 
 		 } 
    	 break;

    case 8: // original web
    	LOG.v(TAG,"switchLinkType","original web");
    	intent.setAction(YouPlayerConstant.YOU_ACTION_NOTIFICATION);
    	intent.putExtra(YouPlayerConstant.YOU_ACTION_PAGE, You_Core.FN_PAGE_ONLINE_WEB_DETAIL);
    	intent.putExtra(YouPlayerConstant.YOU_ACTION_WEIBOURL,weibourl);
    	intent.putExtra(YouPlayerConstant.YOU_ACTION_OURL,ourl);
    	intent.putExtra(YouPlayerConstant.YOU_ACTION_URL,url);
    	intent.putExtra(YouPlayerConstant.YOU_ACTION_BTNPLY,showPlayButton);
    	intent.putExtra(YouPlayerConstant.YOU_ACTION_DEFINITION,definition);
    	intent.putExtra(YouPlayerConstant.YOU_ACTION_PIC,pic);
    	intent.putExtra(YouPlayerConstant.YOU_ACTION_NAME,name);
    	break;	 
   default:
	  break;
}
  }
 
Example 5
Project: flow-android   File: FlowApiRequests.java View source code 6 votes vote down vote up
public static void searchCourses(String keywords, String sortMode, Boolean excludeTakenCourses, Integer count,
                                 Integer offset, final FlowApiRequestCallback callback) {
    // Build the search query string
    Uri.Builder uriBuilder = new Uri.Builder();
    if (StringUtils.isNotBlank(keywords)) {
        uriBuilder.appendQueryParameter("keywords", keywords);
    }
    if (StringUtils.isNotEmpty(sortMode)) {
        uriBuilder.appendQueryParameter("sort_mode", sortMode);
    }
    if (excludeTakenCourses) {
        uriBuilder.appendQueryParameter("exclude_taken_courses", "yes");
    }
    if (count != null && count >= 0) {
        uriBuilder.appendQueryParameter("count", String.valueOf(count));
    }
    if (offset != null && offset >= 0) {
        uriBuilder.appendQueryParameter("offset", String.valueOf(offset));
    }

    final String encodedQuery = uriBuilder.build().getEncodedQuery();
    final String uri = String.format(Constants.API_SEARCH_COURSES, encodedQuery);

    getDetails(Constants.API_REQUEST_CALL_ID.API_SEARCH_COURSES, uri, callback);
}
 
Example 6
Project: phonegap-geolocation   File: CordovaResourceApi.java View source code 6 votes vote down vote up
/**
 * Returns a File that points to the resource, or null if the resource
 * is not on the local filesystem.
 */
public File mapUriToFile(Uri uri) {
    assertBackgroundThread();
    switch (getUriType(uri)) {
        case URI_TYPE_FILE:
            return new File(uri.getPath());
        case URI_TYPE_CONTENT: {
            Cursor cursor = contentResolver.query(uri, LOCAL_FILE_PROJECTION, null, null, null);
            if (cursor != null) {
                try {
                    int columnIndex = cursor.getColumnIndex(LOCAL_FILE_PROJECTION[0]);
                    if (columnIndex != -1 && cursor.getCount() > 0) {
                        cursor.moveToFirst();
                        String realPath = cursor.getString(columnIndex);
                        if (realPath != null) {
                            return new File(realPath);
                        }
                    }
                } finally {
                    cursor.close();
                }
            }
        }
    }
    return null;
}
 
Example 7
Project: BioWiki   File: MediaAddFragment.java View source code 6 votes vote down vote up
private String getRealPathFromURI(Uri uri) {
    String path;
    if ("content".equals(uri.getScheme())) {
        path = getRealPathFromContentURI(uri);
    } else if ("file".equals(uri.getScheme())) {
        path = uri.getPath();
    } else {
        path = uri.toString();
    }
    return path;
}
 
Example 8
Project: BioWiki   File: MediaGridAdapter.java View source code 6 votes vote down vote up
private void loadNetworkImage(Cursor cursor, NetworkImageView imageView) {
    String thumbnailURL = cursor.getString(cursor.getColumnIndex("thumbnailURL"));

    // Allow non-private wp.com and Jetpack blogs to use photon to get a higher res thumbnail
    if (mIsCurrentBlogPhotonCapable) {
        String imageURL = cursor.getString(cursor.getColumnIndex("fileURL"));
        if (imageURL != null) {
            thumbnailURL = StringUtils.getPhotonUrl(imageURL, mGridItemWidth);
        }
    }

    if (thumbnailURL != null) {
        Uri uri = Uri.parse(thumbnailURL);
        String filepath = uri.getLastPathSegment();

        int placeholderResId = MediaUtils.getPlaceholder(filepath);
        imageView.setImageResource(0);
        imageView.setErrorImageResId(placeholderResId);

        // no default image while downloading
        imageView.setDefaultImageResId(0);

        if (MediaUtils.isValidImage(filepath)) {
            imageView.setTag(thumbnailURL);
            imageView.setImageUrl(thumbnailURL, mImageLoader);
        } else {
            imageView.setImageResource(placeholderResId);
        }
    } else {
        imageView.setImageResource(0);
    }

}
 
Example 9
Project: phonegap-geolocation   File: CordovaResourceApi.java View source code 6 votes vote down vote up
public static int getUriType(Uri uri) {
    assertNonRelative(uri);
    String scheme = uri.getScheme();
    if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
        return URI_TYPE_CONTENT;
    }
    if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)) {
        return URI_TYPE_RESOURCE;
    }
    if (ContentResolver.SCHEME_FILE.equals(scheme)) {
        if (uri.getPath().startsWith("/android_asset/")) {
            return URI_TYPE_ASSET;
        }
        return URI_TYPE_FILE;
    }
    if ("data".equals(scheme)) {
        return URI_TYPE_DATA;
    }
    if ("http".equals(scheme)) {
        return URI_TYPE_HTTP;
    }
    if ("https".equals(scheme)) {
        return URI_TYPE_HTTPS;
    }
    return URI_TYPE_UNKNOWN;
}
 
Example 10
Project: BioWiki   File: DeepLinkingIntentReceiverActivity.java View source code 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String action = getIntent().getAction();
    Uri uri = getIntent().getData();

    // check if this intent is started via custom scheme link
    if (Intent.ACTION_VIEW.equals(action) && uri != null) {
        mBlogId = uri.getQueryParameter("blogId");
        mPostId = uri.getQueryParameter("postId");

        // if user is logged in, show the post right away - otherwise show welcome activity
        // and then show the post once t
        // he user has logged in
        if (/*BioWiki.hasValidWPComCredentials(this)*/ false) {
            //showPost();
        } else {
            Intent intent = new Intent(this, WelcomeActivity.class);
            startActivityForResult(intent, INTENT_WELCOME);
        }
    } else {
        finish();
    }
}
 
Example 11
Project: phonegap-geolocation   File: CordovaResourceApi.java View source code 6 votes vote down vote up
private String getDataUriMimeType(Uri uri) {
    String uriAsString = uri.getSchemeSpecificPart();
    int commaPos = uriAsString.indexOf(',');
    if (commaPos == -1) {
        return null;
    }
    String[] mimeParts = uriAsString.substring(0, commaPos).split(";");
    if (mimeParts.length > 0) {
        return mimeParts[0];
    }
    return null;
}
 
Example 12
Project: GeoSMS-Release   File: Contact.java View source code 6 votes vote down vote up
private void initFromAddress(Context context,String address){
    setAddress(address);
    Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(address));
    Cursor c = context.getContentResolver().query(lookupUri, null, null, null, null);
    if (c.getCount() > 0) {
        c.moveToFirst();
        String displayName = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        String photoURI = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
        int id = c.getInt(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));

        setId(id);
        setName(displayName);
        setPhotoUri(photoURI);

        //setPhoto(getPhotoFromURI(photoURI,context));
    }
    c.close();
}
 
Example 13
Project: GeoSMS-Release   File: ConversationActivity.java View source code 6 votes vote down vote up
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(contacts == null || contacts.size() <= 0)
        return false;
    if(item.getItemId() ==  R.id.action_call){
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.fromParts("tel", contacts.get(0).getAddress(), null));
        startActivity(intent);
        return true;
    }else if(item.getItemId() == R.id.people_in_this_conversation){
        Utils.buildContactsDialog(ConversationActivity.this,contacts).show();
        return true;
    }else if(item.getItemId() == R.id.action_show_balance){
        Utils.showBalanceDialog(this,smsManager);
    }
    return super.onOptionsItemSelected(item);
}
 
Example 14
Project: phonegap-geolocation   File: IceCreamCordovaWebViewClient.java View source code 6 votes vote down vote up
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
    try {
        // Check the against the white-list.
        if ((url.startsWith("http:") || url.startsWith("https:")) && !Config.isUrlWhiteListed(url)) {
            LOG.w(TAG, "URL blocked by whitelist: " + url);
            // Results in a 404.
            return new WebResourceResponse("text/plain", "UTF-8", null);
        }

        CordovaResourceApi resourceApi = appView.getResourceApi();
        Uri origUri = Uri.parse(url);
        // Allow plugins to intercept WebView requests.
        Uri remappedUri = resourceApi.remapUri(origUri);
        
        if (!origUri.equals(remappedUri) || needsSpecialsInAssetUrlFix(origUri)) {
            OpenForReadResult result = resourceApi.openForRead(remappedUri, true);
            return new WebResourceResponse(result.mimeType, "UTF-8", result.inputStream);
        }
        // If we don't need to special-case the request, let the browser load it.
        return null;
    } catch (IOException e) {
        if (!(e instanceof FileNotFoundException)) {
            LOG.e("IceCreamCordovaWebViewClient", "Error occurred while loading a file (returning a 404).", e);
        }
        // Results in a 404.
        return new WebResourceResponse("text/plain", "UTF-8", null);
    }
}
 
Example 15
Project: BioWiki   File: UrlUtils.java View source code 6 votes vote down vote up
public static String getDomainFromUrl(final String urlString) {
    if (urlString == null) {
        return "";
    }
    Uri uri = Uri.parse(urlString);
    return uri.getHost();
}
 
Example 16
Project: phonegap-geolocation   File: IceCreamCordovaWebViewClient.java View source code 6 votes vote down vote up
private static boolean needsSpecialsInAssetUrlFix(Uri uri) {
    if (CordovaResourceApi.getUriType(uri) != CordovaResourceApi.URI_TYPE_ASSET) {
        return false;
    }
    if (uri.getQuery() != null || uri.getFragment() != null) {
        return true;
    }
    
    if (!uri.toString().contains("%")) {
        return false;
    }

    switch(android.os.Build.VERSION.SDK_INT){
        case android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH:
        case android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1:
            return true;
    }
    return false;
}
 
Example 17
Project: edx-app-android   File: MediaPresentationDescriptionParser.java View source code 6 votes vote down vote up
protected static Uri parseBaseUrl(XmlPullParser xpp, Uri parentBaseUrl)
    throws XmlPullParserException, IOException {
  xpp.next();
  String newBaseUrlText = xpp.getText();
  Uri newBaseUri = Uri.parse(newBaseUrlText);
  if (!newBaseUri.isAbsolute()) {
    newBaseUri = Uri.withAppendedPath(parentBaseUrl, newBaseUrlText);
  }
  return newBaseUri;
}
 
Example 18
Project: property-db   File: Intent.java View source code 6 votes vote down vote up
public void writeToParcel(Parcel out, int flags) {
    out.writeString(mAction);
    Uri.writeToParcel(out, mData);
    out.writeString(mType);
    out.writeInt(mFlags);
    out.writeString(mPackage);
    ComponentName.writeToParcel(mComponent, out);

    if (mSourceBounds != null) {
        out.writeInt(1);
        mSourceBounds.writeToParcel(out, flags);
    } else {
        out.writeInt(0);
    }

    if (mCategories != null) {
        out.writeInt(mCategories.size());
        for (String category : mCategories) {
            out.writeString(category);
        }
    } else {
        out.writeInt(0);
    }

    if (mSelector != null) {
        out.writeInt(1);
        mSelector.writeToParcel(out, flags);
    } else {
        out.writeInt(0);
    }

    if (mClipData != null) {
        out.writeInt(1);
        mClipData.writeToParcel(out, flags);
    } else {
        out.writeInt(0);
    }

    out.writeBundle(mExtras);
}
 
Example 19
Project: RedditInPictures   File: RESTService.java View source code 6 votes vote down vote up
private static void attachUriWithQuery(HttpRequestBase request, Uri uri, Bundle params) {
    try {
        if (params == null) {
            // No params were given or they have already been
            // attached to the Uri.
            request.setURI(new URI(uri.toString()));
        } else {
            Uri.Builder uriBuilder = uri.buildUpon();

            // Loop through our params and append them to the Uri.
            for (BasicNameValuePair param : paramsToList(params)) {
                uriBuilder.appendQueryParameter(param.getName(), param.getValue());
            }

            uri = uriBuilder.build();
            request.setURI(new URI(uri.toString()));
        }
    } catch (URISyntaxException e) {
        Ln.e(e, "URI syntax was incorrect: %s", uri.toString());
    }
}
 
Example 20
Project: download-manager   File: NotificationDisplayer.java View source code 6 votes vote down vote up
private Intent createClickIntent(long batchId, int batchStatus) {
    String action = getActionFrom(batchStatus);
    Intent clickIntent = new Intent(action, Uri.EMPTY, context, DownloadReceiver.class);

    clickIntent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, new long[]{batchId});
    clickIntent.putExtra(DownloadReceiver.EXTRA_BATCH_ID, batchId);
    int status = statusTranslator.translate(batchStatus);
    clickIntent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_STATUSES, new int[]{status});
    clickIntent.setData(createUniqueUri(clickIntent));

    return clickIntent;
}
 
Example 21
Project: BigPangOrderManager   File: DecodeFormatManager.java View source code 6 votes vote down vote up
static Collection<BarcodeFormat> parseDecodeFormats(Uri inputUri) {
  List<String> formats = inputUri.getQueryParameters(Intents.Scan.FORMATS);
  if (formats != null && formats.size() == 1 && formats.get(0) != null){
    formats = Arrays.asList(COMMA_PATTERN.split(formats.get(0)));
  }
  return parseDecodeFormats(formats, inputUri.getQueryParameter(Intents.Scan.MODE));
}
 
Example 22
Project: servestream   File: RTSP.java View source code 6 votes vote down vote up
@Override
public void getSelectionArgs(Uri uri, Map<String, String> selection) {
	selection.put(StreamDatabase.FIELD_STREAM_PROTOCOL, PROTOCOL);
	
	if (uri.getUserInfo() != null) {
		String [] authInfo = uri.getUserInfo().split("\\:");
		
		if (authInfo.length == 2) {
			selection.put(StreamDatabase.FIELD_STREAM_USERNAME, authInfo[0]);
			selection.put(StreamDatabase.FIELD_STREAM_PASSWORD, authInfo[1]);
		}
	} else {
		selection.put(StreamDatabase.FIELD_STREAM_USERNAME, null);
		selection.put(StreamDatabase.FIELD_STREAM_PASSWORD, null);
	}
	
	selection.put(StreamDatabase.FIELD_STREAM_HOSTNAME, uri.getHost());

	int port = uri.getPort();
	if (port < 0)
		port = DEFAULT_PORT;
	selection.put(StreamDatabase.FIELD_STREAM_PORT, Integer.toString(port));
	
	if (uri.getPath() != null) {
		selection.put(StreamDatabase.FIELD_STREAM_PATH, uri.getPath());
	}
	selection.put(StreamDatabase.FIELD_STREAM_QUERY, uri.getQuery());
	selection.put(StreamDatabase.FIELD_STREAM_REFERENCE, uri.getFragment());		
}
 
Example 23
Project: i2p.android.base   File: CacheProvider.java View source code 6 votes vote down vote up
/**
 *  Generate an i2p URI for a content URI
 *
 *  @param uri must contain a scheme, authority and path with nonce etc. as defined above
 *  @return non-null
 *  @throws java.io.FileNotFoundException on error
 */
public static Uri getI2PUri(Uri uri) throws FileNotFoundException {
    String resPath = uri.getEncodedPath();
    if (resPath == null)
        throw new FileNotFoundException("Bad uri no path? " + uri);
    String[] segs = resPath.split("/", 5);
    // first seg is empty since string starts with /
    String nonce = segs.length > 1 ? segs[1] : null;
    String scheme = segs.length > 2 ? segs[2] : null;
    String host = segs.length > 3 ? segs[3].toLowerCase() : null;
    String realPath = segs.length > 4 ? segs[4] : "";
    String query = uri.getEncodedQuery();
    if (query == null) {
        int marker = realPath.indexOf(QUERY_MARKER);
        if (marker >= 0) {
            query = realPath.substring(marker + QUERY_MARKER.length());
            realPath = realPath.substring(0, marker);
        }
    }
    String debug = "CacheProvider nonce: " + nonce + " scheme: " + scheme + " host: " + host + " realPath: " + realPath + " query: " + query;
    Util.d(debug);
    if ((!NONCE.equals(nonce)) ||
        (!"http".equals(scheme)) ||
        (host == null) ||
        (!host.endsWith(".i2p")))
        throw new FileNotFoundException(debug);
    String i2pUri = scheme + "://" + host + '/' + realPath;
    if (query != null)
        i2pUri += '?' + query;
    return Uri.parse(i2pUri);
}
 
Example 24
Project: PaintDrip   File: FacebookDialog.java View source code 6 votes vote down vote up
/**
 * This is public primarily to allow its use elsewhere in the Android SDK; developers are discouraged from
 * consuming this method as the internal API may change.
 */
protected String getWebFallbackUrlInternal() {
    Iterable<? extends DialogFeature> features = getDialogFeatures();
    String featureName = null;
    String action = null;
    for (DialogFeature feature : features) {
        // All actions in a set of DialogFeatures should have the same fallback url
        // So we can break after assigning the first one
        featureName = feature.name();
        action = feature.getAction();
        break;
    }

    Utility.DialogFeatureConfig config = Utility.getDialogFeatureConfig(applicationId, action, featureName);
    Uri fallbackUrl;
    if (config == null || (fallbackUrl = config.getFallbackUrl()) == null) {
        return null;
    }

    // Since we're talking to the server here, let's use the latest version we know about.
    // We know we are going to be communicating over a bucketed protocol.
    Bundle methodArguments = getMethodArguments();
    int protocolVersion = NativeProtocol.getLatestKnownVersion();
    Bundle webParams = ServerProtocol.getQueryParamsForPlatformActivityIntentWebFallback(
            activity,
            appCall.getCallId().toString(),
            protocolVersion,
            applicationName,
            methodArguments);
    if (webParams == null) {
        // Could not create the query parameters
        return null;
    }

    // Now form the Uri
    if (fallbackUrl.isRelative()) {
        fallbackUrl = Utility.buildUri(
                ServerProtocol.getDialogAuthority(),
                fallbackUrl.toString(),
                webParams);
    }

    return fallbackUrl.toString();
}
 
Example 25
Project: GlassCompute   File: ComputeActivity.java View source code 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_compute);
	// Make progress bar white
	ProgressBar bar = (ProgressBar) findViewById(R.id.progressBar1);
	bar.getIndeterminateDrawable().setColorFilter(Color.WHITE, Mode.SRC_IN);
	// Read in Uri passed from MainActivity
	Uri uri = getIntent().getData();
	Set<String> parameters = uri.getQueryParameterNames();
	// Check if it cotains the right params
	if(!parameters.contains("parsed") || !parameters.contains("q")){
		Log.d(DEBUG_TAG, "Incorrect args provided...closing");
		finish();
	}
	// Extract params
	String query = uri.getQueryParameter("q");
	String parsed = uri.getQueryParameter("parsed");
	// Build a request Url so we can query the GlassComputeServer
	Uri.Builder serverUri = Uri.parse("http://ruxin.aaka.sh:8080").buildUpon();
	//TODO: change
	serverUri.appendQueryParameter("parsed", parsed);
	serverUri.appendQueryParameter("q", query);
	serverUri.build();
	// Start downloading results object
	new DownloadWebpageTask().execute(serverUri.toString());
	
	// Keep the screen on while downloading
	final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
       this.mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, DEBUG_TAG);
       this.mWakeLock.acquire();
}
 
Example 26
Project: financius-public   File: ProviderUtils.java View source code 6 votes vote down vote up
public static void notifyUris(Context context, Uri... uris) {
    if (uris == null) {
        return;
    }

    for (Uri uri : uris) {
        boolean notifyUriChanged = uri.getBooleanQueryParameter(QueryParameterKey.NOTIFY_URI_CHANGED.getKeyName(), true);
        if (notifyUriChanged) {
            context.getContentResolver().notifyChange(uri, null);
        }
    }
}
 
Example 27
Project: RedReader   File: General.java View source code 6 votes vote down vote up
public static Set<String> getUriQueryParameterNames(final Uri uri) {

		if(uri.isOpaque()) {
			throw new UnsupportedOperationException("This isn't a hierarchical URI.");
		}

		final String query = uri.getEncodedQuery();
		if(query == null) {
			return Collections.emptySet();
		}

		final Set<String> names = new LinkedHashSet<String>();
		int pos = 0;
		while(pos < query.length()) {
			int next = query.indexOf('&', pos);
			int end = (next == -1) ? query.length() : next;

			int separator = query.indexOf('=', pos);
			if (separator > end || separator == -1) {
				separator = end;
			}

			String name = query.substring(pos, separator);
			names.add(Uri.decode(name));

			// Move start to end of name.
			pos = end + 1;
		}

		return Collections.unmodifiableSet(names);
	}
 
Example 28
Project: RESTImplementation   File: ParserFactory.java View source code 6 votes vote down vote up
@Nullable
public static Parser GetParserByUri(@NotNull Uri uri) {

	if (uri.compareTo(AppContract.Entities.CONTENT_URI) == 0) {
		return new EntitiesParser();
	}

	return null;
}
 
Example 29
Project: AmazeFileManager   File: StreamServer.java View source code 5 votes vote down vote up
/**
 * Decodes the sent headers and loads the data into
 * java Properties' key - value pairs
 **/
private  void decodeHeader(BufferedReader in, Properties pre, Properties parms, Properties header)
        throws InterruptedException
{
    try {
        // Read the request line
        String inLine = in.readLine();
        if (inLine == null) return;
        StringTokenizer st = new StringTokenizer( inLine );
        if ( !st.hasMoreTokens())
            sendError(socket, HTTP_BADREQUEST, "BAD REQUEST: Syntax error. Usage: GET /example/file.html" );

        String method = st.nextToken();
        pre.put("method", method);

        if ( !st.hasMoreTokens())
            sendError(socket, HTTP_BADREQUEST, "BAD REQUEST: Missing URI. Usage: GET /example/file.html" );

        String uri = st.nextToken();

        // Decode parameters from the URI
        int qmi = uri.indexOf( '?' );
        if ( qmi >= 0 )
        {
            decodeParms( uri.substring( qmi+1 ), parms );
            uri = decodePercent( uri.substring( 0, qmi ));
        }
        else uri = Uri.decode(uri);//decodePercent(uri);

        // If there's another token, it's protocol version,
        // followed by HTTP headers. Ignore version but parse headers.
        // NOTE: this now forces header names lowercase since they are
        // case insensitive and vary by client.
        if ( st.hasMoreTokens())
        {
            String line = in.readLine();
            while ( line != null && line.trim().length() > 0 )
            {
                int p = line.indexOf( ':' );
                if ( p >= 0 )
                    header.put( line.substring(0,p).trim().toLowerCase(), line.substring(p+1).trim());
                line = in.readLine();
            }
        }

        pre.put("uri", uri);
    }
    catch ( IOException ioe )
    {
        sendError(socket, HTTP_INTERNALERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
    }
}
 
Example 30
Project: ijoomer-adv-sdk   File: IjoomerMediaPlayer.java View source code 5 votes vote down vote up
@Override
protected void onCreate(Bundle pSavedInstanceState) {
	super.onCreate(pSavedInstanceState);

	this.requestWindowFeature(Window.FEATURE_NO_TITLE);
	this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

	// create the layout of the view
	setupView();

	// determine the messages to be displayed as the view loads the video
	extractMessages();

	// set the flag to keep the screen ON so that the video can play without
	// the screen being turned off
	getWindow().setFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

	mProgressBar.bringToFront();
	mProgressBar.setVisibility(View.VISIBLE);
	mProgressMessage.setText(mMsgInit);

	// extract the playlist or video id from the intent that started this
	// video

	Uri lVideoIdUri = this.getIntent().getData();

	if (lVideoIdUri == null) {
		Log.i(this.getClass().getSimpleName(), "No video ID was specified in the intent.  Closing video activity.");
		finish();
	}
	String lVideoSchemeStr = lVideoIdUri.getScheme();
	String lVideoIdStr = lVideoIdUri.getEncodedSchemeSpecificPart();
	if (lVideoIdStr == null) {
		Log.i(this.getClass().getSimpleName(), "No video ID was specified in the intent.  Closing video activity.");
		finish();
	}
	if (lVideoIdStr.startsWith("//")) {
		if (lVideoIdStr.length() > 2) {
			lVideoIdStr = lVideoIdStr.substring(2);
		} else {
			Log.i(this.getClass().getSimpleName(), "No video ID was specified in the intent.  Closing video activity.");
			finish();
		}
	}

	// /////////////////
	// extract either a video id or a playlist id, depending on the uri
	// scheme
	YouTubeId lYouTubeId = null;
	if (lVideoSchemeStr != null && lVideoSchemeStr.equalsIgnoreCase(SCHEME_YOUTUBE_PLAYLIST)) {
		lYouTubeId = new PlaylistId(lVideoIdStr);
	} else if (lVideoSchemeStr != null && lVideoSchemeStr.equalsIgnoreCase(SCHEME_YOUTUBE_VIDEO)) {
		lYouTubeId = new VideoId(lVideoIdStr);
	} else if (lVideoSchemeStr != null && lVideoSchemeStr.equalsIgnoreCase(SCHEME_FILE)) {
		lYouTubeId = new FileId(lVideoIdStr);
	} else if (lVideoSchemeStr != null && lVideoSchemeStr.equalsIgnoreCase(SCHEME_MP4_VIDEO)) {
		lYouTubeId = new FileId(lVideoIdStr);
	}

	if (lYouTubeId == null) {
		Log.i(this.getClass().getSimpleName(), "Unable to extract video ID from the intent.  Closing video activity.");
		finish();
	}

	mQueryYouTubeTask = (QueryYouTubeTask) new QueryYouTubeTask().execute(lYouTubeId);
}
 
Example 31
Project: fdroidclient   File: FDroid.java View source code 5 votes vote down vote up
private void handleIntent(Intent intent) {
    final Uri data = intent.getData();
    if (data == null) {
        return;
    }
    final String scheme = data.getScheme();
    final String path = data.getPath();
    String appId = null;
    String query = null;
    if (data.isHierarchical()) {
        final String host = data.getHost();
        if (host == null) {
            return;
        }
        switch (host) {
            case "f-droid.org":
                // http://f-droid.org/app/app.id
                if (path.startsWith("/repository/browse")) {
                    // http://f-droid.org/repository/browse?fdid=app.id
                    appId = data.getQueryParameter("fdid");
                } else if (path.startsWith("/app")) {
                    appId = data.getLastPathSegment();
                    if ("app".equals(appId)) {
                        appId = null;
                    }
                }
                break;
            case "details":
                // market://details?id=app.id
                appId = data.getQueryParameter("id");
                break;
            case "search":
                // market://search?q=query
                query = data.getQueryParameter("q");
                break;
            case "play.google.com":
                if (path.startsWith("/store/apps/details")) {
                    // http://play.google.com/store/apps/details?id=app.id
                    appId = data.getQueryParameter("id");
                } else if (path.startsWith("/store/search")) {
                    // http://play.google.com/store/search?q=foo
                    query = data.getQueryParameter("q");
                }
                break;
            case "apps":
            case "amazon.com":
            case "www.amazon.com":
                // amzn://apps/android?p=app.id
                // http://amazon.com/gp/mas/dl/android?p=app.id
                appId = data.getQueryParameter("p");
                query = data.getQueryParameter("s");
                break;
        }
    } else if ("fdroid.app".equals(scheme)) {
        // fdroid.app:app.id
        appId = data.getSchemeSpecificPart();
    } else if ("fdroid.search".equals(scheme)) {
        // fdroid.search:query
        query = data.getSchemeSpecificPart();
    }

    if (!TextUtils.isEmpty(query)) {
        // an old format for querying via packageName
        if (query.startsWith("pname:"))
            appId = query.split(":")[1];

        // sometimes, search URLs include pub: or other things before the query string
        if (query.contains(":"))
            query = query.split(":")[1];
    }

    Intent call = null;
    if (!TextUtils.isEmpty(appId)) {
        Utils.debugLog(TAG, "FDroid launched via app link for '" + appId + "'");
        call = new Intent(this, AppDetails.class);
        call.putExtra(AppDetails.EXTRA_APPID, appId);
    } else if (!TextUtils.isEmpty(query)) {
        Utils.debugLog(TAG, "FDroid launched via search link for '" + query + "'");
        call = new Intent(this, SearchResults.class);
        call.setAction(Intent.ACTION_SEARCH);
        call.putExtra(SearchManager.QUERY, query);
    }
    if (call != null) {
        startActivity(call);
        finish();
    }
}
 
Example 32
Project: Locast-Core-Android   File: AbsMediaSync.java View source code 5 votes vote down vote up
/**
 * Synchronize the media of the given castMedia. It will download or upload as needed.
 *
 * Blocks until the sync is complete.
 *
 * @param castMediaDir
 *            a {@link CastMedia} item uri
 * @throws SyncException
 */
public void syncItemMedia(Uri castMediaDir) throws SyncException {

    final SyncableProvider provider = getSyncableProvider(castMediaDir);
    if (provider == null) {
        Log.e(TAG,
                "could not sync item media: could not get local binder for syncable provider");
        return;
    }

    if (DEBUG) {
        Log.d(TAG, "syncing " + castMediaDir);
    }

    final CastMedia castMedia = (CastMedia) provider.getWrappedContentItem(castMediaDir,
            mCr.query(castMediaDir, getCastMediaProjection(), null, null, null));

    final NotificationProgressListener downloadListener = new NotificationProgressListener(
            this, NotificationProgressListener.TYPE_DOWNLOAD, R.id.locast_core__sync_download);

    try {
        final int totalItems = castMedia.getCount();

        downloadListener.setTotalItems(totalItems);

        // cache the column numbers
        final int mediaUrlCol = castMedia.getColumnIndex(CastMedia.COL_MEDIA_URL);
        final int localUriCol = castMedia.getColumnIndex(CastMedia.COL_LOCAL_URL);
        final int idCol = castMedia.getColumnIndex(CastMedia._ID);
        final int mediaDirtyCol = castMedia.getColumnIndex(CastMedia.COL_MEDIA_DIRTY);

        while (castMedia.moveToNext()) {

            final boolean keepOffline = castMedia.getInt(castMedia
                    .getColumnIndex(CastMedia.COL_KEEP_OFFLINE)) != 0;

            final String mimeType = castMedia.getString(castMedia
                    .getColumnIndex(CastMedia.COL_MIME_TYPE));

            final boolean isImage = (mimeType != null) && mimeType.startsWith("image/");

            // we don't need to sync this
            if ("text/html".equals(mimeType)) {
                return;
            }

            final Uri locMedia = castMedia.isNull(localUriCol) ? null : Uri.parse(castMedia
                    .getString(localUriCol));
            final String pubMedia = castMedia.getString(mediaUrlCol);
            final boolean hasLocMedia = locMedia != null
                    && new File(locMedia.getPath()).exists();
            final boolean hasPubMedia = pubMedia != null && pubMedia.length() > 0;

            final String localThumb = castMedia.getString(castMedia
                    .getColumnIndex(CastMedia.COL_THUMB_LOCAL));

            final Uri castMediaItem = ContentUris.withAppendedId(castMediaDir,
                    castMedia.getLong(idCol));

            final boolean isLocalDirty = castMedia.isNull(mediaDirtyCol)
                    || castMedia.getInt(mediaDirtyCol) != 0;

            if (hasLocMedia && isLocalDirty) {
                if (DEBUG) {
                    Log.d(TAG, castMediaItem + " has local media and it's dirty");
                }

                final String uploadPath = castMedia.getString(castMedia
                        .getColumnIndex(CastMedia.COL_PUBLIC_URL));
                if (uploadPath == null) {
                    Log.w(TAG, "attempted to sync " + castMediaItem
                            + " which has a null uploadPath");
                    return;
                }

                final Uri titledItem = getTitledItemForCastMedia(castMediaItem);
                final NotificationProgressListener uploadListener = new NotificationProgressListener(
                        this, NotificationProgressListener.TYPE_UPLOAD, titledItem.hashCode());

                try {
                    uploadMedia(uploadPath, castMediaItem, titledItem, mimeType, locMedia,
                            uploadListener);
                    uploadListener.onTransfersSuccessful();
                } finally {
                    uploadListener.onAllTransfersComplete();
                }

            } else if (!hasLocMedia && hasPubMedia) {
                if (DEBUG) {
                    Log.d(TAG, castMediaItem
                            + " doesn't have local media, but has public media url");
                }

                // only have a public copy, so download it and store locally.
                final Uri pubMediaUri = Uri.parse(pubMedia);
                final File destfile = getFilePath(pubMediaUri);

                // the following conditions indicate that the cast media should be downloaded.
                if (keepOffline || getKeepOffline(castMediaItem, castMedia)) {

                    final boolean anythingChanged = downloadMediaFile(pubMedia, destfile,
                            castMediaItem, downloadListener);

                    // the below is inverted from what seems logical, because
                    // downloadMediaFile()
                    // will actually update the castmedia if it downloads anything. We'll only
                    // be
                    // getting here if we don't have any local record of the file, so we should
                    // make
                    // the association by ourselves.
                    if (!anythingChanged) {
                        File thumb = null;
                        if (isImage && localThumb == null) {
                            thumb = destfile;
                        }
                        updateLocalFile(castMediaDir, destfile, thumb);
                        // disabled to avoid spamming the user with downloaded
                        // items.
                        // checkForMediaEntry(castMediaUri, pubMediaUri, mimeType);
                    }
                }
            } else {
                // ensure we tell the listener that we finished
                downloadListener.onTransferComplete(castMediaItem);
            }
        }
        downloadListener.onTransfersSuccessful();
    } finally {
        downloadListener.onAllTransfersComplete();
        castMedia.close();
    }

}