Pages

Wednesday, June 22, 2011

Simple communication between two different applications

Recently, I faced a problem where I needed two different applications to communicate a simple message between each other. I searched around and found many questions regarding this problem. However, there were a lot of vague answers as well.

I figured I would write this in case someone else faced a similar issue and needed a starting point to work from.

Here was the issue I faced:

  1. The user opens TestAppOne and there is a check to see if TestAppTwo exists.
  2. For this example we will say that TRUE is returned.
  3. Since TestAppTwo exists we open it using startActivityForResult(Intent, int).
  4. When the user is done with TestAppTwo they click a button which sends them back to TestAppOne with the resultCode
  5. Call finish() on TestAppTwo.

 


class TestAppOne extends Activity { 
 //... 
 
 private final void startOtherApp() { 
  //... 
  
  // Here we pass "1" to TestAppTwo 
  this.startActivityForResult(intent, 1); 
  
  //... 
 } 
 
 @Override protected void onActivityResult(int pRequestCode, int pResultCode, Intent pData) { 
  super.onActivityResult(pRequestCode, pResultCode, pData); 
  
  // Check the result code that was sent from the calling activity 
  if( pResultCode == 1 ) { 
   // The result was successfully sent and received 
  } else { 
   // There is something wrong 
  } 
 } 
} 

class TestAppTwo extends Activity { 
 //... 
 
 private void someMethod() { 
  //... 
  
  // Set the result here to be passed back to TestAppOne 
  this.setResult(1); 
  this.finish();
 } 
} 

 

Credits go to:
Android Developer Reference
Let's Share Some Thoughts
Android Forums

No comments:

Post a Comment