Monday, August 25, 2014

Intents

Intent is a request for an action to be performed on a set of data.

Android applications are sandboxed but they can use
  • Intents, 
  • Broadcast Receivers,
  • Adapters, 
  • Content Providers, 
  • Internet 
to interact through those boundaries.

An Android application can contain zero or more activities.

In Android, you navigate between activities through what is known as an intent.

An Activity started via startActivity is independent of its parent and will not provide any feedback when it closes.

Activities in Android can be invoked by any application running on the device

Explicitly starting an activity

Intent intent = new Intent(MyActivity.class, MyOtherActivity.class);
startActivity(intent);


If the activity that you want to invoke is defined within the same project, you can use

startActivity(new Intent(this, SecondActivity.class));

https://github.com/coderetriever/Android/tree/master/SimpleIntent

Implicitly starting an activity

format
new Intent(action constant/component name, data to be processed)

Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:123-4567"));
startActivity(intent)

public class UsingIntentActivity extends Activity 
{
  ...
public void onClick(View view) {
startActivity(new Intent("com.example.simpleintent.SecondActivity"));
}
}

public class SecondActivity extends Activity{
 ...
}

In AndroidManifest.xml

        <activity
            android:name=".SecondActivity"
            android:label="Second Activity" >
            <intent-filter>
                <action android:name="com.example.simpleintent.SecondActivity" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

The intent filter name for the new activity com.example.simpleintent.SecondActivity
Other activities that wish to call this activity will invoke it via this name.

If you do not want other activities to call your activity from outside your application, simply remove
the <action> element within the <intent-filter> element

The category for the intent filter is android.intent.category.DEFAULT
You need to add this to the intent filter so that this activity can be started by another activity using the startActivity() method.

Alternatively, you can start an Activity as a sub-Activity that’s inherently connected to its parent.

Explicitly starting a sub-activity

To call an activity and get a result to be returned from it, you need to use the startActivityForResult() method

The request code is simply an integer value that identifies an activity you are calling.

For example, you may be calling multiple activities at the same time, and some activities may not return immediately (for example, waiting for a reply from a server).

When an activity returns, you need this request code to determine which activity is actually returned

private static final int SHOW_SUBACTIVITY = 1;

Intent intent = new Intent(this, MyOtherActivity.class);
startActivityForResult(intent, SHOW_SUBACTIVITY);

Implicitly starting a sub-activity

private static final int SHOW_SUBACTIVITY = 1;

Uri uri = Uri.parse("content://contacts/people");
Intent intent = new Intent(Intent.ACTION_PICK, uri);
startActivityForResult(intent, PICK_CONTACT_SUBACTIVITY);

Returning Results from sub-activity

The setResult() method sets a result code (either RESULT_OK or RESULT_CANCELLED) and the data (an Intent object) to be returned back to the calling activity.

The finish() method closes the activity and returns control back to the calling activity

setResult(result code, result itself as an intent)
result code: Activity.RESULT_OK or Activity.RESULT_CANCELED or any integer value

Uri data = Uri.parse("content://markers/" + marked_id);

Intent resultIntent = new Intent(null, data);
resultIntent.putExtra(key1, value1);
resultIntent.putExtra(key2, value2);
setResult(RESULT_OK, resultIntent);
finish();


Handling sub-activity results in the parent Activity

In the calling activity, you need to implement the onActivityResult() method, which is called whenever an activity returns.

Override the following
onActivityResult(request code, result code, resultIntent)

Uri data = resultIntent.getData();
resultIntent.getBooleanExtra(key1, default_value);
resultIntent.getStringExtra(key2);

Example

https://github.com/coderetriever/Android/tree/master/IntentReturnResults

public class UsingIntentActivity extends Activity {
int request_Code = 1;

public void onClick(View view) {
startActivityForResult(new Intent("com.example.intentreturnresults.SecondActivity"), requestCode);
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == request_Code) {
if (resultCode == RESULT_OK) {
Toast.makeText(this, data.getData().toString(),
Toast.LENGTH_SHORT).show();
}
}
}
}

public class SecondActivity extends Activity{
    public void onClick(View view) {
        Intent data = new Intent();

        //---get the EditText view---
        EditText txt_username =
            (EditText) findViewById(R.id.txt_username);

        //---set the data to pass back---
        data.setData(Uri.parse(txt_username.getText().toString()));
        setResult(RESULT_OK, data);

        //---closes the activity---
        finish();
    }
}

AndroidManifest.xml

        <activity
            android:name="com.example.intentreturnresults.UsingIntentActivity"
            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=".SecondActivity"
            android:label="Second Activity" >
            <intent-filter>
                <action android:name="com.example.intentreturnresults.SecondActivity" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

        </activity>

Passing Data Using an Intent Object

Sending Data
Can use the putExtra() method of an Intent object to add a name/value pair
you can also create a Bundle object and then attach it using the putExtras() method

Receiving Data
Obtain the Intent object using the getIntent() method. Use the getIntExtra() method, to get the int value.
To retrieve the Bundle object, use the getExtras() method

Sending Data
Another way to pass data to an activity is to use the setData() method on the intent object

Receiving Data
To retrieve the data set using the setData() method, use the getData() method on the intent object

Sending Data
Through the intent objects constructor in a URI object.

https://github.com/coderetriever/Android/tree/master/IntentPassingData

public class PassingDataActivity extends Activity {
    public void onClick(View view) {
    Intent i = new 
    Intent("com.example.intentpassingdata.SecondActivity");

    //---use putExtra() to add new key/value pairs---            
    i.putExtra("str1", "This is a string");
    i.putExtra("age1", 25);

    //---use a Bundle object to add new key/values 
    // pairs---  
    Bundle extras = new Bundle();
    extras.putString("str2", "This is another string");
    extras.putInt("age2", 35);                

    //---attach the Bundle object to the Intent object---
    i.putExtras(extras);                

    //---start the activity to get a result back---
    startActivityForResult(i, 1);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        //---check if the request code is 1---
        if (requestCode == 1) {

            //---if the result is OK--- 
            if (resultCode == RESULT_OK) {

                //---get the result using getIntExtra()---
                Toast.makeText(this, Integer.toString(
                    data.getIntExtra("age3", 0)), 
                    Toast.LENGTH_SHORT).show();      

                //---get the result using getData()---
                Toast.makeText(this, data.getData().toString(), 
                    Toast.LENGTH_SHORT).show();
            }            
        }
    }
}


public class Second_Activity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_layout);

//---get the data passed in using getStringExtra()---
Toast.makeText(this,getIntent().getStringExtra("str1"), 
Toast.LENGTH_SHORT).show();

//---get the data passed in using getIntExtra()---
Toast.makeText(this,Integer.toString(
getIntent().getIntExtra("age1", 0)), 
Toast.LENGTH_SHORT).show();               

//---get the Bundle object passed in---
Bundle bundle = getIntent().getExtras();

//---get the data using the getString()---         
Toast.makeText(this, bundle.getString("str2"), 
Toast.LENGTH_SHORT).show();

//---get the data using the getInt() method---
Toast.makeText(this,Integer.toString(bundle.getInt("age2")), 
Toast.LENGTH_SHORT).show();
}

public void onClick(View view) {
//---use an Intent object to return data---
Intent i = new Intent();            

//---use the putExtra() method to return some 
// value---
i.putExtra("age3", 45);

//---use the setData() method to return some value---
i.setData(Uri.parse(
"Something passed back to main activity"));                           

//---set the result with OK and the Intent object---
setResult(RESULT_OK, i);

//---destroy the current activity---
finish();        
}
}

https://github.com/coderetriever/Android/tree/master/IntentPassingData

https://github.com/coderetriever/Android/tree/master/PassingData

createChooser method

If the activity you are trying to call does not exist on the device, your application will crash.

To ensure that your application does not stop abruptly, call the startActivity() method together with the Intent.createChooser() method.

The createChooser() method takes an Intent object and a string to display if an activity cannot be found (or if more than one activity has been found to satisfy your Intent object):

Intent i = new Intent("net.learn2develop.Activity2");
startActivity(Intent.createChooser(i, "Choose an application"));

https://github.com/coderetriever/Android/tree/master/Linking

Calling Built-in Applications with Intents

One of the key aspects of Android programming is using the intent to call activities from other applications, including built-ins.

For example, if your application needs to load a web page, you can use the Intent object to invoke the built-in web browser to display the web page, instead of building your own web browser for this purpose.

Can use the Intent class to invoke some of the built-in applications in Android (such as Maps, Phone,

Contacts, and Browser).

An Intent object can contain the following information
  • Action Constant/Component name
    • used to identify the target activity/application that you want to invoke
  • Data
  • Type
    • to specify the type of data to return.
  • Category
    • groups activities into logical units so that Android can use it for further filtering
Intents usually come in pairs: action and data.

Example
To dial a phone number, you would use the pair ACTION_DIAL/tel:+651234567
To display a list of contacts stored in your phone, you use the pair ACTION_VIEW/content://contacts
To pick a contact from the list of contacts, you use the pair ACTION_PICK/content://contacts

Code
Action: android.content.Intent.ACTION_VIEW
Data: http://www.amazon.com

Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(“http://www.amazon.com”));

startActivity(i);

android.content.Intent.ACTION_VIEW constant refers to the “android.intent.action.VIEW” action

Intent i = new Intent(“android.intent.action.VIEW”, Uri.parse(“http://www.amazon.com”));
startActivity(i);

or

Intent i = new Intent(“android.intent.action.VIEW”);
i.setData(Uri.parse(“http://www.amazon.com”));
startActivity(i);


ACTION

Describes what is to be performed, such as 
  • editing an item
  • viewing the content of an item. 
Examples:

ACTION_VIEW
ACTION_DIAL

  • To just display the dialer, omit the data portion.

ACTION_CALL, to directly call

  • to directly call the specified number, you need to add the android.permission.CALL_PHONE permission to your application

ACTION_PICK

Note: No data is needed for this intent. 
It just needs a MIME data type to indicate the type of data to return.
The MIME type for ContactsContract.Contacts.CONTENT_TYPE is "vnd.android.cursor.dir/contact”.

Intent i = new Intent(android.content.Intent.ACTION_PICK);

i.setType(ContactsContract.Contacts.CONTENT_TYPE);


DATA

Specifies what is affected as an URI object, such as 
  • a person in the Contacts database.

Examples:

www.google.com
tel:+651234567
geo:37.827500,-122.481670
content://contacts




For all activities that you want others to
call using the startActivity() or startActivityForResult() methods, they need to have the

“android.intent.category.DEFAULT” category

The <data> element specifi es the type of data expected by the activity. In this case, it expects the data

to start with the “http://” prefix

When multiple activities match your Intent object, the dialog titled “Complete action using”

appears. You can customize this by using the createChooser() method from the Intent class

The added benefit of using the createChooser() method is that in the event that no activity matches

your Intent object, your application will not crash

https://github.com/coderetriever/Android/tree/master/CallBuiltInsUsingIntents

No comments:

Post a Comment