MobileAndroidAndroid Development: Tracking Target Apps When Sharing Information

Android Development: Tracking Target Apps When Sharing Information

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Introduction

During mobile app development, there are at times you’ll need to share images, text, or link with other apps. The other apps could be Facebook, Twitter, e-mail, SMS, and so forth. In this article, we will learn to take subsequent actions when a target application is selected while sharing—a handler to track the selected target application.

Description

To begin with, we will create a Xamarin Forms application with two target platforms, Android and iOS. Because the share feature is platform dependent, we will use a ‘Dependency’ service to communicate between the forms and the platform-specific project. To use dependency injection, we will use FreshMVVM.

Xamarin Forms Level Changes

In the Xamarin Forms project, add a new interface named, “IShareInfo.cs,” with the following definition:

public interface IShareInfo
{
   Task ShareText(string message);
}

The method ‘ShareText‘ will be defined in the platform-specific project.

Add the ‘FreshMVVM’ NuGet package to the project. In the constructor method of App.Xaml.cs, register and resolve the dependency service—IShareInfo—as shown:

FreshIOC.Container.Register(DependencyService.Get
   <IShareInfo>());
var shareService = FreshIOC.Container.Resolve<IShareInfo>();

This dependency service will be injected in the <xaml>.cs page as a parameter in the constructor. In this example, a page named ‘NotificationAppPage.xaml’ is already created and the page is set as a main page in App.xaml.cs:

MainPage = new NotificationAppPage(shareService);

In NotificationAppPage.xaml.cs, the constructor is defined as follows:

IShareInfo _shareInfo;
public NotificationAppPage(IShareInfo shareInfo)
{
   InitializeComponent();
   _shareInfo = shareInfo;
}

In the XAML project, add a button. In the button click event handler, call the IShareInfo’s ShareText method:

_shareInfo.ShareText("test data");

This completes the required changes in the forms app.

Android Changes

In the Android project, add a new class file named ‘ShareInfo.cs’. This will be a dependency implementation for the service ‘IShareInfo.cs’ created in the Xamarin Forms app. Decorate the namespace with the following value to define it as an implementation for the dependency service.

[assembly: Xamarin.Forms.Dependency(typeof(ShareInfo))]
namespace NotificationApp.Droid
{
   public class ShareInfo: IShareInfo
   { ....

The definition of the ShareText method is shown next:

 1. public Task ShareText(string message)
 2. {
 3.    var intent = new Intent(Intent.ActionSend)
 4.    intent.PutExtra(Intent.ExtraText, "Sample text ");
 5.    intent.SetType("*/*");//("text/plain");

 6.     Intent receiver = new Intent(Forms.Context,
           typeof(ShareReceiver));

 7.     PendingIntent pendingIntent =
           PendingIntent.GetBroadcast(Forms.Context,
           0, receiver, PendingIntentFlags.UpdateCurrent);
 8.     var chooserIntent =
           Intent.CreateChooser(intent,"Sample App",

 9.    var activity = (MainActivity)Forms.Context;
10.    activity.StartActivity(chooserIntent);
       return null;
11. }


12. BroadcastReceiver(Enabled = true)]
13. [IntentFilter(new[] { "ShareReceiver" })]
14. public class ShareReceiver : BroadcastReceiver
    {
15.    public override async void OnReceive(Context context,
          Intent intent)
       {
          // TODO implement
       }
    }

In the ShareText method, we first create an intent of type ‘Action.Send’ (Line 3). Add some text message to share and set the type of content to be shared. It will have a value such as “text/plain.” For this example, it’s been set as “*/*”. In Line 6, we define an intent for type BroadcastReceiver, named ‘ShareReceiver‘. This receiver is passed as a parameter when creating a chooser (Line 8) named ‘chooserIntent’ and then start the activity.

This opens up the window to select the different share options and, as soon as a person selects one of the target apps to share, the ShareReceiver’s OnReceive method gets a callback. Here, we can perform the required action.

iOS Changes

In the iOS project, we start by adding a class file named ‘ShareInfo.cs.’ It will be the implementation for the ‘IShareInfo’ service created in the forms project. As in Android, we decorate the namespace with this:

[assembly: Xamarin.Forms.Dependency(typeof(ShareInfo))]
namespace NotificationApp.iOS
{
   public class ShareInfo: IShareInfo
   ....

The following method, ‘ShareTextData,’ displays the different share apps available for sharing:

 1. public async Task ShareTextData(string message)
    {
 2.    var messages = new[] { (NSString) message }
 3.    var shareController = new
          UIActivityViewController(messages, null);

       // Event handler
 4.    shareController.CompletionWithItemsHandler +=
          (activityType, completed, returnedItems, error) =>
       {
          if (completed)
          {
             //
          }
       } ;
       // Show activity controller
 5.    var visibleController = GetVisibleViewController();
 6.    if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
       {
 7.       if (shareController.PopoverPresentationController
             != null)
          {
 8.          shareController.PopoverPresentationController
                .SourceView = visibleController.View;
          }
       }
 9.    await visibleController.PresentViewControllerAsync
          (shareController, true);
    }
10. UIViewController GetVisibleViewController(UIViewController
       controller = null)
    {
11.    controller = controller ??
       UIApplication.SharedApplication.KeyWindow
          .RootViewController;
    }

Line 2 converts the .NET string messages to NSString objects. Line 4 implements the handler method that is called when the user selects a target app to share the text message. Line 5 gets the view controller, and Line 9 displays the share app options. The GetVisibleViewController method defined in Line 10 gets the current view controller to display the ‘Share’ intent.

Summary

In this article, we saw how to trace the share application selected by the user. We also saw the implementation of CompletionWithItemsHandler in iOS and passing BroadcastReceiver as a parameter in CreateChooser method in Android; this helps tracing the target application selected.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories