1. 程式人生 > >android官方API之ContentProvider

android官方API之ContentProvider

來源:https://developer.android.com/reference/android/content/ContentProvider

ContentProvider

public abstract class ContentProvider 
extends Object implements ComponentCallbacks2

java.lang.Object
   ↳ android.content.ContentProvider
Known direct subclasses

DocumentsProviderMockContentProviderSearchRecentSuggestionsProviderSliceProvider

 


Content providers are one of the primary building blocks of Android applications, providing content to applications. They encapsulate data and provide it to applications through the single 

ContentResolver interface. A content provider is only required if you need to share data between multiple applications. For example, the contacts data is used by multiple applications and must be stored in a content provider. If you don't need to share data amongst multiple applications you can use a database directly via 
SQLiteDatabase
.

When a request is made via a ContentResolver the system inspects the authority of the given URI and passes the request to the content provider registered with the authority. The content provider can interpret the rest of the URI however it wants. The UriMatcher class is helpful for parsing URIs.

The primary methods that need to be implemented are:

 

Data access methods (such as insert(Uri, ContentValues) and update(Uri, ContentValues, String, String[])) may be called from many threads at once, and must be thread-safe. Other methods (such as onCreate()) are only called from the application main thread, and must avoid performing lengthy operations. See the method descriptions for their expected thread behavior.

Requests to ContentResolver are automatically forwarded to the appropriate ContentProvider instance, so subclasses don't have to worry about the details of cross-process calls.

Developer Guides

For more information about using content providers, read the Content Providers developer guide.

 

Summary

Nested classes

interface ContentProvider.PipeDataWriter<T>

Interface to write a stream of data to a pipe. 

Inherited constants

From interface android.content.ComponentCallbacks2

Public constructors

ContentProvider()

Construct a ContentProvider instance.

Public methods

ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)

Override this to handle requests to perform a batch of operations, or the default implementation will iterate over the operations and call ContentProviderOperation.apply(ContentProvider, ContentProviderResult[], int) on each of them.

void attachInfo(Context context, ProviderInfo info)

After being instantiated, this is called to tell the content provider about itself.

int bulkInsert(Uri uri, ContentValues[] values)

Override this to handle requests to insert a set of new rows, or the default implementation will iterate over the values and call insert(Uri, ContentValues) on each of them.

Bundle call(String method, String arg, Bundle extras)

Call a provider-defined method.

Uri canonicalize(Uri url)

Implement this to support canonicalization of URIs that refer to your content provider.

abstract int delete(Uri uri, String selection, String[] selectionArgs)

Implement this to handle requests to delete one or more rows.

void dump(FileDescriptor fd, PrintWriter writer, String[] args)

Print the Provider's state into the given stream.

final String getCallingPackage()

Return the package name of the caller that initiated the request being processed on the current thread.

final Context getContext()

Retrieves the Context this provider is running in.

final PathPermission[] getPathPermissions()

Return the path-based permissions required for read and/or write access to this content provider.

final String getReadPermission()

Return the name of the permission required for read-only access to this content provider.

String[] getStreamTypes(Uri uri, String mimeTypeFilter)

Called by a client to determine the types of data streams that this content provider supports for the given URI.

abstract String getType(Uri uri)

Implement this to handle requests for the MIME type of the data at the given URI.

final String getWritePermission()

Return the name of the permission required for read/write access to this content provider.

abstract Uri insert(Uri uri, ContentValues values)

Implement this to handle requests to insert a new row.

void onConfigurationChanged(Configuration newConfig)

Called by the system when the device configuration changes while your component is running. This method is always called on the application main thread, and must not perform lengthy operations.

abstract boolean onCreate()

Implement this to initialize your content provider on startup.

void onLowMemory()

This is called when the overall system is running low on memory, and actively running processes should trim their memory usage. This method is always called on the application main thread, and must not perform lengthy operations.

void onTrimMemory(int level)

Called when the operating system has determined that it is a good time for a process to trim unneeded memory from its process.

AssetFileDescriptor openAssetFile(Uri uri, String mode, CancellationSignal signal)

