学习记录:android GrantUriPermission

                     android GrantUriPermission 实例

1,背景

        关于Provider,作为数据存储一直是安全性问题比较多的地方,比如worldreadable,openfile,uri-path等,关于前面的情况,基本上有很多案例,这里就不在多说,一直以来关于GrantUriPermission在心头是个小病,并且没有亲手实践过(平时看代码比较多,偶尔动手写就会比较生分,还是有照顾一下)


2,GrantPermission的实例代码

代码的主题部分主要来源:

https://thinkandroid.wordpress.com/2010/01/13/writing-your-own-contentprovider/

https://thinkandroid.wordpress.com/2012/08/07/granting-content-provider-uri-permissions/

稍微做了部分修改,这篇稳定的代码直接使用时启动不了的。

2.1 APP1源码:

provider源码:

public class NotesContentProvider extends ContentProvider {

    private static final String TAG = "NotesContentProvider";

    private static final String DATABASE_NAME = "notes.db";

    private static final int DATABASE_VERSION = 1;

    private static final String NOTES_TABLE_NAME = "notes";

    public static final String AUTHORITY = "com.example.granturipermissiontest.providers.NotesContentProvider";

    private static final UriMatcher sUriMatcher;

    private static final int NOTES = 1;

    private static final int NOTES_ID = 2;

    private static HashMap notesProjectionMap;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE " + NOTES_TABLE_NAME + " (" + Notes.NOTE_ID
                    + " INTEGER PRIMARY KEY AUTOINCREMENT," + Notes.TITLE + " VARCHAR(255)," + Notes.TEXT + " LONGTEXT" + ");");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + NOTES_TABLE_NAME);
            onCreate(db);
        }
    }

    private DatabaseHelper dbHelper;

    @Override
    public int delete(Uri uri, String where, String[] whereArgs) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        switch (sUriMatcher.match(uri)) {
            case NOTES:
                break;
            case NOTES_ID:
                where = where + "_id = " + uri.getLastPathSegment();
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }

        int count = db.delete(NOTES_TABLE_NAME, where, whereArgs);
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    @Override
    public String getType(Uri uri) {
        switch (sUriMatcher.match(uri)) {
            case NOTES:
                return Notes.NOTES_TYPE;
            case NOTES_ID:
                return Notes.NOTES_ID_TYPE;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues initialValues) {
        if (sUriMatcher.match(uri) != NOTES) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        ContentValues values;
        if (initialValues != null) {
            values = new ContentValues(initialValues);
        } else {
            values = new ContentValues();
        }

        SQLiteDatabase db = dbHelper.getWritableDatabase();
        long rowId = db.insert(NOTES_TABLE_NAME, Notes.TEXT, values);
        if (rowId > 0) {
            Uri noteUri = ContentUris.withAppendedId(Notes.CONTENT_URI, rowId);
            getContext().getContentResolver().notifyChange(noteUri, null);
            return noteUri;
        }

        throw new SQLException("Failed to insert row into " + uri);
    }

    @Override
    public boolean onCreate() {
        dbHelper = new DatabaseHelper(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables(NOTES_TABLE_NAME);
        qb.setProjectionMap(notesProjectionMap);

        switch (sUriMatcher.match(uri)) {
            case NOTES:
                break;
            case NOTES_ID:
                selection = selection + "_id = " + uri.getLastPathSegment();
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }

        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);

        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    }

    @Override
    public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
            case NOTES:
                count = db.update(NOTES_TABLE_NAME, values, where, whereArgs);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    static {
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(AUTHORITY, NOTES_TABLE_NAME, NOTES);
        sUriMatcher.addURI(AUTHORITY, NOTES_TABLE_NAME + "/#", NOTES_ID);

        notesProjectionMap = new HashMap();
        notesProjectionMap.put(Notes.NOTE_ID, Notes.NOTE_ID);
        notesProjectionMap.put(Notes.TITLE, Notes.TITLE);
        notesProjectionMap.put(Notes.TEXT, Notes.TEXT);
    }
}

 
  

notes源码:

public class Note {

    public Note() {
    }

    public static final class Notes implements BaseColumns {
        private Notes() {
        }

        public static final Uri CONTENT_URI = Uri.parse("content://"
                + NotesContentProvider.AUTHORITY + "/notes");

        public static final String NOTES_TYPE = "vnd.android.cursor.dir/NOTES";
        public static final String NOTES_ID_TYPE = "vnd.android.cursor.item/NOTES";

        public static final String NOTE_ID = "_id";

        public static final String TITLE = "title";

        public static final String TEXT = "text";
    }

}

GrantUriPermission的源码

public class MainActivity extends Activity {
    public static final String NOTE_ACTION_VIEW = "notes.intent.action.NOTE_VIEW";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void GrantPermissionForTest(View view) {
        Uri uri = Uri.parse("content://com.example.granturipermissiontest.providers.NotesContentProvider/notes");
        Intent intent = new Intent();
        intent.setAction(NOTE_ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.setData(uri);
        startActivity(intent);
//        grantUriPermission("com.example.acceptpermissions", uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 显示启动
//        grantUriPermission("com.example.acceptpermissions", uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }
}

layout源码:




    

AndroidManifest.xml



    
    
    
    
    
    
    
        
            
                

                
            
        

        
        
    


2.1 APP2源码:

public class AccpetActivity extends Activity {
    private ContentResolver resolver;
    private Uri myUri;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_accpet);
        Intent mIntent = getIntent();
        if(mIntent != null && null != mIntent.getData())
            myUri = mIntent.getData();
        InitSqlite(myUri);
    }

    public void InitSqlite(Uri uri) {
        ContentResolver resolver = this.getContentResolver();
        Cursor cursor = resolver.query(uri, null, null, null, null);
        if(cursor == null || cursor.getCount() < 2) {
            ContentValues values = new ContentValues();
            values.put("title", "test2");
            values.put("text", "justfortest2");
            resolver.insert(uri, values);
        }
    }
    public void InsertNotes(View view) {
//        Uri myUri = Uri.parse("content://com.example.notes.providers.NotesContentProvider/notes/1");
// 此处无论如何不要使用固定的uri,只能使用从intent传入的,即使是完全相同也会报无权限
        ContentResolver resolver = this.getContentResolver();
        Cursor cursor = resolver.query(myUri, null, null, null, null);
        if(cursor == null || cursor.getCount() < 10) {
            ContentValues values = new ContentValues();
            values.put("title", "zhuxian");
            values.put("text", "goodbook");
            resolver.insert(myUri, values);
        }
    }
}

 
  

layout source

    


AndroidManifest.xml




    
        
            
                
                
            
        
        
            
                
                
                
            
        
    


//关于Data的属性,这里非常重要,必须要完全匹配,上面的参考文章就是因为设置问题,导致无法启动activity

可以参考这里如何设置:

http://blog.csdn.net/lixiang0522/article/details/7615707

http://blog.csdn.net/u012702547/article/details/50193967
关于具体的属性含义
 http://www.cnblogs.com/newcj/archive/2011/08/11/2135094.html

当然,如果不,能够打开google官网查看,是最好不过了


3,运行结果

第一行是启动立即插入的,后面是点击多次插入的数据

学习记录:android GrantUriPermission_第1张图片


备注:

如果大家想自己实现一个其他的contentprovider,建议这篇文章,比较负责,格式排版都不错:

http://www.cnblogs.com/smyhvae/p/4108017.html

关于安全?其实就是显示和隐式的区别

https://www.blackhat.com/presentations/bh-usa-09/BURNS/BHUSA09-Burns-AndroidSurgery-PAPER.pdf

你可能感兴趣的:(Android,安全)