Google Android Developer Documentation Series-Create shared files for apps with content sharing features

Source: Internet
Author: User

Sharing a file (shared files)

This series of articles in my study of Google Developer documentation combined with Google translation and their own understanding of the writing, I hope to learn Android development friends bring some convenience, due to the limited level of personal translation, so the content contains the original text and translation, I hope that the browser combined understanding, so as not to step into the misunderstanding I may be wrong translation. In this thank http://android.xsoftlab.net/provide the image, I hope the reprint of the source http://blog.csdn.net/u014031072/article/details/51596803 convenient to view the latest blog

Once you have the set up your app to share files using content URIs, you can respond to other apps ' requests for those files. One-to respond-these requests is-provide a file selection interface from the server app, the other applications Can invoke. This approach allows a client application-let users select a file from the server app and then receive the selected Fil E ' s content URI.
Once you've set up file sharing with the content URI in your app, you'll be able to respond to other app file requests. One way to respond to these requests is to provide a selection interface for other apps from the service app that can request a file. This approach enables the client app to allow the user to select a file on the server and then receive the content URI of the selected file.

This lesson shows the Create a file selection Activity in the your app that responds to requests for files.
This lesson shows you how to create a file selection activity in your app in response to a file request.

Receive file requests (Request for files)

To receive requests-files from the client apps and respond with a content URI, your app should provide a file selection Ac Tivity. Client apps start this Activity by calling Startactivityforresult () a Intent containing the action Action_pick. When the client app is calls Startactivityforresult (), the Your app can return a result to the client app, in the form of a conte NT URI for the file the user selected.
The request to receive a file from the client application responds and returns a content URI, and your app should provide a file selection activity. The client application initiates the request activity by calling the Startactivityforresult () method and passing in a intent that contains the Action_pick action. When a client application calls the Startactivityforresult () method, your application can return the results to the client application in the form of a user-selected file content URI.

To learn how to implement a request for a file in a client app, see the lesson requesting a Shared file.
To learn how to implement a file request in the client app, refer to requesting a Shared file course.

Create a file Selection activity (creates an activity for the selected files)

To set up the file selection activity, start by specifying the activity in your manifest, along with a intent filter that Matches the action Action_pick and the Categories Category_default and category_openable. Also Add MIME type filters for the files your app serves to other apps. The following snippet shows to specify the new Activity and intent filter:
To create a file selection activity, first define an activity in your manifest file, containing a intent filter that matches the action of Action_pick, whose categories value is Category_ Default and Category_openable. Also add a MIME type filter that your app serves for other apps. The following code slice shows how to define a new activity and its intent filter:

<manifest xmlns:android="Http://schemas.android.com/apk/res/android">...<application>...<activity android:name=". Fileselectactivity "Android:label="@"File Selector"> <intent-filter> <action android:name="Android.intent.action.PICK"/> <category android:name="Android.intent.category.DEFAULT"/> <category android:name="Android.intent.category.OPENABLE"/> <data android:mimetype="Text/plain"/> <data android:mimetype="image/*"/> </intent-filter> </activity>
Define the file selection activity in code (defines the activity in the file selection)

Next, define an Activity subclass this displays the files available from your app ' s files/images/directory in internal St Orage and allows the user to pick the desired file. The following snippet demonstrates how to define this Activity and respond to the user ' s selection:
Next, define an activity subclass to display the files available in the files/images/path in your app's internal storage and allow the user to select the desired file. The following code snippet demonstrates how to define the activity and respond to the user's choice:

 Public  class mainactivity extends Activity {    //The path to the root of this app ' s internal storage    Internal Storage root path for//app    PrivateFile Mprivaterootdir;//The path to the "images" subdirectory    //images Sub-path    PrivateFile Mimagesdir;//Array of files in the images subdirectory    List of files under//images sub-pathFile[] Mimagefiles;//Array of filenames corresponding to Mimagefiles    List of file names in the///iamges file listingString[] Mimagefilenames;//Initialize the Activity    //Initialize activity    @Override    protected void onCreate(Bundle savedinstancestate) {        ...//Set up-an Intent-to-send back-to-apps that request a file        //Define a intent to send back to the app that made the file requestMresultintent =NewIntent ("Com.example.myapp.ACTION_RETURN_FILE");//Get the files/subdirectory of internal storage        //Get sub-paths of files/paths in memoryMprivaterootdir = Getfilesdir ();//Get the files/images subdirectory;        //Get sub-path of Files/images pathMimagesdir =NewFile (Mprivaterootdir,"Images");//Get The files in the images subdirectory        //Get a list of files under the images sub-pathMimagefiles = Mimagesdir.listfiles ();//Set The Activity ' s result to null-begin with        //Set the activity's return result to nullSetresult (activity.result_canceled,NULL);/ * Display The file names in the ListView Mfilelistview.         * Back the ListView with the array mimagefilenames, which * can create by iterating through Mimagefiles and * Calling File.getabsolutepath () for each File */...    } ...}
