Intents

Each activity is started or activated with an Intent, which is a message object that makes a request to the Android runtime to start an activity or other app component in your app or in some other app.

Intent types

  • Explicit intent: You use explicit intents to start components in your own app (for example, to move between screens in the UI).

  • Implicit intent: You do not specify a specific activity or other component to receive the intent. Instead, you declare a general action to perform, and the Android system matches your request to an activity or other component that can handle the requested action.

Implicit intent

Intent intent = new Intent(CurrenActivity.this, TargetActivity.class);
startActivity(intent);

passing extra data to next activity

Intent intent = new Intent(CurrenActivity.this, TargetActivity.class);
intent.putExtra("key", "this is my message");
startActivity(intent);

Getting data on target activity

String message = getIntent.getStringExtra("key");

An example for implicit intent(take picture using camera)

Implement on onCreateView method

Intent pictureIntent = new Intent(
        MediaStore.ACTION_IMAGE_CAPTURE
);
    startActivityForResult(pictureIntent,
            REQUEST_CAPTURE_IMAGE);

override onActivityResult method

 @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
        if (requestCode == REQUEST_CAPTURE_IMAGE &&
                resultCode == RESULT_OK) {
            if (data != null && data.getExtras() != null) {
                imageView.setVisibility(View.VISIBLE);
                Toast.makeText(this, "got image", Toast.LENGTH_SHORT).show();
                Bitmap imageBitmap = (Bitmap) data.getExtras().get("data");
                imageView.setImageBitmap(imageBitmap);
            }
        }
    }

Last updated