In this lesson:

- reading action from Intent

Translated by Taras Leskiv (http://android-by-example.blogspot.com/)

In the previous lesson we have created an obvious example that illustrates how action, Intent and Intent Filter are bound together. In this lesson we will continue illustrating the topic. I have both good and good news for you )

News item one. Intent Filter can contain several actions. By doing so Activity notifies us that it can perform several actions. For example, not only viewing an image but also editing it. Activity can approach different Intents with different actions.

News item number two. Activity which has been invoked using Intent has access to this Intent and can read its attributes. That is, Activity can find out which action was used.

We will do the following: create an Activity and configure Intent Filter for action = ru.startandroid.intent.action.showtime and action = ru.startandroid.intent.action.showdate. By doing so we specify that Activity is capable of displaying both time and date. Later we will create an intent with action = ru.startandroid.intent.action.showtime or with action = ru.startandroid.intent.action.showdate. They will both invoke one Activity. And for Activity to know whether to display date or time, we will be reading action from Intent and define what to show for each action.

Okay, we will start implementing it and everything will be clear.

 

Let’s create a project:

Project name: P0271_GetIntentAction
Build Target: Android 2.3.3
Application name: GetIntentAction
Package name: ru.startandroid.develop.p0271getintentaction
Create Activity: MainActivity

 

Open main.xml and draw two buttons:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btnTime"
        android:text="Show time">
    </Button>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btnDate"
        android:text="Show date">
    </Button>
</LinearLayout>

Screen is the same as in the previous lesson

 

MainActivity.java code:

package ru.startandroid.develop.p0271getintentaction;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {
  
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button btnTime = (Button) findViewById(R.id.btnTime);
        Button btnDate = (Button) findViewById(R.id.btnDate);
        
        btnTime.setOnClickListener(this);
        btnDate.setOnClickListener(this);
    }

  @Override
  public void onClick(View v) {
    Intent intent;

    switch(v.getId()) {
    case R.id.btnTime:
      intent = new Intent("ru.startandroid.intent.action.showtime");
      startActivity(intent);
      break;
    case R.id.btnDate:
      intent = new Intent("ru.startandroid.intent.action.showdate");
      startActivity(intent);
      break;
    }
  }
}

Code is also completely the same as in the previous lesson. Define buttons, assign a listener - Activity and invoke an Intent on button click. Let’s now create an Activity that will catch both these Intents.

To begin with create a layout-file info.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tvInfo"
        android:text="TextView"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp"
        android:textSize="30sp">
    </TextView>
</LinearLayout>

We have only one TextView on the screen.

Create an Activity, name it just Info.

Info.java code:

package ru.startandroid.develop.p0271getintentaction;

import java.sql.Date;
import java.text.SimpleDateFormat;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class Info extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.info);
    
    // get the intent which launched this activity
    Intent intent = getIntent();
    // get action from it
    String action = intent.getAction();
    
    String format = "", textInfo = "";
    
    // fill variables dependning on the action
    if (action.equals("ru.startandroid.intent.action.showtime")) { 
      format = "HH:mm:ss";
      textInfo = "Time: ";
    }
    else if (action.equals("ru.startandroid.intent.action.showdate")) { 
      format = "dd.MM.yyyy";
      textInfo = "Date: ";
    }
    
    // depending on the format variable value 
    // get date of time for datetime variable
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    String datetime = sdf.format(new Date(System.currentTimeMillis()));
    
    TextView tvDate = (TextView) findViewById(R.id.tvInfo);
    tvDate.setText(textInfo + datetime);
  }
}

We receive Intent using getIntent() method, read action from it and depending on its value we display text on the screen.

 

Don’t forget to register new Activity in the manifest and create Intent Filter with two actions and a category. And specify a label - Date/time info.

Intent Filter of Info contains two actions. It means if the Intent with any of these actions comes - the Activity will be invoked.

 

Save everything and run the application.

 Press the Show time button. Most likely you will see the following:

The system gives us a choice. That is, Intent with action = ru.startandroid.intent.action.showtime found two Activities that fit. The one that is Date/time info is the one we have just created, everything is clear with it. The question is where does the second item with name IntentFilter comes from. Answer - this is ActivityTime from the previous lesson. It is named IntentFilter because we have not specified a label in the manifest for this Activity in the previous lesson and the system displays application name by default.

If the system haven’t displayed a choice dialog, that means that you didn’t create the application from previous lesson or you have created a new AVD, or there is a mistake in your code.

Choose Date/time info and we can see what we’ve just implemented. Activity recognized that Intent was with action = ru.startandroid.intent.action.showtime and shown time with Time: text

 

If to choose IntentFilter we will see Activity from the previous lesson:

 

Now let’s try pressing Show date: button: we see the following choice:

Снова

We can again see our Date/time info and two Activities from the previous lesson. They all contain action = ru.startandroid.intent.action.showdate in their Intent Filter and we have to make a choice. Choose Date/time info and you will see date with Date: text:

 

If you choose Date basic or Date expanded we will see what we were doing in the previous lesson:

simple date

 

and expanded

 

We have figured out that one Activity can be invoked using Intent with different actions. Activity can read action and perform the required operations.

 

We have also made sure that Intent looks for Activities in all applications in the system. In this case it found Activity from the application that we developed in the previous lesson.

 

In the next lesson:

- passing data using Intent


Присоединяйтесь к нам в Telegram:

- в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.

- в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Compose, Kotlin, RxJava, Dagger, Тестирование, Performance 

- ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня




Language