Respond to a file Selection (response File Selection interface)

Once A user selects a shared file, your application must determine what file is selected and then generate a content U RI for the file. Since The Activity displays the list of available files in a ListView, when the user clicks a file name the system calls T He method Onitemclick (), in which you can get the selected file.
Once a user selects a shared file, your app must decide which file is selected and then produce the content URI for that file. Because activity displays a list of available files in the ListView, when the user taps the file name, the system calls the ListView Onitemclick () method, in which case you can get to the selected file.

In Onitemclick (), get a file object for the file name of the selected file and pass it as an argument to Geturiforfile (), Along with the authority so you specified in the <? (remove question mark) provider> element for the Fileprovider. The resulting content URI contains the authority, a path segment corresponding to the file's directory (as specified in th e XML meta-data), and the name of the file including its extension. How Fileprovider maps directories to path segments based on XML Meta-data are described in the section specify Sharable Dir Ectories.
In Onitemclick (), get a file object corresponding to the file name, and the < associated with Fileprovider; (remove the question mark) provider> with the defined permissions in the feature, passed as a parameter to the Geturiforfile () method. The resulting content URI contains permissions, a path segment corresponding to the file's directory (as specified in the XML), and a file name that contains its extension. Fileprovider How to map the file path of a path fragment, based on the description of XML meta-data in the Specify Sharable directories section

The following snippet shows you what to detect the selected file and get a content URI for it:
The following code snippet shows how to detect a selected file and get a content URI corresponding to it:

