Skip to content

App Integration

Nicholas LaBelle edited this page Oct 7, 2019 · 26 revisions

App Integration

Intent-Filters

  • Implicit Intents are what one needs to use in order to send photos in between apps using an intent receiver.
  • Intent filters determine what data you can send and receive from other applications within android. Apps such as facebook and Google Photos contain data such as text and images. Intents that are Implicit allow any app which can send data of the type listed in the manifest to send it. Here is an Example Manifest using intent filters implicitly:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="<YourNamespace>.sharingintents">
    
    <uses-permission android:name="android.permission.INTERNET" ></uses-permission>

    <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=".PickAnImage"
            android:label="@string/displayPick" />
        <activity
            android:name=".MyLittleBrowser"
            android:label="@string/little_browser_name" 
       android:theme="@style/BrowserTheme">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:scheme="http" />
            </intent-filter>
        </activity>
    </application>

</manifest>

How to receive data via intents:Receiving

  • Receiving data is handled via a Chooser Target Service. Once the Chooser Target Service hands the data to your app. You as the apps programmer are responsible for providing storage and variables to hold the data. The Chooser Target Service launches an app and runs it for the datatypes listed in the manifest. The Chooser Target Service allows for other apps to access your app to send it data. The Share Action Provider handles receiving by giving a list of compatible application that can be opened to get the wanted data here is example button that asks for barcode data or Strings or Images:
// Process button clicks
    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            // For button 1, share string data
            case R.id.button01:
                isBarcodeScan = false;
                // Launch the text share intent and associate it with the ShareActionProvider
                Intent share = shareText(inputText.getText().toString());
                Log.i(TAG, "intent=" + share.toString());
                shareActionProvider.setShareIntent(share);

                // Force the soft keyboard closed so following Toast instructions easy to see
                InputMethodManager inputManager = (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.hideSoftInputFromWindow(v.getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);

                // Display Toast with instructions
                Toast.makeText(this, getString(R.string.toaster),
                        Toast.LENGTH_LONG).show();
                break;

            // For button 2, share barcode data
            case R.id.button02:
                isBarcodeScan = true;
                shareActionProvider.setShareIntent(shareBarcode());
                break;

            // For button 3, pick an image from gallery or other sources and share
            case R.id.button03:
                Intent j = new Intent(this, PickAnImage.class);
                startActivity(j);
                break;

            // For browserButton, test the shared custom browser MyLittleBrowser.  If
            // no preferred browser has been set, this should display a list of
            // apps registered to display webpages, including MyLittleBrowser.  Choosing
            // MyLittleBrowser should display the url given below in MyLittleBrowser.

            case R.id.browserButton:
                String url = "http://developers.google.com";
                Intent k = new Intent(Intent.ACTION_VIEW);
                k.setData(Uri.parse(url));
                startActivity(k);
                break;
        }

How to send data via intents:Sending

  • In order to send data one need to have an intent set to send data in the manifest and use Chooser Target and Share Action Provider to send the data to any app that can receive the data and Share Action Provider by default will produce a list of all compatible applications. This is an example of picking an image and sending via intents:
package <YourNamespace>.sharingintents;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.support.v7.widget.ShareActionProvider;

public class PickAnImage extends AppCompatActivity implements OnClickListener {

    private static final String TAG = "SHARE";
    private static final int REQUEST_CODE = 1;
    private Bitmap bitmap;
    private ImageView imageView;
    private Button shareButton;
    private Uri uri;
    private ShareActionProvider shareActionProvider;

    /**
     * Called when the activity is first created.
     */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pickanimage);

        // Create top toolbar.  This assumes a NoActionBar style in styles.xml,
        // since it will be replaced by the following toolbar.

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar2);
        // Remove default toolbar title and replace with an icon
        if (toolbar != null) {
            toolbar.setNavigationIcon(R.mipmap.ic_launcher);
        }

        // Set background color.  Handle method getColor deprecated as of API 23
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            toolbar.setTitleTextColor(getResources().getColor(R.color.barTextColor, null));
        } else {
            toolbar.setTitleTextColor(getResources().getColor(R.color.barTextColor));
        }
        // Note: getColor(color) deprecated as of API 23
        //toolbar.setTitleTextColor(getResources().getColor(R.color.barTextColor));
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        imageView = (ImageView) findViewById(R.id.theImage);
        shareButton = (Button) findViewById(R.id.button04);
        shareButton.setOnClickListener(this);
        chooseImage();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        // Get the share menu item
        MenuItem menuItem = menu.findItem(R.id.menu_share);
        // Get the provider
        shareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);

        return true;
    }

    // This will allow you to choose an image from the device by selecting it in a file chooser
    // such as Gallery.  It will be displayed in an ImageView once selected.

    public void chooseImage() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        startActivityForResult(intent, REQUEST_CODE);

        /** Alternative: Preceding line can be replaced by the following commented-out line,
         * which may give the user some say in the form of the chooser for some devices.  See the
         * API documentation of the Intent static string constant ACTION_GET_CONTENT for
         * discussion of the difference.
         */

        //startActivityForResult (Intent.createChooser(intent, "Message"), REQUEST_CODE);
    }

    // Executed when the activity started from chooseImage() with startActivityForResults
    // returns a result.  Uses a content resolver to retrieve an image from the device,
    // assign it to a bitmap, and display the bitmap. The Uri of the image file that is displayed
    // in the bitmap is saved in the variable uri to be passed to the method shareImage(uri),
    // which shares the bitmap.

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        InputStream inStream = null;
        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
            try {
                uri = intent.getData();
                inStream = getContentResolver().openInputStream(uri);
                bitmap = BitmapFactory.decodeStream(inStream);
                imageView.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                if (inStream != null)
                    try {
                        inStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
            }
        super.onActivityResult(requestCode, resultCode, intent);
    }

    // Share the bitmap that was selected from the local filesystem using the chooseImage()
    // method by using an implicit intent.  When launched with
    // shareActionProvider.setShareIntent(shareImage(uri)) in the onClick method below,
    // this will populate the top Toolbar with an adaptive sharing menu (most used apps
    // will float to the top and the current default will appear as a separate icon), and
    // will open the sharing menu (if the startActivity line below is not commented out).

    public Intent shareImage(Uri uri) {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("image/*");
        // Clear activity stack if reset
        shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
        //shareIntent.setAction(Intent.ACTION_SEND);
        Log.i(TAG, "shareImage:  Uri=" + uri);
        shareIntent.putExtra(Intent.EXTRA_STREAM, uri);

        // Comment out following line to populate top ActionBar with adaptive sharing menu
        // but not open the sharing menu until selected by user. With this line present
        // the menu will be added and will be opened by default, which is likely the most
        // user-friendly workflow.

        startActivity(Intent.createChooser(shareIntent, getString(R.string.shareImage)));

        return shareIntent;
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.button04:
                Log.i(TAG, "uri=" + uri.toString());
                Intent temp = shareImage(uri);
                Log.i(TAG, "intent=" + temp.toString());

                shareActionProvider.setShareIntent(shareImage(uri));
                break;
        }
    }
}

Share Action Provider

Applications that are compatible

  • Google Drive
  • Google Photos
  • Files
  • Facebook
  • Twitter
  • Gmail
  • Messages
  • Facebook Messenger
  • Any application with the correct Receiving or Sending Intent.

Resources for Intent implementation

  1. Sharing Intents provides example code
  2. Google Intent Documentation