Sunday 21 December 2014

Intent Types

 Following are 2 types of intents

1.Explicit Intents

used to call a specific component. When you know which component you want to launch and you do not want to give the user free control over which component to use. For example, you have an application that has 2 activities. Activity A and activity B. You want to launch activity B from activity A. In this case you define an explicit intent targeting activityB and then use it to directly call it.

2.Implicit Intents

used when you have an idea of what you want to do, but you do not know which component should be launched. Or if you want to give the user an option to choose between a list of components to use. If these Intents are send to the Android system it searches for all components which are registered for the specific action and the data type. If only one component is found, Android starts the component directly. For example, you have an application that uses the camera to take photos. One of the features of your application is that you give the user the possibility to send the photos he has taken. You do not know what kind of application the user has that can send photos, and you also want to give the user an option to choose which external application to use if he has more than one. In this case you would not use an explicit intent. Instead you should use an implicit intent that has its action set to ACTION_SEND and its data extra set to the URI of the photo.

An explicit intent is always delivered to its target, no matter what it contains; the filter is not consulted. But an implicit intent is delivered to a component only if it can pass through one of the component's filters 



Examples:

Explicit Intent:  

          Intent explicitIntent = new Intent(ActivityA.this,ActivityB.class);
          startActivity(explicitIntent);




 Implicit Intent:

              Intent contacts = new Intent();
              contacts.setAction(android.content.Intent.ACTION_VIEW);
              contacts.setData(People.CONTENT_URI);
              startActivity(contacts);

            

What is Intent in Android?

An Intent is exactly what it describes. It's an "intention" to do an action.

An Intent is basically a message to say you did or want something to happen. Depending on the intent, apps or the OS might be listening for it and will react accordingly.

Think of it as a blast email to a bunch of friends, in which you tell your friend John to do something. The other folks will ignore the email, but John will react to it.

To listen for an intent (like the phone ringing, or an SMS is received), you implement a broadcast receiver.

If you want to fire off an intent to do something, like pop up the dialer, you fire off an intent saying you will.

Example:

After writing a single activity, there comes a need to transition to another activity to perform another task either with or without information from the first activity.

Android platform allows transition by means of Intent Interface.

In this example there are two activities - IntentActionDemo.java and IntentA.java that both extend the super class Activity. Do not forget to declare any new activity in the AndroidManifest.xml with permission.

I have introduced buttons in both activities which have a listener to allow an intent to transition from one intent to the other activity and vis-versa.
Simple intent example;
Note that optional step 2 was not used in our demo.
Step 1: Intent i = new Intent(context, NameOfClassToTransitionTo.class)

Step 2:(Optional)Intents can take various forms that make it even carry data in key/name pairs iei.putExtra("key1", "My first Info")
i.putExtra("key2", "My second Info")

Step 3: startActivity(i)



IntentActionDemo.java
Code:


package com.intent.example;

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 IntentActionDemo 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 button = (Button) findViewById(R.id.intentButton);
        button.setOnClickListener(this);
        
    }

    @Override
    public void onClick(View src) {
      Intent i = new Intent(this, IntentA.class);
      startActivity(i);
    }
}


IntentA.java

Code:


package 
com.intent.example;

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 IntentA extends Activity implements OnClickListener{

    @Override
    public void onClick(View src) {
      Intent i = new Intent(this, IntentActionDemo.class);
      startActivity(i);
    }
   
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.intenta);
       
        Button button = (Button) findViewById(R.id.ButtonIntentA);
        button.setOnClickListener(this);
    }
}


AndroidManifest.xml
Code:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="
com.intent.example"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".IntentActionDemo"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    <activity android:name="IntentA"></activity>
</application>
    <uses-sdk android:minSdkVersion="3" />

</manifest>


string.xml

Code:


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello</string>
    <string name="app_name">IntentActionDemo</string>
<string name="IntentA">Click Next intent</string>
<string name="world">World!</string>
<string name="Intent0">Click to Previous Intent</string>
</resources>


main.xml
Code:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    android:textSize="18sp"/>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/intentButton" android:text="@string/IntentA"></Button>
</LinearLayout>


intenta.xml
Code:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:orientation="vertical">

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/TextViewWorld" android:text="@string/world" android:textSize="18sp"></TextView>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/ButtonIntentA" android:text="@string/Intent0"></Button>
</LinearLayout>


How to open a PDF via Intent from SD card

  By starting activity with intent of ACTION_VIEW, for "application/pdf", we can ask the installed       PDF ready to open PDF file from our app.


File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf");

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);

Monday 21 April 2014

Navigation Menu/Android Sliding Menu Sample

Hello All,

By this post I am gonna explain about how to integrate the Navigation Drawer like Facebook, Gmail, Google+ apps.

First you have to know whats mean by Navigation Drawer:

1. Navigation Drawer: 


The navigation drawer is a panel that displays the app’s main navigation options on the left edge of the screen. It is hidden most of the time, but is revealed when the user swipes a finger from the left edge of the screen or, while at the top level of the app, the user touches the app icon in the action bar.

you can get more info about this here. Good news is its now available in the SupportLibrary itself. 


How to Create the Drawer Layout ? 


To add a navigation drawer, declare your user interface with aDrawerLayout object as the root view of your layout. Inside theDrawerLayout, add one view that contains the main content for the screen (your primary layout when the drawer is hidden) and another view that contains the contents of the navigation drawer.

For example, the following layout uses a DrawerLayout with two child views: a FrameLayout to contain the main content (populated by a Fragment at runtime), and a ListView for the navigation drawer.


<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <!-- The main content view -->
    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <!-- The navigation drawer -->
    <ListView android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#111"/>
</android.support.v4.widget.DrawerLayout>

Here is the code to do in MainActivity.java

public class MainActivity extends Activity {
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    ...

    public void onCreate(Bundle savedInstanceState) {
        ...

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_drawer,  /* nav drawer icon to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description */
                R.string.drawer_close  /* "close drawer" description */
                ) {

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                getActionBar().setTitle(mTitle);
            }

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                getActionBar().setTitle(mDrawerTitle);
            }
        };

        // Set the drawer toggle as the DrawerListener
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Pass the event to ActionBarDrawerToggle, if it returns
        // true, then it has handled the app icon touch event
        if (mDrawerToggle.onOptionsItemSelected(item)) {
          return true;
        }
        // Handle your other action bar items...

        return super.onOptionsItemSelected(item);
    }

    ...
}


You can load multiple no of Fragments into the NavigationDrawer like as follow 


/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new FindPeopleFragment();
break;
case 2:
fragment = new PhotosFragment();
break;
case 3:
fragment = new CommunityFragment();
break;
case 4:
fragment = new PagesFragment();
break;
case 5:
fragment = new WhatsHotFragment();
break;

default:
break;
}

if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();

// update selected item and title, then close the drawer
// mDrawerList.setItemChecked(position, true);
//mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}


}