protected void OnCreate (Bundle savedinstancestate) {...Define a listener that responds to clicks on a fileinchThe ListView//defines a listener to respond to the Click event in the ListView Mfilelistview.setonitemclicklistener (New Adapterview . Onitemclicklistener () {@Override/* * when a filenameinchThe ListView is clicked, get their * content URI and send it to the requesting app *//                    When a file name in the ListView is clicked, it gets its content URI and sends it to the request app public void Onitemclick (Adapterview<?> adapterview,                 View view, int position, long rowId) {/* * Get a File forThe selected file name. * Assume that the file names isinchThe * mimagefilename array. *//Get a file corresponding to the selected file name, assuming that the file name is in the mimagefilename array requestfile = new file (mimagefilename[pos                Ition]); /* * Most file-related method calls need to beinch*Try-catch blocks. *///Most file-related method calls need to beTry-catch block in//use the Fileprovider to get a content URI//using Fileprovider to get a content URITry{Fileuri = Fileprovider.geturiforfile (Mainactivity.this,"Com.example.myapp.fileprovider", RequestFile); } catch (IllegalArgumentException e) {LOG.E ("File Selector","The selected file can ' t be shared:"+ Clickedfilename); }...}        });...}

Remember that's generate content URIs for files, reside in a directory, you ' ve specified in the Meta-data fi Le that contains the <? (remove question mark) paths> element, as described in the section specify sharable directories. If you call Geturiforfile () for a File with a path that is haven ' t specified, you receive an illegalargumentexception.
Remember, you can only produce < that are included in the Meta-data file;? (remove question mark) The content URI of the file corresponding to the file path defined in the Paths> feature (as described in the Specify Sharable directories section). If you call the Geturiforfile () method for a file that is not well defined, you will receive an IllegalArgumentException exception.

Grant Permissions for the file (authorization for files)

Now there is a content URI for the file you want to share with another app, and you need the client app to Acces s the file. To allow access, grant permissions to the client app by adding the content URI to a Intent and then setting permission FL AGS on the Intent. The permissions you grant was temporary and expire automatically when the receiving app's task stack is finished.
Now that you have a content URI for a file that you want to share with other apps, you need to allow the client app to enter the file. To enter the file, grant the client app permission by adding the content URI to a intent and then setting the permissions tag to the intent. The permissions you grant are temporary and can be canceled automatically when the stack task of receiving the app is complete.

The following code snippet shows you are set Read permission for the file:
The following code snippet shows how to set the Read permission for a file:

protected void OnCreate (Bundle savedinstancestate) {...Define a listener that responds to clicksinchThe ListView Mfilelistview.setonitemclicklistener (new Adapterview.onitemclicklistener () {                    @Override public void Onitemclick (adapterview<?> adapterview, view view, int position, long rowId) {...                if(Fileuri! = null)                    {//Grant temporary Read permission to the Content URI//Set temporary Read permission for content URI                Mresultintent.addflags (intent.flag_grant_read_uri_permission); }...}...});...}

caution:calling SetFlags () is the only-to-securely grant access to your files using temporary access permissions. Avoid calling Context.granturipermission () method for a file's content URI, since this method grants access so you can Only revoke by calling Context.revokeuripermission ().
Note: Calling the SetFlags () method is the only safe way to grant your file access permissions with temporary access permissions. Avoid calling the Context.granturipermission () method for the file's content URI, because the permission that this method obtains can only be canceled by calling the Context.revokeuripermission () method.

Share the file with the requesting app (share files with the requesting app)

To share the file with the app, this requested it, pass the Intent containing the content URI and permissions to Setresult ( ). When the Activity has just defined is finished, the system sends the Intent containing the content URI to the client App. The following code snippet shows you what do this:
To share files with the app requesting the files, you need to pass the intent to Setresult () method that contains the content URI and permissions. When you have defined the activity where these operations are destroyed, the system sends a intent to the client app that contains the content URI. The following code slice shows how to implement:

protected void OnCreate (Bundle savedinstancestate) {...Define a listener that responds to clicks on a fileinchThe ListView Mfilelistview.setonitemclicklistener (new Adapterview.onitemclicklistener () {                    @Override public void Onitemclick (adapterview<?> adapterview, view view, int position, long rowId) {...                if(Fileuri! = null) {...Put the Uri and MIME typeinchThe result Intent Mresultintent.setdataandtype (Fileuri,                    Getcontentresolver (). GetType (Fileuri)); Set The result MainActivity.this.setResult (ACTIVITY.RESULT_OK, Mresultint                    ENT); }Else{Mresultintent.setdataandtype (NULL,"");                    MainActivity.this.setResult (result_canceled, mresultintent); }                }        });

Provide users with a-to-return immediately to the client app once they has chosen a file. One-to-do-a-provide a checkmark or done button. Associate a method with the button using the button ' s Android:onclick attribute. In the method, call finish (). For example:
Once the user has selected a file, provide them with a way to return to the client app immediately. One way is to provide a flag or Finish button. You associate a method to a button by using the Android:onclick property of the button. Call the Finish () method in the method. For example:

publicvoidonDoneClick(View v) {        // Associate a method with the Done button        finish();    }

Google Android Developer Documentation Series-Create shared files for apps with content sharing features

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.