Intent and Intent Filters

Intent: Intent is a messaging object, it is a data structure containing a description of to-be-performed operation. Using intents we can send messages asynchronously to other component.

Intents are 2 types.

  1. Explicit Intent: In explicit intent we will specify the component name which we want to start. In our application we mostly use explicit intent because we know which component(Activity, Service or Broadcast Receiver).

Example:

Intent intent = new Intent(MainActivity.this, AboutTgActivity.class); 
                startActivity(intent);

      2. Implicit Intent: For implicit intent we just specify the action then the android framework will take care of launching the specified action component. If more than one component is found for specified action then it will prompt all available components then user can select any of one.

Example:

        Uri articleURL = Uri.parse(articleUrlString);
        Intent i = new Intent(Intent.ACTION_VIEW, articleURL);
        startActivity(i);

 

Intent Filters:

Using intent filter we can specify which actions can be performed in a specific component. Intent filters we normally specify in the manifest.xml.  In intent filter we can specify only one action and multiple categories which can handle the given action also we can specify the data type.

Advertisements

Adding Shortcut to App Icon

Adding shortcuts to app icon in the launcher feature is added in the Android Nougat 7.1.1.

It is good feature in android. By using this feature we can provide user to access directly to any screen in our app. We can add max 5 shortcuts for the app which includes both static and dynamic shortcuts.

App shortcuts on Nexus 6P

Image: Source from the developer.android.com

Reference:Shortcuts

Shortcuts are 2 types.

Static shortcuts :

Statics shortcuts we define the in xml/<name of file>.xml and this xml file should be refer from the manifest.xml file in launcher activity. Static shortcuts are can’t be removed dynamically. If we want to remove we have to update the app with removing this shortcuts.

Example:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.myapplication">
  <application ... >
    <activity android:name="Main">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
      <meta-data android:name="android.app.shortcuts"
                 android:resource="@xml/shortcuts" />
    </activity>
  </application>
</manifest>
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
  <shortcut
    android:shortcutId="compose"
    android:enabled="true"
    android:icon="@drawable/compose_icon"
    android:shortcutShortLabel="@string/compose_shortcut_short_label1"
    android:shortcutLongLabel="@string/compose_shortcut_long_label1"
    android:shortcutDisabledMessage="@string/compose_disabled_message1">
    <intent
      android:action="android.intent.action.VIEW"
      android:targetPackage="com.example.myapplication"
      android:targetClass="com.example.myapplication.ComposeActivity" />
    <!-- If your shortcut is associated with multiple intents, include them
         here. The last intent in the list determines what the user sees when
         they launch this shortcut. -->
    <categories android:name="android.shortcut.conversation" />
  </shortcut>
  <!-- Specify more shortcuts here. -->
</shortcuts>

Dynamic shortcuts:

Dynamic shortcuts we can add and remove dynamically. Which is more useful when we want to predict more user operations and give those in the shortcut. Like for contacts app we can find which contact user calling more then we can add that contact in the shortcut.

Dynamic shortcuts we can add and remove dynamically.

Dynamic shortcuts we can create using ShortcutManager API. Which provides set of methods for add, set, remove and other features.

Example:

ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);

ShortcutInfo shortcut = new ShortcutInfo.Builder(this, "id1")
    .setShortLabel("Web site")
    .setLongLabel("Open the web site")
    .setIcon(Icon.createWithResource(context, R.drawable.icon_website))
    .setIntent(new Intent(Intent.ACTION_VIEW,
                   Uri.parse("https://www.mysite.example.com/")))
    .build();

shortcutManager.setDynamicShortcuts(Arrays.asList(shortcut));

 

Handle Button Click Events

Event: When user clicks on the button event will be triggered and it will be processed by the OS. Then listener will receive the event and perform the specified on action on it.

Different ways to handle button clicks:

-> Handle from xml

In layout xml file while defining the button add onclick attribute.

Example:

<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”ListActivity”
android:id=”@+id/button4″
       android:onClick=”proceedToNext”
