Friday, January 27, 2012

How to launch pending intent?

Pending Intent:


An application can create a Pending Intent, which is nothing but an intent and action to it, so that it can passed to some other applications which can execute this pendingintent as if original application executes it.


PendingIntents can be created of three types


getActivity(Context, int, Intent, int), getBroadcast(Context, int, Intent, int),
getService(Context, int, Intent, int);



You can create a pending intent to launch an activity, or service, broadcast an intent.


Let us see how to create an pendingIntent which can launch an activity and see once you have pendingIntent, how can you launch make operation on the intent.


Following is example with two activity


1. Activity1



package com.mani.pending;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;


public class activity extends Activity {
 Button b1;
 PendingIntent pendingIntent;
 Context mContext;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mContext = this.getApplicationContext();
        b1 = (Button) findViewById(R.id.button);
        Intent intent = new Intent();
        intent.setClass(mContext,activity2.class);
        pendingIntent =  PendingIntent.getActivity(mContext, 0, intent, 0);
        
        b1.setOnClickListener( new View.OnClickListener() {

 @Override
 public void onClick(View v) {
  // TODO Auto-generated method stub
  Intent intent = new Intent();
  try {
   pendingIntent.send(mContext, 0, intent);

  } catch (PendingIntent.CanceledException e) {
  // the stack trace isn't very helpful here.  Just log the exception message.
  System.out.println( "Sending contentIntent failed: " );
  }
 }
 });
        
    }
}


2. Activity2



package com.mani.pending;


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


public class activity2 extends Activity{


 TextView v1;
    public void onCreate(Bundle savedInstanceState) {
     
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
         v1 = (TextView)findViewById(R.id.text);
         v1.setTextSize(30);
         v1.setText("Welcome to pendinIntent");
    }


}




No comments:

Post a Comment