This is like openFile(Uri, String), but can be implemented by providers that need to be able to return sub-sections of files, often assets inside of their .apk.

AssetFileDescriptor openAssetFile(Uri uri, String mode)

This is like openFile(Uri, String), but can be implemented by providers that need to be able to return sub-sections of files, often assets inside of their .apk.

ParcelFileDescriptor openFile(Uri uri, String mode, CancellationSignal signal)

Override this to handle requests to open a file blob.

ParcelFileDescriptor openFile(Uri uri, String mode)

Override this to handle requests to open a file blob.

<T>ParcelFileDescriptor openPipeHelper(Uri uri, String mimeType, Bundle opts, T args,PipeDataWriter<T> func)

A helper function for implementing openTypedAssetFile(Uri, String, Bundle), for creating a data pipe and background thread allowing you to stream generated data back to the client.

AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts)

Called by a client to open a read-only stream containing data of a particular MIME type.

AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts,CancellationSignal signal)

Called by a client to open a read-only stream containing data of a particular MIME type.

Cursor query(Uri uri, String[] projection, Bundle queryArgs, CancellationSignalcancellationSignal)

Implement this to handle query requests where the arguments are packed into a Bundle.

Cursor query(Uri uri, String[] projection, String selection, String[]selectionArgs, String sortOrder, CancellationSignal cancellationSignal)

Implement this to handle query requests from clients with support for cancellation.

abstract Cursor query(Uri uri, String[] projection, String selection, String[]selectionArgs, String sortOrder)

Implement this to handle query requests from clients.

boolean refresh(Uri uri, Bundle args, CancellationSignal cancellationSignal)

Implement this to support refresh of content identified by uri.

void shutdown()

Implement this to shut down the ContentProvider instance.

Uri uncanonicalize(Uri url)

Remove canonicalization from canonical URIs previously returned by canonicalize(Uri).

abstract int update(Uri uri, ContentValues values, String selection, String[]selectionArgs)

Implement this to handle requests to update one or more rows.

Protected methods

boolean isTemporary()

Returns true if this instance is a temporary content provider.

finalParcelFileDescriptor openFileHelper(Uri uri, String mode)

Convenience for subclasses that wish to implement openFile(Uri, String) by looking up a column named "_data" at the given URI.

final void setPathPermissions(PathPermission[] permissions)

Change the path-based permission required to read and/or write data in the content provider.

final void setReadPermission(String permission)

Change the permission required to read data from the content provider.

final void setWritePermission(String permission)

Change the permission required to read and write data in the content provider.

Inherited methods

From class java.lang.Object

From interface android.content.ComponentCallbacks2

From interface android.content.ComponentCallbacks

Public constructors

ContentProvider

added in API level 1

 

public ContentProvider ()

Construct a ContentProvider instance. Content providers must be declared in the manifest, accessed with ContentResolver, and created automatically by the system, so applications usually do not create ContentProvider instances directly.

At construction time, the object is uninitialized, and most fields and methods are unavailable. Subclasses should initialize themselves in onCreate(), not the constructor.

Content providers are created on the application main thread at application launch time. The constructor must not perform lengthy operations, or application startup will be delayed.

 

Public methods

applyBatch

added in API level 5

 

public ContentProviderResult[] applyBatch (ArrayList<ContentProviderOperation> operations)

Override this to handle requests to perform a batch of operations, or the default implementation will iterate over the operations and call ContentProviderOperation.apply(ContentProvider, ContentProviderResult[], int) on each of them. If all calls to ContentProviderOperation.apply(ContentProvider, ContentProviderResult[], int) succeed then a ContentProviderResult array with as many elements as there were operations will be returned. If any of the calls fail, it is up to the implementation how many of the others take effect. This method can be called from multiple threads, as described in Processes and Threads.

 

Parameters
operations ArrayList: the operations to apply

This value must never be null.

Returns
ContentProviderResult[] the results of the applications

This value will never be null.

Throws
OperationApplicationException thrown if any operation fails.

See also:

attachInfo

added in API level 1

 

public void attachInfo (Context context, ProviderInfo info)

