Поделиться через


Quickstart: Receiving shared content (XAML)

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

This Quickstart walks you through the steps required to receive shared content from another app.

Objective: To learn how to receive shared content.

Prerequisites

  • You should be familiar with Visual Studio and its templates.
  • You should be familiar with developing in C#/C++.

Instructions

Supporting the Share contract

Before your app can receive shared content, you have to declare that it supports the Share contract. This contract lets the system know that your app is available to receive content. If you're using a Visual Studio template to create your app, here's how you support the Share contract:

  1. Open the manifest file. It should be called something like package.appxmanifest.
  2. Open the Declarations tab.
  3. Choose Share Target from the Available Declarations list and click Add.

Specify the file types and data formats that you support

As a target app developer, you need to decide what file types and data formats you want to support. To specify the file types you support:

  1. Open the manifest file. It should be called something like package.appxmanifest.
  2. In the Supported File Types section of the Declarations page, click Add New.
  3. Type the file name extension that you want to support. For example, .docx. You need to include the period (.).

If you want to support all file types, check the SupportsAnyFileType box.

To specify the data formats that you support:

  1. Open the manifest file.
  2. In the Data Formats section of the Declarations page, click Add New.
  3. Type the name of the data format you support. For example, "Text".

The Share APIs support several standard formats, such as Text, HTML, and Bitmap. You can also specify custom file types and data formats. If you do, remember that source apps have to know what those types and formats are, otherwise those apps can't use the formats to share data.

Adding the DataTransfer namespaces

You need to add the right namespaces to your app so you can handle share activation events, and create and process the objects related to sharing. For a target app, you'll need the Windows.ApplicationModel.Activation, Windows.ApplicationModel.DataTransfer, and Windows.ApplicationModel.DataTransfer.ShareTarget namespaces:

using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.DataTransfer;
using Windows.ApplicationModel.DataTransfer.ShareTarget;
using namespace concurrency; 
using namespace Windows::ApplicationModel::Activation;
using namespace Windows::ApplicationModel::DataTransfer;
using namespace Windows::ApplicationModel::DataTransfer::ShareTarget;

Handling share activation

When a user selects your app (usually by selecting it from a list of available target apps in the share UI), an Application.OnShareTargetActivated event is fired. Your app needs to handle this event to process the data the user wants to share.

protected override async void OnShareTargetActivated(ShareTargetActivatedEventArgs args)
{
    // Code to handle activation goes here. 
}

Note  

If your app is running when it is activated as a Share target, the existing instance of your app is terminated and a new instance of your app is launched to handle the contract.

void App::OnShareTargetActivated(ShareTargetActivatedEventArgs^ args)
{
    // Code to handle activation goes here. 
}

The data that the user wants to share is contained in a ShareOperation object. You can use this object to check the format of the data it contains. Here's an example of an event handler that handles shared content in plain text format:

ShareOperation shareOperation = args.ShareOperation;
if (shareOperation.Data.Contains(StandardDataFormats.Text))
{
    string text = await shareOperation.Data.GetTextAsync();

    // To output the text from this example, you need a TextBlock control
    // with a name of "sharedContent".
    sharedContent.Text = "Text: " + text;
}
ShareOperation^ shareOperation = args->ShareOperation;
if (shareOperation->Data->Contains(StandardDataFormats::Text))
{
    create_task(shareOperation->Data->GetTextAsync()).then([this](Platform::String^ text)
    {
        // To output the text from this example, you need a TextBlock control
        // with a name of "sharedContent".
        sharedContent.Text = "Text: " + text;
            
    });     
}

Report extended share status (for lengthy operations)

Note  

The following step applies only to Windows Store apps. You can call the reporting methods below from Windows Phone 8.1, but no data will be returned.

In some cases, it can take time for your app to process the data it wants to share. We call these situations extended shares. Examples of extended shares include users sharing collections of files or images. These items are larger than a simple text string, so they take longer to process.

Note  If you're only interested in sharing simple things like text or a hyperlink, you can skip this section.

 

As a target app, your app should not force the user to stay in the share UI just because your app needs more time to handle data. Instead, you should use the ShareOperation object to let the system know that your app is still working. That way, the user can dismiss the share UI and return to what they were doing. Meanwhile, your app continues to process the data in the background.

shareOperation.ReportStarted();
shareOperation->ReportStarted();

After you call ReportStarted, don't expect any more user interaction with your app. As a result, you shouldn't call it unless you're app is at a point where it can be dismissed by the user.

With an extended share, it's possible that the user might dismiss the source app before your app has all the data from the DataPackage object. As a result, we recommend that you let the system know when your app has acquired the data it needs. This way, the system can suspend or terminate the source app as necessary.

shareOperation.ReportDataRetreived();
shareOperation->ReportDataRetreived();

It's also a good idea to let the system know if you're using on of the Windows.Networking.BackgroundTransfer classes to upload your content. You can do this with the ReportSubmittedBackgroundTask method.

shareOperation.ReportSubmittedBackgroundTask();
shareOperation->ReportSubmittedBackgroundTask();

If something goes wrong, you can also call ReportError to send an error message to the system. The user will see the message when they check on the status of the share. At that point, your app is shut down and the share is ended—the user will need to start again to share the content to your app. Depending on your scenario, you may decide that a particular error isn't serious enough to end the share operation. In that case, you can choose to not call ReportError and to continue with the share.

shareOperation.ReportError("Could not reach the server! Try again later.");
shareOperation->ReportError("Could not reach the server! Try again later.");

When you use these methods, you usually call them in the order just described, and you don't call them more than once. However, there are times when a target app can call ReportDataRetrieved before ReportStarted. For example, the app might retrieve the data as part of a task in the activation handler, but not call ReportStarted until the user clicks a Share button.

To see sharing in action, see our Sharing content target app sample.

Report that sharing has been completed

Finally, when your app has successfully processed the shared content, you should call ReportCompleted to let the system know.

shareOperation.ReportCompleted();
shareOperation->ReportCompleted();

After your app knows the share is complete, your app is dismissed.

Note  

QuickLinks are not supported in Windows Phone 8.1. Windows Phone Store apps can receive QuickLinks as part of a share operation, but they will be automatically ignored.

When a user selects your app to receive shared content, we highly recommend that you create a QuickLink. A QuickLink is like a shortcut that makes it easier for users to share information with your app. For example, your app could create a QuickLink that opens a new mail message pre-configured with a friend's email address.

A QuickLink must have a title, an icon, and an ID. The title (like "Email Mom") and icon appear when the user taps the Share charm. The ID is what your app uses to access any custom information, such as an email address or login credentials. When your app creates a QuickLink, the app returns the QuickLink to the system by calling the ShareOperation object's ReportCompleted method. Here's an example:

async void ReportCompleted(ShareOperation shareOperation, string quickLinkId, string quickLinkTitle)
{
    QuickLink quickLinkInfo = new QuickLink
    {
        Id = quickLinkId,
        Title = quickLinkTitle,

        // For quicklinks, the supported FileTypes and DataFormats are set 
        // independently from the manifest
        SupportedFileTypes = { "*" },
        SupportedDataFormats = { StandardDataFormats.Text, StandardDataFormats.Uri, 
                StandardDataFormats.Bitmap, StandardDataFormats.StorageItems }
    };

    StorageFile iconFile = await Windows.ApplicationModel.Package.Current.InstalledLocation.CreateFileAsync(
            "assets\\user.png", CreationCollisionOption.OpenIfExists);
    quickLinkInfo.Thumbnail = RandomAccessStreamReference.CreateFromFile(iconFile);
    shareOperation.ReportCompleted(quickLinkInfo);
}
void YourClass::ReportCompleted(ShareOperation^ shareOperation, String^ quickLinkId, String^ quickLinkTitle)
{
    QuickLink^ quickLinkInfo = ref new QuickLink();
    quickLinkInfo->Id = quickLinkId;
    quickLinkInfo->Title = quickLinkTitle;

    // For QuickLinks, the supported FileTypes and DataFormats are set independently from the manifest.
    quickLinkInfo->SupportedFileTypes->Append("*");
    quickLinkInfo->SupportedDataFormats->Append(StandardDataFormats::Text);
    quickLinkInfo->SupportedDataFormats->Append(StandardDataFormats::Uri);
    quickLinkInfo->SupportedDataFormats->Append(StandardDataFormats::Bitmap);
    quickLinkInfo->SupportedDataFormats->Append(StandardDataFormats::StorageItems);

    create_task(Package::Current->InstalledLocation->CreateFileAsync("assets\\user.png", CreationCollisionOption::OpenIfExists)).then(
        [this, shareOperation, quickLinkInfo](StorageFile^ iconFile)
    {
        quickLinkInfo->Thumbnail = RandomAccessStreamReference::CreateFromFile(iconFile);
        shareOperation->ReportCompleted(quickLinkInfo);      
    });
}

Remember that your app is responsible for storing the ID of the QuickLink and the corresponding user data. When the user taps the QuickLink, you can get its ID through the QuickLinkId property of the ShareOperation object.

Summary and next steps

Now you should have a good idea how to received shared content, and how to create a QuickLink to help users share content with your app.

To learn more, or to get more specific examples of how to add sharing to your app, you might want to take a look at:

Note  Debugging a share target app is different from debugging other kinds of apps. To learn more, see Guidelines for debugging target apps.

 

Choosing data formats for sharing

Guidelines and checklist for sharing content

Quickstart: Sharing content