android:layout_below=”@+id/button3″
android:layout_alignStart=”@+id/button” />

Then write the method in activity for handle the click event.

public void proceedToNext(View v) {
if (v.getId() == R.id.button) {
Intent intent = new Intent(this, Communicate.class);
startActivity(intent);
}
if (v.getId() == R.id.button2) {
Intent intent = new Intent(this, TextHandle.class);
startActivity(intent);
}
if(v.getId() == R.id.button3){
Intent intent = new Intent(this, ListExample.class);
startActivity(intent);
}
if(v.getId() == R.id.button4){
Intent intent = new Intent(this, ListActivityEx.class);
startActivity(intent);
}
}

Here proceedToNext must take a View argument.
If we define multiple buttons for same method then we can find the which button is
clicked by comparing the button and argument which passed to proceedToNext method.
like shown above.

-> Using OnClickListener and override onClick method:

Implement the OnClickListener interface in activity and override the method onClick method. After button object is created then call setOnClickListner method.

Example:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button button= (Button) findViewById(R.id.button4);
    button.setOnClickListener(this);
}
@Override
public void onClick(View view) {
    Intent intent = new Intent(this, ListActivityEx.class);
    startActivity(intent);
}

-> Using anonymous class:

At the same time create a object for OnClickLister and implement the onClick method.

Example:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent = new Intent(MainActivity.this, ListActivityEx.class);
        startActivity(intent);
    }
});

Activity and Its Life Cycle

An Activity is an application component that provides a screen with which users can interact in order to do something.

Activity Life Cycle Methods:

Life cycle methods will be called by the android OS. So in each life cycle method we must call super class method.

enter image description here

onCreate: This method calls by the android os whenever the activity is launched.

In this method we write code for create view hierarchy. It draw the UI on the screen.

For draw the UI on the screen we need to call a method of View class.

setContentView(R.layout.activity_main);

Here activity_main is layout xml file in which we define the UI elements.
For every Resource which we keep in the res folder a hex reference will be created
in R.java class. Using which we can access the resources in the source code.
i.e R.layout.

onStart: Whenever activity is launched Android OS will call 3 callback methods
in a sequential those are onCreate and onStart and onResume. In onStart we need
to write code which needs to be executed after immediately UI is loaded. like
start service or register broadcast receiver etc.

onResume: Whenever this callback methods is calling android OS that means user able
see the UI and can perform the operations.

onPause: This method is called user can able to see the UI partially and can’t perform any operation.  When user receive a dialog this method is called. In this method we need to write code for save user data. i.e write important data in the database. This operation should be light weight.

onStop: This method is called when the user leave the activity. When user move from 1 activity to other activity this method will be called in the last. So in this method we need to write code related to release the resource like close database connection and close http connections. stop services which trigger by this activity if it is not required to run and also we can unregister the broadcast receiver.

onDestroy: This method is called by Android OS when the activity is no longer exist.
This method is called when the user click back button.

onRestart: When user moves from one activity to another activity and press back
button to come last activity or whenever user press the home screen and relaunched
activity from the menu.

Other call back methods which used for the save the state of an activity.

enter image description here

  1. onSavedInstanceState: This is called after onPause callback method called. Here we can write the code for save the state of variables which need to be restored when user comes back to the activity. We need to use this method for the values which are temporary(When application destroys values will be destroyed).
  2. onRestoreInstanceState: This is called after onCreate call back method, In this method this method receive the saveInstance state. In this method we can restore the values which are saved in the onSavedInstanceState callback method.

ScreenOrientation

For keep the device in fixed orientation

-> Using Manifest: Define screen orientation in activity tag.

Example:

 

-> Using java code:
In manifest need to define the configurationChanges as orientation/screensize
In Activity override the onConfigurationChanged method.
Example:

 @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            Toast.makeText(this, "Current screen orientation is portrait", Toast.LENGTH_SHORT).show();
        }
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            Toast.makeText(this, "Current screen orientation is Landscape", Toast.LENGTH_SHORT).show();
        }
//        If we want to set screen orientation to portrait or landscape
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }