Android Basic Training Course: Launching Activities And sub-Activities

    In Android development, switch to other screen often is changing Activity (another case is changing  Fragment ). With Intent, you can easily to go to other Activity from current one, and they are peer-to-peer in back stack. Another problem is sub-Activity - when it stop running, it will response a result to parent-Activity. This tutorial will show you how to create a sub-Activity from a calling-Activity, and process the results produced by the sub-Activity, if you want to do so. Also, the various ways of launching a sub-Activity are covered, along with the Android Activity  history stack. A subclass of Activity is also provided that makes it trivial to launch sub-Activities and respond to results from them.

Launching another Activity

    You can start another activity within the same application by calling startActivity(), passing it an Intent that describes the activity “class name” you want to start. Of course, never forget to declaring your Activities in AndroidManifest. This process is done with this simple code:
                Intent intent = new Intent(MainActivity.this, OtherActivity.class);
                startActivity(intent);

Put data to destination Activity

    Only switch between Activities is very simple, the most important problem is sending data through them. With Intent, we can easily to put data from the source Activity to the destination one by invoke  putExtras():
                Intent intent = new Intent(MainActivity.this, OtherActivity.class);
                intent.putExtra("TEXT", "this is a String from MainActivity");
                startActivity(intent);
    As you see, the data will be pass in (key, value) type. Through this Intent official doc page, you can find out datatypes which Intent can transport.
    In the destination Activity, you can receive this data that available in Intent by calling  getIntent():
        Intent intent = this.getIntent();
        String receivedString = intent.getStringExtra("TEXT");
    Note: the key must be same with declaration in the source Activity and you must use the correct method of receiving data (in this example is  getStringExtra()).

Activities Back (history) stack

    Please note that Android maintains a history stack of all the Activities that have been spawned in an application’s Linux process. By this way, when you get to the destination Activity and press Back button, your app will redirect you back to the source Activity. If you don't like this feature, please invoke finish() after call  startActivity(intent), your source Activity will be destroyed and you can't go back after switching. It's useful when developing Login - Home screens.

Launching Sub-Activity

   Sometimes you need to run some Activities, do some operation there and return some value to parent Activity. For this situation, Android has possibility to run Activity for result - called run sub-Activity. The method to invoke this process:
startActivityForResult(intent, requestCode);
   To receiving data from the sub-Activity, your parent-Activity must overrides onActivityResult(int requestCode, int resultCode, Intent data). In the sub-Activity, before finish, sending data to the parent-Activity through call:
setResult(resultCode, intent);
finish();
    The special thing here is you can call system app Activity (Camera, Contacts,...) or an Activity  from other apps which available in your device. Now, I will provide an example to take photos from device Camera and set it to  ImageView.
    First, creating a layout file for Activity:       This screen after running:

    In programmatically code, create an instance of ACTION_IMAGE_CAPTURE Intent and invoke it when click a  Button :
        btnGetPicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(takePicture, REQUEST_CAMERA_CODE);
            }
        });
    We will receive the  Bitmap  after take a photo with camera and set it to  ImageView :
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CAMERA_CODE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            imageView.setImageBitmap(imageBitmap);
        } else {
            Toast.makeText(this, "You have not take any picture", Toast.LENGTH_SHORT).show();
        }
    }
    Full code of this Activity:
package info.devexchanges.photopicker;

import android.content.Intent;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private Button btnGetPicture;
    private Button btnGo;
    private ImageView imageView;
    private final static int REQUEST_CAMERA_CODE = 111;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = (ImageView) findViewById(R.id.image);
        btnGetPicture = (Button) findViewById(R.id.btn_get);
        btnGo = (Button) findViewById(R.id.btn_go_with_data);

        btnGetPicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(takePicture, REQUEST_CAMERA_CODE);
            }
        });

        btnGo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, OtherActivity.class);
                intent.putExtra("TEXT", "this is a String from MainActivity");
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CAMERA_CODE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            imageView.setImageBitmap(imageBitmap);
        } else {
            Toast.makeText(this, "You have not take any picture", Toast.LENGTH_SHORT).show();
        }
    }
}
    Output screen (after taking a photo):

Conclusions

    I have completed to present the way to starting Activity and sub-Activity through Intent. If you need more example about start sub-Activity on other app in your device, please see "How to use Scan Barcode" post. Moreover, you can find out yourself how to write your own sub-Activity after follows my guide above. Finally, you can get full code for this project on @Github by click button below.




Share


Previous post
« Prev Post
Next post
Next Post »