After being instantiated, this is called to tell the content provider about itself.

 

Parameters
context Context: The context this provider is running in

 

info ProviderInfo: Registered information about this content provider

 

bulkInsert

added in API level 1

 

public int bulkInsert (Uri uri, ContentValues[] values)

Override this to handle requests to insert a set of new rows, or the default implementation will iterate over the values and call insert(Uri, ContentValues) on each of them. As a courtesy, call notifyChange() after inserting. This method can be called from multiple threads, as described in Processes and Threads.

 

Parameters
uri Uri: The content:// URI of the insertion request.

This value must never be null.

values ContentValues: An array of sets of column_name/value pairs to add to the database. This must not be null.

 

Returns
int The number of values that were inserted.

 

call

added in API level 11

 

public Bundle call (String method, String arg, Bundle extras)

Call a provider-defined method. This can be used to implement interfaces that are cheaper and/or unnatural for a table-like model.

WARNING: The framework does no permission checking on this entry into the content provider besides the basic ability for the application to get access to the provider at all. For example, it has no idea whether the call being executed may read or write data in the provider, so can't enforce those individual permissions. Any implementation of this method must do its own permission checks on incoming calls to make sure they are allowed.

 

 

Parameters
method String: method name to call. Opaque to framework, but should not be null.

 

arg String: provider-defined String argument. May be null.

 

extras Bundle: provider-defined Bundle argument. May be null.

 

Returns
Bundle provider-defined return value. May be null, which is also the default for providers which don't implement any call methods.

 

canonicalize

added in API level 19

 

public Uri canonicalize (Uri url)

Implement this to support canonicalization of URIs that refer to your content provider. A canonical URI is one that can be transported across devices, backup/restore, and other contexts, and still be able to refer to the same data item. Typically this is implemented by adding query params to the URI allowing the content provider to verify that an incoming canonical URI references the same data as it was originally intended for and, if it doesn't, to find that data (if it exists) in the current environment.

For example, if the content provider holds people and a normal URI in it is created with a row index into that people database, the cananical representation may have an additional query param at the end which specifies the name of the person it is intended for. Later calls into the provider with that URI will look up the row of that URI's base index and, if it doesn't match or its entry's name doesn't match the name in the query param, perform a query on its database to find the correct row to operate on.

If you implement support for canonical URIs, all incoming calls with URIs (including this one) must perform this verification and recovery of any canonical URIs they receive. In addition, you must also implementuncanonicalize(Uri) to strip the canonicalization of any of these URIs.

The default implementation of this method returns null, indicating that canonical URIs are not supported.

 

 

Parameters
url Uri: The Uri to canonicalize.

This value must never be null.

Returns
Uri Return the canonical representation of url, or null if canonicalization of that Uri is not supported.

 

delete

added in API level 1

 

public abstract int delete (Uri uri, String selection, String[] selectionArgs)

Implement this to handle requests to delete one or more rows. The implementation should apply the selection clause when performing deletion, allowing the operation to affect multiple rows in a directory. As a courtesy, call notifyChange() after deleting. This method can be called from multiple threads, as described in Processes and Threads.

The implementation is responsible for parsing out a row ID at the end of the URI, if a specific row is being deleted. That is, the client would pass in content://contacts/people/22 and the implementation is responsible for parsing the record number (22) when creating a SQL statement.

 

Parameters
uri Uri: The full URI to query, including a row ID (if a specific record is requested).

This value must never be null.

selection String: An optional restriction to apply to rows when deleting.

This value may be null.

selectionArgs String

This value may be null.

Returns
int The number of rows affected.

 

Throws
SQLException  

dump

added in API level 18

 

public void dump (FileDescriptor fd, PrintWriter writer, String[] args)

Print the Provider's state into the given stream. This gets invoked if you run "adb shell dumpsys activity provider <provider_component_name>".

 

Parameters
fd FileDescriptor: The raw file descriptor that the dump is being sent to.

 

writer PrintWriter: The PrintWriter to which you should dump your state. This will be closed for you after you return.

 

args String: additional arguments to the dump request.

 

getCallingPackage

