android基础--uri简介

通用资源标志符(Universal Resource Identifier, 简称"URI")。

Uri代表要操作的数据,Android上每种可用的资源 - 图像、视频片段等都可以用Uri来表示。

 

URI一般由三部分组成:

访问资源的命名机制。 

存放资源的主机名。 

资源自身的名称,由路径表示。 

 

Android的Uri由以下三部分组成: "content://"、数据的路径、标示ID(可选)

举些例子,如: 

所有联系人的Uri: content://contacts/people

某个联系人的Uri: content://contacts/people/5

所有图片的Uri: content://media/external

某个图片的Uri:content://media/external/images/media/4


我们经常需要解析Uri,并从Uri中获取数据。

Android系统提供了两个用于操作Uri的工具类,分别为UriMatcher 和ContentUris

以下是一个简单的使用例子:

import android.app.Activity;
import android.app.Notification;
import android.content.Intent;
import android.database.Cursor;
import android.provider.Contacts.Phones;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
 
public class MainActivity extends Activity {
	private static final String AUTHORITY = "com.example.test";
	private static final int PEOPLE = 1;
	private static final int PEOPLE_ID = 2;
	
    private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

//当类被载入时,静态代码块被执行,且只被执行一次
static{	
    uriMatcher.addURI(AUTHORITY, "People", PEOPLE);       //添加URI匹配规则, 若URI为content://AUTHORITY/People, 则对应PEOPLE
    uriMatcher.addURI(AUTHORITY, "People/#", PEOPLE_ID);  //同上, #为通配符, 代表任意数字
}

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        Uri myUri = Uri.parse("content://"+AUTHORITY+"/People");  //构造URI
        String result = getType(myUri);
        Uri myUri2 = ContentUris.withAppendedId(myUri, 10);    //在URI后添加数字,content://AUTHORITY/People/10
        String result2 = getType(myUri2);
        Toast.makeText(this, result2, Toast.LENGTH_LONG).show();
        
    }
    
    private String getType(Uri uri){
    	int match = uriMatcher.match(uri); //与已经添加的URI进行匹配,并返回前面设置的标识数字
    	switch(match){
    	case PEOPLE:
    		return "all the people";       
    	case PEOPLE_ID:{
    		long code = ContentUris.parseId(uri);   //取得ContentUris.withAppendedID设置的数字ID
    		return "peopleId: "+code;
    	}
    	default:
    		return null;
    	}
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值