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<String, String> 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