added in API level 19

 

public final String getCallingPackage ()

Return the package name of the caller that initiated the request being processed on the current thread. The returned package will have been verified to belong to the calling UID. Returns null if not currently processing a request.

This will always return null when processing getType(Uri) or getStreamTypes(Uri, String) requests.

 

Returns
String

This value may be null.

Throws
SecurityException if the calling package doesn't belong to the calling UID.

See also:

getContext

added in API level 1

 

public final Context getContext ()

Retrieves the Context this provider is running in. Only available once onCreate() has been called -- this will return nullin the constructor.

 

Returns
Context

This value may be null.

getPathPermissions

added in API level 4

 

public final PathPermission[] getPathPermissions ()

Return the path-based permissions required for read and/or write access to this content provider. This method can be called from multiple threads, as described in Processes and Threads.

 

Returns
PathPermission[]

This value may be null.

getReadPermission

added in API level 1

 

public final String getReadPermission ()

Return the name of the permission required for read-only access to this content provider. This method can be called from multiple threads, as described in Processes and Threads.

 

Returns
String

This value may be null.

getStreamTypes

added in API level 11

 

public String[] getStreamTypes (Uri uri, String mimeTypeFilter)

Called by a client to determine the types of data streams that this content provider supports for the given URI. The default implementation returns null, meaning no types. If your content provider stores data of a particular type, return that MIME type if it matches the given mimeTypeFilter. If it can perform type conversions, return an array of all supported MIME types that match mimeTypeFilter.

 

Parameters
uri Uri: The data in the content provider being queried.

This value must never be null.

