Skip to content

Instantly share code, notes, and snippets.

@OrenBochman
Last active March 1, 2023 09:12
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OrenBochman/db53c59b0d72e6f68bdf79f0d0f6c95a to your computer and use it in GitHub Desktop.
Save OrenBochman/db53c59b0d72e6f68bdf79f0d0f6c95a to your computer and use it in GitHub Desktop.
All about Intents in Android

Intents

Explicit v.s. Implicit

A quick demo of implicit and explicit intents.

Requesting data from another activity

  1. Use startActivityForResult() to start the second Activity
  2. To return data from the second Activity:
    • Create a new Intent
    • Put the response data in the Intent using putExtra()
    • Set the result to Activity.RESULT_OK or RESULT_CANCELED, if the user cancelled out
    • Set result can has a version without an intent, just a code: setResult(RESULT_COLOR_RED);
    • call finish() to close the Activity
  3. Implement onActivityResult() in first Activity

Delegating onActivityResult() to an Adapter/ViewModel etc.

Delegation to adaptor + preserving the position

From a Service

From a ViewModel

Allowing other apps to start your activity

Implement an Intetent filter

//Implicit
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);
sendIntent.setType("text/plain")
startactivity(sendIntent);
//Explicit: Explicit intent when you call you're on application activity from one activity to another
// e.g. first activity to second activity:
Intent intent = new Intent(first.this, second.class);
startactivity(intent);
Intent intent = new Intent(first.this, second.class);
//just navigate
startActivity(intent);
//to start activity and get response back
startActivityForResult(intent,code);
//start a service
startService(intent);
//start service in background
startForeGroundService(intent);
intent.setData(Uri.parse(""http://www.google.com""));
intent.setData(Uri.fromFile(new File(""/sdcard/sample.jpg"")));
Bundle extras = new Bundle();
extras.putString(EXTRA_MESSAGE, ""this is my message"");
extras.putInt(EXTRA_POSITION_X, 100);
extras.putInt(EXTRA_POSITION_Y, 500);
putExtras(bundle);
Intent intent = getIntent();
intent.getData();
int res = intent.getIntExtra (String name, int defaultValue)
Bundle bundle = intent.getExtras();
//Started by using startActivityForResult(messageIntent, TEXT_REQUEST);
//get the TEXT_REQUEST code, to return it so that the requesting activity will know what to expect.
int positionX = intent.getIntExtra(MainActivity.EXTRA_POSITION_X);
//avoid confusing sent and returned data, by using a new Intent.
Intent replyIntent = new Intent();
//used an established this is some shared key
public final static String EXTRA_RETURN_MESSAGE = "com.example.mysampleapp.RETURN_MESSAGE";
//the reutrned data
returnIntent.putExtra(EXTRA_RETURN_MESSAGE, mMessage);
//set the response
setResult(RESULT_OK,replyIntent);
//close the activity
finish();
//Started by using startActivityForResult(messageIntent, TEXT_REQUEST);
//avoid confusing sent and returned data, by using a new Intent.
Intent replyIntent = new Intent();
//user canceled
setResult(RESULT_CANCELED,replyIntent);
//close the activity
finish();
"public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TEXT_REQUEST) {
if (resultCode == RESULT_OK) {
String reply =
data.getStringExtra(SecondActivity.EXTRA_RETURN_MESSAGE);
// process data
}
}
}"
//in the activity/fragment
//here we override
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
mAdapter.onActivityResult(requestCode, resultCode, data); //delegate handling to madapter
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
//in the Adapter (note: this is not an overide!)
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("MyAdapter", "onActivityResult");
}
//p.s. this means we are handling a response for a list/recycler item event (click/swipe)
holder.EditRemnant1.Click += delegate (object sender, System.EventArgs args)
{
if (remnantModel != null)
{
Intent intent = new Intent(context, typeof(EditRemnant));
intent.PutExtra("OpenPopType", 2);
intent.PutExtra("Position", position ); //well need this to be passed from incoming to result intent in the invoked activity
context.StartActivityForResult(intent, 1);
}
};
public class SomeService extends Service {
/**
* Code for a successful result, mirrors {@link Activity.RESULT_OK}.
*/
public static final int RESULT_OK = -1;
/**
* Key used in the intent extras for the result receiver.
*/
public static final String KEY_RECEIVER = "KEY_RECEIVER";
/**
* Key used in the result bundle for the message.
*/
public static final String KEY_MESSAGE = "KEY_MESSAGE";
// ...
/**
* Used by an activity to send a result back to our service.
*/
class MessageReceiver extends ResultReceiver {
public MessageReceiver() {
// Pass in a handler or null if you don't care about the thread
// on which your code is executed.
super(null);
}
/**
* Called when there's a result available.
*/
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
// Define and handle your own result codes
if (resultCode != RESULT_OK) {
return;
}
// Let's assume that a successful result includes a message.
String message = resultData.getString(KEY_MESSAGE);
// Now you can do something with it.
}
}
}
/**
* Starts an activity for retrieving a message.
*/
private void startMessageActivity() {
Intent intent = new Intent(this, MessageActivity.class);
// Pack the parcelable receiver into the intent extras so the
// activity can access it.
intent.putExtra(KEY_RECEIVER, new MessageReceiver());
startActivity(intent);
}
public class MessageActivity extends Activity {
// ...
@Override
public void finish() {
// Unpack the receiver.
ResultReceiver receiver =
getIntent().getParcelableExtra(SomeService.KEY_RECEIVER);
Bundle resultData = new Bundle();
resultData.putString(SomeService.KEY_MESSAGE, "Hello world!");
receiver.send(SomeService.RESULT_OK, resultData);
super.finish();
}
}
<activity android:name="ShareActivity">
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
<data android:mimeType="image/*"/>
</intent-filter>
</activity>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_item_share"
android:showAsAction="ifRoom"
android:title="Share"
android:actionProviderClass="android.widget.ShareActionProvider" />
...
</menu>
private ShareActionProvider mShareActionProvider;
...
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate menu resource file.
getMenuInflater().inflate(R.menu.share_menu, menu);
// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.menu_item_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
// Return true to display menu
return true;
}
// Call to update the share intent
private void setShareIntent(Intent shareIntent) {
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareIntent);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment