Inter-Process Communication In Android

Introduction

 
We already know how to save files and read files in Android. But here I am going to tell you about how a file created by one application is shared with another application. The file created by the first application is saved in the data folder, as you all know that the data storage is private to the application.
 
The task I am going to tell you is I have two application, the first application has an edittext, button and a text view on clicking on the button the application will save the text which is present in the edittext to a file in the data storage and show the status in the text view that is whether the file is created or not.
 
The second application has also three controls they are two text view and one button. On clicking in the button the contents from the file which are created by the first application are loaded into the first text view and the status will be shown in the next text view.
 
Create the first applications its name is ShareAppOne
 
Here I am using an Android studio for creating the two applications. Create a blank activity and its layout. Suppose the layout file is activity_main.xml. which will contain one EditText one Button and a TextView. Here is the XML file.
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
  2.      xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"    
  3.      android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"    
  4.      android:paddingRight="@dimen/activity_horizontal_margin"    
  5.      android:paddingTop="@dimen/activity_vertical_margin"    
  6.      android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">    
  7.      
  8.      <EditText    
  9.          android:layout_width="match_parent"    
  10.          android:layout_height="wrap_content"    
  11.          android:id="@+id/editText"    
  12.          android:layout_alignParentTop="true"    
  13.          android:layout_centerHorizontal="true"    
  14.          android:layout_marginTop="38dp" />    
  15.      
  16.      <Button    
  17.          android:layout_width="wrap_content"    
  18.          android:layout_height="wrap_content"    
  19.          android:text="Save to File"    
  20.          android:id="@+id/button"    
  21.          android:layout_below="@+id/editText"    
  22.          android:layout_centerHorizontal="true"    
  23.          android:layout_marginTop="54dp" />    
  24.      
  25.      <TextView    
  26.          android:layout_width="wrap_content"    
  27.          android:layout_height="wrap_content"    
  28.          android:text="Status"    
  29.          android:id="@+id/statusView"    
  30.          android:layout_centerVertical="true"    
  31.          android:layout_centerHorizontal="true" />    
  32.  </RelativeLayout>   
    Now declare two private variables in the MainActivity,
    1. private EditText editText = null;    
    2.  private TextView statusText = null;   
      And in the onCreate() please initialize these variables and the buttons.
      1. editText = (EditText) findViewById(R.id.editText);    
      2. statusText = (TextView) findViewById(R.id.statusView);    
      3. Button saveFile = (Button) findViewById(R.id.button); 
      Now we need to do the main things like we need to do save the contents to file in the data folder on clicking on the button. Please see the code below.
      1. private void saveFile(){    
      2.      File file = null;    
      3.      FileOutputStream fileOutputStream = null;    
      4.      
      5.      file = getFilesDir();    
      6.      try {    
      7.          fileOutputStream = openFileOutput("app1.txt", MODE_PRIVATE);    
      8.          fileOutputStream.write(editText.getText().toString().getBytes());    
      9.          statusText.setTextColor(Color.GREEN);    
      10.          statusText.setText("File write "+file.getAbsolutePath());    
      11.          fileOutputStream.close();    
      12.      } catch (FileNotFoundException e) {    
      13.          statusText.setTextColor(Color.RED);    
      14.          statusText.setText("Error " + e.getMessage());    
      15.      } catch (IOException e) {    
      16.          statusText.setTextColor(Color.RED);    
      17.          statusText.setText("Error " + e.getMessage());    
      18.      }    
      19.  }   
        The above method will save the file in the data folder of this application.
         
        Now the main thing here is each applications has its own application id and the process id which will be assigned by the Android operating system while the time of installing the application. The application id will be unique. So we need to set a shared application id for this two application we are going to create. That we need to set in the Manifest file. Like the following,
        1. <manifest xmlns:android="http://schemas.android.com/apk/res/android"    
        2.      android:sharedUserId="com.negociosit.shareApp"    
        3.      package="sample.negociosit.com.shareappone" > 
        Create the second application named ShareAppTwo
         
        This application also contains two text views and a button. The first text view will show the contents of the file on clicking in the button and the second textview will display the status.
         
        Please see the xml file for the layout,
        1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
        2.      xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"    
        3.      android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"    
        4.      android:paddingRight="@dimen/activity_horizontal_margin"    
        5.      android:paddingTop="@dimen/activity_vertical_margin"    
        6.      android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">    
        7.      
        8.      <TextView android:text="@string/hello_world"    
        9.          android:layout_width="wrap_content"    
        10.          android:layout_height="wrap_content"    
        11.          android:id="@+id/textView"    
        12.          android:layout_alignParentTop="true"    
        13.          android:layout_centerHorizontal="true"    
        14.          android:layout_marginTop="63dp" />    
        15.      
        16.      <Button    
        17.          android:layout_width="wrap_content"    
        18.          android:layout_height="wrap_content"    
        19.          android:text="Load Text"    
        20.          android:id="@+id/loadButton"    
        21.          android:layout_below="@+id/textView"    
        22.          android:layout_centerHorizontal="true"    
        23.          android:layout_marginTop="50dp" />    
        24.      
        25.      <TextView    
        26.          android:layout_width="wrap_content"    
        27.          android:layout_height="wrap_content"    
        28.          android:textAppearance="?android:attr/textAppearanceLarge"    
        29.          android:text="Status"    
        30.          android:id="@+id/statusText"    
        31.          android:layout_centerVertical="true"    
        32.          android:layout_centerHorizontal="true" />    
        33.      
        34.  </RelativeLayout>   
          Now initialize these controls in the onCreate() of your MainActivity,
          1. textView = (TextView) findViewById(R.id.textView);      
          2. statusTextView = (TextView) findViewById(R.id.statusText);      
          3. Button loadButton = (Button) findViewById(R.id.loadButton);   
            On Clicking on the loadButton we need to show the file contents for that first we need to check whether the first application exists or not by using the following code.
            1. PackageManager packageManager = getPackageManager();    
            2.  try {    
            3.      ApplicationInfo applicationInfo = packageManager.getApplicationInfo("sample.negociosit.com.shareappone",PackageManager.GET_META_DATA);    
            4.      
            5.      readFile(applicationInfo.dataDir +"/files/app1.txt");    
            6.  } catch (PackageManager.NameNotFoundException e) {    
            7.      e.printStackTrace();    
            8.  }   
              In the Application info object we need to pass the package name of the application which we want to get info. If that package is not existing then it will get an exception like NameNotFoundException. Here we need to put the ShareAppOne package name because we need to read a file from that application’s private storage. If that package exists then we need to read the contents of the file using the following code.
              1. private void readFile(String filePath){    
              2.      FileInputStream fileInputStream = null;    
              3.      try {    
              4.          fileInputStream = new FileInputStream(new File(filePath));    
              5.          int read = -1;    
              6.          StringBuffer stringBuffer = new StringBuffer();    
              7.          while((read = fileInputStream.read())!=-1){    
              8.              stringBuffer.append((char)read);    
              9.          }    
              10.          textView.setText(stringBuffer.toString());    
              11.          statusTextView.setTextColor(Color.GREEN);    
              12.          statusTextView.setText("File loaded successfully");    
              13.      } catch (FileNotFoundException e) {    
              14.          statusTextView.setTextColor(Color.RED);    
              15.          statusTextView.setText("Error " + e.getMessage());    
              16.      } catch (IOException e) {    
              17.          statusTextView.setTextColor(Color.RED);    
              18.          statusTextView.setText("Error "+e.getMessage());    
              19.      }    
              20.  }   
                This will display the file contents in the TextView if no error occurs in reading the file. Please see the screenshots also for the two applications.
                 
                  
                 
                Happy coding! Cheers!
                 
                Read more articles on Android