學習記錄: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<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;
    }

    @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<String, String>();
        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源碼:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.granturipermissiontest.MainActivity">

    <Button
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="@string/grant_permission"
        android:onClick="GrantPermissionForTest" />
</RelativeLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.granturipermissiontest">
    <permission
        android:name="com.example.notes.READ_CONTENT"
        android:protectionLevel="dangerous" >
    </permission>
    <permission
        android:name="com.example.notes.WRITE_CONTENT"
        android:protectionLevel="dangerous" >
    </permission>
    <uses-permission android:name="com.example.notes.READ_CONTENT"/>
    <uses-permission android:name="com.example.notes.WRITE_CONTENT" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <provider
            android:name="com.example.granturipermissiontest.NotesContentProvider"
            android:authorities="com.example.granturipermissiontest.providers.NotesContentProvider"
            android:readPermission="com.example.notes.READ_CONTENT"
            android:writePermission="com.example.notes.WRITE_CONTENT"
            android:exported="true"
            android:grantUriPermissions="true">
        </provider>
    </application>

</manifest>

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

    <Button
        android:id="@+id/btn1"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="@string/insert_notes"
        android:onClick="InsertNotes" />


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.acceptpermissions">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".AccpetActivity"
            android:label="@string/title_activity_accpet"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="notes.intent.action.NOTE_VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="vnd.android.cursor.dir/NOTES" />
            </intent-filter>
        </activity>
    </application>

</manifest>


//關於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,運行結果

第一行是啓動立即插入的,後面是點擊多次插入的數據



備註:

如果大家想自己實現一個其他的contentprovider,建議這篇文章,比較負責,格式排版都不錯:

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

關於安全?其實就是顯示和隱式的區別

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章