mimeTypeFilter String: The type of data the client desires. May be a pattern, such as */* to retrieve all possible data types.

This value must never be null.

Returns
String[] Returns null if there are no possible data streams for the given mimeTypeFilter. Otherwise returns an array of all available concrete MIME types.

 

See also:

getType

added in API level 1

 

public abstract String getType (Uri uri)

Implement this to handle requests for the MIME type of the data at the given URI. The returned MIME type should start with vnd.android.cursor.item for a single record, or vnd.android.cursor.dir/ for multiple items. This method can be called from multiple threads, as described in Processes and Threads.

Note that there are no permissions needed for an application to access this information; if your content provider requires read and/or write permissions, or is not exported, all applications can still call this method regardless of their access permissions. This allows them to retrieve the MIME type for a URI when dispatching intents.

 

Parameters
uri Uri: the URI to query.

This value must never be null.

Returns
String a MIME type string, or null if there is no type.

 

getWritePermission

added in API level 1

 

public final String getWritePermission ()

Return the name of the permission required for read/write access to this content provider. This method can be called from multiple threads, as described in Processes and Threads.

 

Returns
String

This value may be null.

insert

added in API level 1

 

public abstract Uri insert (Uri uri, ContentValues values)

Implement this to handle requests to insert a new row. As a courtesy, call notifyChange() after inserting. This method can be called from multiple threads, as described in Processes and Threads.

 

Parameters
uri Uri: The content:// URI of the insertion request. This must not be null.

 

values ContentValues: A set of column_name/value pairs to add to the database. This must not be null.

 

Returns
Uri The URI for the newly inserted item.

This value may be null.

onConfigurationChanged

added in API level 1

 

public void onConfigurationChanged (Configuration newConfig)

Called by the system when the device configuration changes while your component is running. Note that, unlike activities, other components are never restarted when a configuration changes: they must always deal with the results of the change, such as by re-retrieving resources.

At the time that this function has been called, your Resources object will have been updated to return resource values matching the new configuration.

For more information, read 

相關推薦

android官方APIContentProvider

來源:https://developer.android.com/reference/android/content/ContentProvider ContentProvider public abstract class ContentProvider extends 

android官方APIRecyclerView

來源:https://developer.android.com/reference/android/support/v7/widget/RecyclerView RecyclerView public class RecyclerView extends ViewGro

android官方APIConstraintLayout

來源:https://developer.android.com/reference/android/support/constraint/ConstraintLayout ConstraintLayout public class ConstraintLayout extends

android官方APIAppCompatActivity

來源:https://developer.android.com/reference/android/support/v7/app/AppCompatActivity AppCompatActivity public class AppCompatActivity extends&

android官方APIToolbar

來源:https://developer.android.com/reference/android/widget/Toolbar Toolbar public class Toolbar extends ViewGroup  jav

android官方APIEditText

來源:https://developer.android.com/reference/android/widget/EditText EditText public class EditText extends TextView  j

android官方APIAsyncTask

來源:https://developer.android.com/reference/android/os/AsyncTask AsyncTask public abstract class AsyncTask extends Object 

android官方APIMediaPlayer

來源:https://developer.android.com/reference/android/media/MediaPlayer MediaPlayer public class MediaPlayer extends Object implements

android官方APIBroadcastReceiver

來源:https://developer.android.com/reference/android/content/BroadcastReceiver BroadcastReceiver public abstract class BroadcastReceiver extend

Android四大元件ContentProvider(二)

上節提到的四大元件之ContentProvider的簡單使用,在這篇文章中詳細的介紹其中的一些方法。 1.String getType(Uri uri)方法 首先看看官方對它的解釋: /** * Implement this to handle requests

Android四大元件ContentProvider(一)

1.什麼是ContentProvider? 內容提供程式管理對資料結構化資料集的訪問。它們封裝資料,並提供用於定義資料安全性的機制。內容提供者是連線一個程序中的資料與另一個程序中執行的程式碼的標準介面。 是不同應用程式之間進行資料交換的標準API,以某種Uri的形式對外提供資料,

Android四大元件ContentProvider

關於ContentProvider ContentProvider,被稱為內容提供者,通過Binder向其他元件以及其他應用提供資料。以某種Uri的形式對外提供資料,允許其他應用訪問或修改資料。其他應用程式使用ContentResolver根據Uri去訪問操作

Android四大元件ContentProvider詳解

1.適用場景 1) ContentProvider為儲存和讀取資料提供了統一的介面 2) 使用ContentProvider,應用程式可以實現資料共享 3) android內建的許多資料都是使用ContentProvider形式,供開發者呼叫的(如視訊,音訊,圖片,

Android 四大元件" ContentProvider "

前言 ContentProvider作為Android的四大元件之一,是屬於需要掌握的基礎知識,可能在我們的應用中,對於Activity和Service這兩個元件用的很常見,瞭解的也很多,但是對ContentProvider所知卻甚少,所以有必要去整理歸納下其中的內容,講講為什麼要用ContentProvid

Android 面試總結ContentProvider

1、ContentProvider 是如何實現資料共享的: 在 Android 中如果想將自己應用的資料(一般多為資料庫中的資料)提供給第三發應用,那麼我們只能通過 ContentProvider 來實現了。 ContentProvider 是應用程式之間共享資料的介面。使

Android四大元件ContentProvider內容提供器

public class MyProvider extends ContentProvider{ public static final int TABLE1_DIR = 0; public static final int TABLE1_ITEM = 1; public s

Android四大元件ContentProvider(內容提供者)

ContentProvider是什麼 ContentProvider是Android中的四大元件之一,主要用於不用應用之間共享資料,通過ContentProvider把應用中的資料共享給其他應用訪問,其他應用可以通過ContentProvider對指定應用中

小談Android四大元件ContentProvider

內容提供者的作用 1.應用程式建立的資料庫預設都是私有的,別的應用程式不可以訪問裡面的資料. 2.如果需要把自己應用程式私有的資料庫暴露給別的使用者增刪改查,就需要使用內容提供者. 3.作用: 一個應用程式訪問另外一個應用程式在硬碟上

Android官方資料-OTA Package Tools

The ota_from_target_files tool provided inbuild/tools/releasetools can build two types of package: full andincremental. The tool takes the target-files 

Android四大元件ContentProvider-劉志遠-專題視訊課程

Android四大元件之ContentProvider—4971人已學習 課程介紹        本課程向大家講述Android中的四大元件之一ContentProvider(內容提供者)課程收益    學員學習之後,能夠吃透ContentProvier講師介紹    劉志遠