I read through some articles. All seem to do the same thing and I was wondering what is the difference between starting the service as below:
Intent intent = new Intent(this, HelloService.class);
startService(intent);
or below:
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(this, MyService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);
As I read through, these two do the same thing, if in the service you return a parameter START_STICKY;
Intent
An Android Intent is an object carrying an intent, i.e. a message from one component to another component either inside or outside of the application. Intents can communicate messages among any of the three core components of an application -- Activities, Services, and BroadcastReceivers.
The intent itself, an Intent object, is a passive data structure. It holds an abstract description of an operation to be performed.
For example: say you have an Activity that needs to launch an email client and send an email. To do this, your Activity would send an Intent with the action ACTION_SEND, along with the appropriate chooser, to the Android Intent Resolver:
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:")); // only email apps should handle this
The specified chooser gives the proper interface for the user to pick how to send your email data.
EXPLICIT INTENTS
// Explicit Intent by specifying its class name
Intent i = new Intent(this, TargetActivity.class);
i.putExtra("Key1", "ABC");
i.putExtra("Key2", "123");
// Starts TargetActivity
startActivity(i);
IMPLICIT INTENTS
// Implicit Intent by specifying a URI
Intent i = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.example.com"));
// Starts Implicit Activity
startActivity(i);
Pending Intent
A PendingIntent is a token that you give to a foreign application (e.g. NotificationManager, AlarmManager, Home Screen AppWidgetManager, or other 3rd party applications), which allows the foreign application to use your application's permissions to execute a predefined piece of code.
By giving a PendingIntent to another application, you are granting it
the right to perform the operation you have specified as if the other
application was yourself (with the same permissions and identity). As
such, you should be careful about how you build the PendingIntent:
almost always, for example, the base Intent you supply should have the
component name explicitly set to one of your own components, to ensure
it is ultimately sent there and nowhere else.
Example for Pending Intent : http://android-pending-intent.blogspot.in/
Source : Android Intents and Android Pending Intents
PendingIntent is a wrapper of Intent. The foreign app that receives the PendingIntent, doesn't know the content of Intent which is wrapped by PendingIntent. The mission of foreign app is to send back the intent to owner when some conditions are met (For example: alarm with schedule, or notification with click...). The conditions are given by owner but processed by foreign app (For example: alarm, notification).
If foreign app sent intent to your app, mean that foreign app know about the content of the intent. and foreign app make decision to send intent then your app must process intent to meet some conditions => your app get performance resource of system.
Another simple difference:
Normal intent will die as soon as the app is killed.
Pending intents never die. They will be alive as long as it's needed by alarm service, location service, or any other services.
There's another major difference between Intent and PendingIntent which is better to be aware of, otherwise your app's design might become vulnerable. The problem is well described in Android Nesting Intents article.
Note that PendingIntent.send() method doesn't accept a Context instance, it uses a context provided during the intent creation instead. It allows a third party component to execute an action associated with a pending intent within the intent creator's context.
Let's imagine a third party service which performs some job and then starts an activity specified by your app as an intent. If the callback activity is provided as a basic Intent, the service can only start it using its own context and such a design has two drawbacks:
It forces the callback activity to be defined as exported so it can be started using a third party context. As a result the activity can be started not only by the service it was intended for, but by any other app installed on the device.
Any activity defined by the third party service app can be used as a callback activity, even non-exported one, since it's started using the third party context.
Both problems can be easily solved by specifying the callback activity as PendingIntent instead.
Functionally, there is no difference.
The meaning of PendingIntent is that, you can handle it to other application that later can use it as if the other application was yourself. Here is the relevant explanation from the documentation:
By giving a PendingIntent to another application, you are granting it
the right to perform the operation you have specified as if the other
application was yourself (with the same permissions and identity). As
such, you should be careful about how you build the PendingIntent:
almost always, for example, the base Intent you supply should have the
component name explicitly set to one of your own components, to ensure
it is ultimately sent there and nowhere else.
A PendingIntent itself is simply a reference to a token maintained by
the system describing the original data used to retrieve it.
So PendingIntent is just a reference to the data that represents the original Intent (that used to create the PendingIntent).
Starting services regularly via AlarmManager
As with activities the Android system may terminate the process of a service at any time to save resources. For this reason you cannot simply use a TimerTask in the service to ensure that it is executed on a regular basis.
So, for correct scheduling of the Service use the AlarmManager class.
UPDATE:
So there is no actual difference between the two.
But depending on whether you want to ensure the execution of the service or not, you can decide what to use as for the former there is no guarantee and for the later it is.
More info at AndroidServices.
Related
I'm trying to better understand the topic of intents.
An explicit intent is configured with a component's name. In every example I've seen, it's used to start or stop the component. Is this the only purpose of an explicit intent?
An implicit intent doesn't have a target component. Implicit intents can also start/stop a component, but they can also be received by BroadcastReceivers. Is there another way to receive an implicit intent?
When the OS sends the intent with the action set to Action.MAIN, that's an explicit intent, right?
Thanks.
From the android documentation:
Explicit intents specify the component to start by name (the
fully-qualified class name). You'll typically use an explicit intent
to start a component in your own app, because you know the class name
of the activity or service you want to start. For example, start a new
activity in response to a user action or start a service to download a
file in the background.
Implicit intents do not name a specific component, but instead declare
a general action to perform, which allows a component from another app
to handle it. For example, if you want to show the user a location on
a map, you can use an implicit intent to request that another capable
app show a specified location on a map.
Explicit intents, as you've said, are used to start an activity in your application -- or to transition from one "screen" to another. An explicit intent would be something like Intent intent = new Intent(currentContext, ActivityB.class); These types of intents are used when you are within your application and explicitly know which component you want to start depending on how the user interacts with your activity.
Implicit Intents don't directly specify the Android components which should be called, but rather just specify a general action to be performed. These are generally used when you would like some external application to do something for you. An example of an implicit intent used to send an email using an external application would be:
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"someemail#gmail.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject");
i.putExtra(Intent.EXTRA_TEXT , "body");
This intent would query for applications installed on the device that can handle sending an email, but there could be quite a few applications that can do this -- for example, if we have a gmail application, hotmail application, etc. So, basically you're just specifying a general action and asking the system "who can handle this", and the system will handle the rest. These types of intents are used by application developers so they don't have to "reinvent the wheel" if there is already something on the device that can do what the developer wants.
Here's a couple of references that might help explain it better:
http://developer.android.com/guide/components/intents-filters.html
http://www.vogella.com/articles/AndroidIntent/article.html
Is this the only purpose of an explicit intent?
An Intent generally is used to:
start an activity
start or stop a service
send a broadcast
An explicit Intent can be used for any of these.
Implicit intents can also start/stop a component, but they can also be received by BroadcastReceivers.
Whether an Intent is implicit or explicit is independent of what sort of role the Intent is used for.
Is there another way to receive an implicit intent?
An implicit Intent serves the roles listed above. You do not normally see it used for starting and stopping a service, though.
When the OS sends the intent with the action set to Action.MAIN, that's an explicit intent, right?
Not necessarily. If by "the OS" you mean "the home screen", and by "sends the intent with the action set to Action.MAIN", you mean "starts an activity based upon the user tapping on an icon in the launcher", then that is an explicit Intent, to identify the particular activity to start. An explicit Intent can have an action string, so it is not ACTION_MAIN that makes the Intent explicit.
Intent is an object which is used for communication between anyone of the android component(Activity, Services, BroadcastReceiver, ContentProvider) and Operating System.
Intent Class provides various constructors depending on what we intend to do.
In a case, Intent sends request to ActivityManager which activity to start. ActivityManager is a part of OS.
Now question will come that why do we require ActivityManager which is outside our application to communicate between two activities inside application. Here comes concept of Implicit and Explicit Intent.
Explicit Intent : To communication between components(Activity) within one application we use explicit intent.
Eg. Send current date from one activity to another.
Implicit Intent : To communicate between activities of different applications.
Eg. One application requesting photos from gallery application.
In case of Implicit Intent ActivityManager makes things easier.
As its name suggest Intent --> It's an "intention" to do an action.
It is a way of sending a message to perform an action which can be listen by other app or O.S.
In Explicit intent you know which work to perform by which person or class.
In Implicit intent you just ask a work to do ... all the apps capable of doing the activity like sharing a message will be shown in a list and you can do your work from any one of them.
I'm trying to create a method that will execute or run every 24 hours. What I exactly want to do is to delete the data from my database table "history" every day at 9am. I searched how to make this and I found an alarm manager but it works with PendingIntent. Is there any way to use alarm manager that handle a method instead of pending intent?
A PendingIntent is a token that you give to a foreign application (e.g. NotificationManager, AlarmManager, Home Screen AppWidgetManager, or other 3rd party applications), which allows the foreign application to use your application's permissions to execute a predefined piece of code.
If you give the foreign application an Intent, and that application sends/broadcasts the Intent you gave, they will execute the Intent with their own permissions. But if you instead give the foreign application a PendingIntent you created using your own permission, that application will execute the contained Intent using your application's permission.
So you can't use the AlaramManager without using the PendingIntent.
I read the Android Documentation but I still need some more clarification. What exactly is a PendingIntent?
A PendingIntent is a token that you give to a foreign application (e.g. NotificationManager, AlarmManager, Home Screen AppWidgetManager, or other 3rd party applications), which allows the foreign application to use your application's permissions to execute a predefined piece of code.
If you give the foreign application an Intent, it will execute your Intent with its own permissions. But if you give the foreign application a PendingIntent, that application will execute your Intent using your application's permission.
Why PendingIntent is required ? I was thinking like
Why the receiving application itself cannot create the Intent or
Why we cannot use a simple Intent for the same purpose.
E.g.Intent bluetoothIntent= new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
If I send bluetoothIntent to another application, which doesn't have permission android.permission.BLUETOOTH_ADMIN, that receiving application cannot enable Bluetooth with startActivity(bluetoothIntent).
The limitation is overcome using PendingIntent. With PendingIntent the receiving application, doesn't need to have android.permission.BLUETOOTH_ADMIN for enabling Bluetooth. Source.
A Pending Intent is a token you give to some app to perform an action on your apps' behalf irrespective of whether your application process is alive or not.
I think the documentation is sufficiently detailed:
Pending Intent docs.
Just think of use-cases for Pending Intents like (Broadcasting Intents, scheduling alarms) and the documentation will become clearer and meaningful.
In my case, none of above answers nor google's official documentation helped me to grab the concept of PendingIntent class.
And then I found this video, Google I/O 2013, Beyond the Blue Dot session. In this video, ex-googler Jaikumar Ganesh explains what PendingIntent is, and that was the thing gave me the big picture of this.
Below is just transcription of above video (from 15:24).
So what's a pending intent?
It's a token that your app process will give to the location process, and the location process will use it to wake up your app when an event of interest happens. So this basically means that your app in the background doesn't have to be always running. When something of interest happens, we will wake you up. This saves a lot of battery.
This explanation becomes more clear with this snippet of code(which is included in the session's slide).
PendingIntent mIntent = PendingIntent.getService(...);
mLocationClient.requestLocationUpdates(locationRequest, mIntent);
public void onHandleIntent(Intent intent) {
String action = intent.getAction();
if (ACTION_LOCATION.equals(action)) {
Location location = intent.getParcelableExtra(...)
}
}
Pending intent is an intent which will start at some point in the future. Normal intent starts immediately when it is passed to startActivity(Intent) or StartService(Intent).
TAXI ANALOGY
Intent
Intents are typically used for starting Services. For example:
Intent intent = new Intent(CurrentClass.this, ServiceClass.class);
startService(intent);
This is like when you call for a taxi:
Myself = CurrentClass
Taxi Driver = ServiceClass
Pending Intent
You will need to use something like this:
Intent intent = new Intent(CurrentClass.this, ServiceClass.class);
PendingIntent pi = PendingIntent.getService(parameter, parameter, intent, parameter);
getDataFromThirdParty(parameter, parameter, pi, parameter);
Now this Third party will start the service acting on your behalf.
A real life analogy is Uber or Lyft who are both taxi companies.
You send a request for a ride to Uber/Lyft. They will then go ahead and call one of their drivers on your behalf.
Therefore:
Uber/Lyft ------ ThirdParty which receives PendingIntent
Myself --------- Class calling PendingIntent
Taxi Driver ---- ServiceClass
What is an Intent?
An Intent is a specific command in Android that allows you to send a command to the Android OS to do something specific. Think of it as an action that needs to take place. There are many actions that can be done such as sending an email, or attaching a photo to an email, or even launching an application.
The logical workflow of creating an intent is usually as follows:
a. Create the Intent
b. Add Intent options -> Ex. what type of intent we are sending to the OS or any attributes associated with that intent, such as a text string or something being passed along with the intent
c. RUN the Intent
Real-Life Example: Let's say I wake up in the morning and I "INTEND" to go to the washroom. I will first have to THINK about going to the washroom, but that DOESN'T really gets me to the washroom. I will then have to tell my brain to get out of bed first, then walk to the washroom, and then release, then go and wash my hands, then go and wipe my hands. Once I know where I'm going I SEND the command to begin and my body takes action.
What is Pending Intents?
Continuing from the real-life example, let's say I want to take a shower but I want to shower AFTER I brush my teeth and eat breakfast. So I know I won't be showering until at least 30-40 minutes. I still have in my head that I need to prepare my clothes, and then walk up the stairs back to the bathroom, then undress and then shower. However, this will not happen until 30-40 minutes have passed. I now have a PENDING intent to shower. It is PENDING for 30-40 minutes.
That is pretty much the difference between a Pending Intent and a Regular Intent. Regular Intents can be created without a Pending Intent, however, in order to create a Pending Intent you need to have a Regular Intent setup first.
A future intent that other apps can use.
And here's an example for creating one:
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendIntent = PendingIntent.getActivity(context, 0, intent, 0);
A PendingIntent is a token that you give to another application (e.g. Notification Manager, Alarm Manager or other 3rd party applications), which allows this other application to use the permissions of your application to execute a predefined piece of code.
To perform a broadcast via a pending intent so get a PendingIntent via PendingIntent.getBroadcast(). To perform an activity via an pending intent you receive the activity via PendingIntent.getActivity().
PendingIntent is basically an object that wraps another Intent object. Then it can be passed to a foreign application where you’re granting that app the right to perform the operation, i.e., execute the intent as if it were executed from your own app’s process (same permission and identity). For security reasons you should always pass explicit intents to a PendingIntent rather than being implicit.
PendingIntent aPendingIntent = PendingIntent.getService(Context, 0, aIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
A PendingIntent wraps the general Intent with a token that you give to foreign app to execute with your permission.
For eg:
The notification of your music app can't play/pause the music if you
didn't give the PendingIntent to send broadcast because your music app
has READ_EXTERNAL_STORAGE permission which the notification app
doesn't. Notification is a system service (so it's a foreign app).
A Pending Intent specifies an action to take in the future. It lets you pass a future Intent to another application and allow that application to execute that Intent as if it had the same permissions as your application, whether or not your application is still around when the Intent is eventually invoked.
It is a token that you give to a foreign application which allows the foreign application to use your application’s permissions to execute a predefined piece of code.
If you give the foreign application an Intent, and that application sends/broadcasts the Intent you gave, they will execute the Intent with their own permissions. But if you instead give the foreign application a Pending Intent you created using your own permission, that application will execute the contained Intent using your application’s permission.
To perform a broadcast via a pending intent so get a PendingIntent via PendingIntent.getBroadcast(). To perform an activity via an pending intent you receive the activity via PendingIntent.getActivity().
It is an Intent action that you want to perform, but at a later time. Think of it a putting an Intent on ice. The reason it’s needed is because an Intent must be created and launched from a valid Context in your application, but there are certain cases where one is not available at the time you want to run the action because you are technically outside the application’s context (the two common examples are launching an Activity from a Notification or a BroadcastReceiver.
By creating a PendingIntent you want to use to launch, say, an Activity while you have the Context to do so (from inside another Activity or Service) you can pass that object around to something external in order for it to launch part of your application on your behalf.
A PendingIntent provides a means for applications to work, even after their process exits. Its important to note that even after the application that created the PendingIntent has been killed, that Intent can still run. A description of an Intent and target action to perform with it. Instances of this class are created with getActivity(Context, int, Intent, int), getBroadcast(Context, int, Intent, int), getService (Context, int, Intent, int); the returned object can be handed to other applications so that they can perform the action you described on your behalf at a later time.
By giving a PendingIntent to another application, you are granting it the right to perform the operation you have specified as if the other application was yourself (with the same permissions and identity). As such, you should be careful about how you build the PendingIntent: often, for example, the base Intent you supply will have the component name explicitly set to one of your own components, to ensure it is ultimately sent there and nowhere else.
A PendingIntent itself is simply a reference to a token maintained by the system describing the original data used to retrieve it. This means that, even if its owning application’s process is killed, the PendingIntent itself will remain usable from other processes that have been given it. If the creating application later re-retrieves the same kind of PendingIntent (same operation, same Intent action, data, categories, and components, and same flags), it will receive a PendingIntent representing the same token if that is still valid, and can thus call cancel() to remove it.
In an easy language,
1. A description of an Intent and Target action to perform. First you have to create an intent and then you have to pass an specific java class which you want to execute, to the Intent.
2. You can call those java class which is your class action class by PendingIntent.getActivity, PendingIntent.getActivities(Context, int, Intent[], int), PendingIntent.getBroadcast(Context, int, Intent, int), and PendingIntent.getService(Context, int, Intent, int);
Here you see that Intent which is comes from the step 1
3. You should keep in mind that...By giving a PendingIntent to another application, you are granting it the right to perform the operation you have specified.
That is what I learned after a long reading.
In simple terms
A pending intent is basically an intent that you can pass to other apps or services like notification manager, alarm manager etc. and let them handle when is the right timing/behaviour for it to be executed.
As its name suggest .. PendingIntent
you can pend(do it after some time) it . It work as the other intent ..it is a way of giving your task to some other app to perform on your behalf.
Pending Intent
A pending intent is a wrapper around regular intent that is designed
to be used by another application.
It gives that other application the ability to perform the included
action as it was your application with all the permissions your
application has been granted
When you want to open some application components like Activity/Service/BroadcastReceiver at later time or after some specified time interval you have to send PendingIntent in this case. It acts like a permission slip you gave to another apps to run your application’s code on your behalf after some time. So PendingIntent works beyond process boundaries like you want AlarmManager which is an another app in another process then AlarmManager perfom action on your app specified by PendingIntent
Pending Intent is an intent who provides all permission to other application to do a particular works. When the main activity is destroyed, Android OS takes back the permission from it.
I have came across PendingIntents in Notifications. So here is a simple explanation:
We want to provide an Intent to Notification, in this case we want to open a Activity which performs Camera capture functionality. Here, if we pass simply Intent, the NotificationManager doesnt have this permission although my app has this permission stated in Manifest; due to this the action wont work as NotificationManager doesnt have the permission to do so.
But, if you use PendingIntent, here the permission that my app have will be used instead of NotificationManager. Therefore, even if NotificationManager doesnt have Camera permission and my app has it will still open up the activity and perform the app.
NOTE: Pending intent requires regular Intent to be setup first.
What is an Intent in Android?
Can someone elaborate with an example?
What are the types of Intents, and why we are using them?
Why are Intents so important in Android?
An Intent is an "intention" to perform an action; in other words,
a messaging object you can use to request an action from another app component
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, or to friends who can do X ("intent filters"), to do X. The other folks will ignore the email, but John (or friends who can do X) will react to it.
To listen for an broadcast intent (like the phone ringing, or an SMS is received), you implement a broadcast receiver, which will be passed the intent. To declare that you can handle another's app intent like "take picture", you declare an intent filter in your app's manifest file.
If you want to fire off an intent to do something, like pop up the dialer, you fire off an intent saying you will.
What is an Intent ?
An Intent is basically a message that is passed between components (such as Activities, Services, Broadcast Receivers, and Content Providers). So, it is almost equivalent to parameters passed to API calls. The fundamental differences between API calls and invoking components via intents are:
API calls are synchronous while intent-based invocations are
asynchronous.
API calls are compile-time binding while intent-based calls are
run-time binding.
Of course, Intents can be made to work exactly like API calls by using what are called explicit intents, which will be explained later. But more often than not, implicit intents are the way to go and that is what is explained here.
One component that wants to invoke another has to only express its intent to do a job. And any other component that exists and has claimed that it can do such a job through intent-filters, is invoked by the Android platform to accomplish the job. This means, neither components are aware of each other's existence but can still work together to give the desired result for the end-user.
This invisible connection between components is achieved through the combination of intents, intent-filters and the Android platform.
This leads to huge possibilities like:
Mix and match or rather plug and play of components at runtime.
Replacing the inbuilt Android applications with custom developed
applications.
Component level reuse within and across applications.
Service orientation to the most granular level, if I may say.
Here are additional technical details about Intents from the Android documentation.
An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a Background Service.
An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed. The primary pieces of information in an intent are:
action
The general action to be performed, such as ACTION_VIEW,
ACTION_EDIT, ACTION_MAIN, etc.
data
The data to operate on, such as a person record in the contacts
database, expressed as a Uri.
Learn more
Lars Vogel's tutorial
ProgrammerGuru article
Common intents
Intents are a way of telling Android what you want to do.
In other words, you describe your intention. Intents can be used to signal to the Android system that a certain event has occurred. Other components in Android can register to this event via an intent filter.
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
Intent Filters
If an Intents is send to the Android system, it will determine suitable applications for this Intents. If several components have been registered for this type of Intents, Android offers the user the choice to open one of them.
This determination is based on IntentFilters. An IntentFilters specifies the types of Intent that an activity, service, orBroadcast Receiver can respond to. An Intent Filter declares the capabilities of a component. It specifies what anactivity or service can do and what types of broadcasts a Receiver can handle. It allows the corresponding component to receive Intents of the declared type. IntentFilters are typically defined via the AndroidManifest.xml file. For BroadcastReceiver it is also possible to define them in coding. An IntentFilters is defined by its category, action and data filters. It can also contain additional metadata.
If a component does not define an Intent filter, it can only be called by explicit Intents.
Following are 2 ways to define a filter
1.Manifest file
If you define the intent filter in the manifest, your application does not have to be running to react to the intents defined in it’s filter. Android registers the filter when your application gets installed.
2.BroadCast Receiver
If you want your broadcast receiver to receive the intent only when your application is running. Then you should define your intent filter during run time (programatically). Keep in mind that this works for broadcast receivers only.
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.
Words are taken from here: Using Intent Demo and i suggest you to go through this example because they also have provided a code file as well. so you can use it and easily understand the same.
Android Intent
Android Intent lets you navigate from one android activity to another. With examples, this tutorial also talks about various types of Android intents.
Android Intent can be defined as a simple message objects which is used to communicate from 1 activity to another.
Intents define intention of an Application . They are also used to transfer data between activities.
An Android Intent can be used to perform following 3 tasks :
Open another Activity or Service from the current Activity
Pass data between Activities and Services
Delegate responsibility to another application. For example, you can
use Intents to open the browser application to display a URL.
Intent can be broadly classified into 2 categories. There are no keywords for this category and just a broad classification of how android intents are used.
Explicit Android Intent
Explicit Android Intent is the Intent in which you explicitly define the component that needs to be called by Android System.
Intent MoveToNext = new Intent (getApplicationContext(), SecondActivity.class);
Implicit Android Intent
Implicit Android Intents is the intent where instead of defining the exact components, you define the action you want to perform. The decision to handle this action is left to the operating system. The OS decides which component is best to run for implicit intents.
Let us see an example:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
For more information you may visit below
http://developer.android.com/reference/android/content/Intent.html
According to their documentation:
An Intent is an object that provides runtime binding between separate components (such as two activities). The Intent represents an app’s "intent to do something." You can use intents for a wide variety of tasks, but most often they’re used to start another activity.
Here is the link with example:
http://developer.android.com/training/basics/firstapp/starting-activity.html#BuildIntent
As the document describes, in order to start an activity (you also need to understand what activity is) use the intent like below
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.
For more details see these links :
1). http://developer.android.com/reference/android/content/Intent.html
2) http://developer.android.com/guide/topics/intents/intents-filters.html
3). http://www.vogella.de/articles/AndroidIntent/article.html
there are many more articles are available.
what is Intent ?
It is a kind of message or information that is passed to the components. It is used to launch an activity, display a web page, send sms, send email etc.
There are two types of intents in android:
Implicit Intent
Explicit Intent
Implicit intent is used to invoke the system components
Example
Intent i = newIntent(android.content.Intent.ACTION_VIEW,Uri.parse(“http://www.amazon.com”));
startActivity(i);
Explicit intent is used to invoke the activity class.
Example
Intent intent = newIntent (this, SecondActivity.class);
startActivity(intent);
you can read more
http://www.vogella.com/tutorials/AndroidIntent/article.html#intents_overview
http://developer.android.com/reference/android/content/Intent.html
An Intent is a class,that is bind the information for doing some actions.
example:passing data one activity to another actvity when user perform such actions in
present activity.
In a broad view, we can define Intent as
When one Activity wants to start another activity it creates an Object
called Intent that specifies which Activity it wants to start.
From the paper Deep Dive into Android IPC/Binder Framework atAndroid Builders Summit 2013 link
The intent is understood in some small but effective lines
Android supports a simple form of IPC(inter process communication) via intents
Intent messaging is a framework for asynchronous communication among Android components (activity, service, content providers, broadcast receiver )
Those components may run in the same or across different apps (i.e. processes)
Enables both point-to-point as well as publish subscribe messaging domains
The intent itself represents a message containing the description of the operation to be performed as well as data to be passed to the recipient(s).
From this thread a simple answer of android architect Dianne Hackborn states it as a data container which it actually is.
From android architecture point of view :
Intent is a data container that is used for inter process communication. It is built on top of the Binder from android architecture point of view.
An Android application can contain zero or more activities. When your application has more than one activity, you often need to navigate from one to another. In Android, you navigate between activities through what is known as an intent. You can pass some data to the activity which you want to start through intent, by using putExtra().
Intents are used to initiate another activity from one activity.It is basically used for several purposes such as sending data to another activity from one activity,and for triggering purposes.
They are basically of two types
Implicit intents.
Explicit intents.
As a beginner I know this much,I think this will give some basic idea about android intents
An intent is basically a way of passing data from one activity to other activity
I read the Android Documentation but I still need some more clarification. What exactly is a PendingIntent?
A PendingIntent is a token that you give to a foreign application (e.g. NotificationManager, AlarmManager, Home Screen AppWidgetManager, or other 3rd party applications), which allows the foreign application to use your application's permissions to execute a predefined piece of code.
If you give the foreign application an Intent, it will execute your Intent with its own permissions. But if you give the foreign application a PendingIntent, that application will execute your Intent using your application's permission.
Why PendingIntent is required ? I was thinking like
Why the receiving application itself cannot create the Intent or
Why we cannot use a simple Intent for the same purpose.
E.g.Intent bluetoothIntent= new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
If I send bluetoothIntent to another application, which doesn't have permission android.permission.BLUETOOTH_ADMIN, that receiving application cannot enable Bluetooth with startActivity(bluetoothIntent).
The limitation is overcome using PendingIntent. With PendingIntent the receiving application, doesn't need to have android.permission.BLUETOOTH_ADMIN for enabling Bluetooth. Source.
A Pending Intent is a token you give to some app to perform an action on your apps' behalf irrespective of whether your application process is alive or not.
I think the documentation is sufficiently detailed:
Pending Intent docs.
Just think of use-cases for Pending Intents like (Broadcasting Intents, scheduling alarms) and the documentation will become clearer and meaningful.
In my case, none of above answers nor google's official documentation helped me to grab the concept of PendingIntent class.
And then I found this video, Google I/O 2013, Beyond the Blue Dot session. In this video, ex-googler Jaikumar Ganesh explains what PendingIntent is, and that was the thing gave me the big picture of this.
Below is just transcription of above video (from 15:24).
So what's a pending intent?
It's a token that your app process will give to the location process, and the location process will use it to wake up your app when an event of interest happens. So this basically means that your app in the background doesn't have to be always running. When something of interest happens, we will wake you up. This saves a lot of battery.
This explanation becomes more clear with this snippet of code(which is included in the session's slide).
PendingIntent mIntent = PendingIntent.getService(...);
mLocationClient.requestLocationUpdates(locationRequest, mIntent);
public void onHandleIntent(Intent intent) {
String action = intent.getAction();
if (ACTION_LOCATION.equals(action)) {
Location location = intent.getParcelableExtra(...)
}
}
Pending intent is an intent which will start at some point in the future. Normal intent starts immediately when it is passed to startActivity(Intent) or StartService(Intent).
TAXI ANALOGY
Intent
Intents are typically used for starting Services. For example:
Intent intent = new Intent(CurrentClass.this, ServiceClass.class);
startService(intent);
This is like when you call for a taxi:
Myself = CurrentClass
Taxi Driver = ServiceClass
Pending Intent
You will need to use something like this:
Intent intent = new Intent(CurrentClass.this, ServiceClass.class);
PendingIntent pi = PendingIntent.getService(parameter, parameter, intent, parameter);
getDataFromThirdParty(parameter, parameter, pi, parameter);
Now this Third party will start the service acting on your behalf.
A real life analogy is Uber or Lyft who are both taxi companies.
You send a request for a ride to Uber/Lyft. They will then go ahead and call one of their drivers on your behalf.
Therefore:
Uber/Lyft ------ ThirdParty which receives PendingIntent
Myself --------- Class calling PendingIntent
Taxi Driver ---- ServiceClass
What is an Intent?
An Intent is a specific command in Android that allows you to send a command to the Android OS to do something specific. Think of it as an action that needs to take place. There are many actions that can be done such as sending an email, or attaching a photo to an email, or even launching an application.
The logical workflow of creating an intent is usually as follows:
a. Create the Intent
b. Add Intent options -> Ex. what type of intent we are sending to the OS or any attributes associated with that intent, such as a text string or something being passed along with the intent
c. RUN the Intent
Real-Life Example: Let's say I wake up in the morning and I "INTEND" to go to the washroom. I will first have to THINK about going to the washroom, but that DOESN'T really gets me to the washroom. I will then have to tell my brain to get out of bed first, then walk to the washroom, and then release, then go and wash my hands, then go and wipe my hands. Once I know where I'm going I SEND the command to begin and my body takes action.
What is Pending Intents?
Continuing from the real-life example, let's say I want to take a shower but I want to shower AFTER I brush my teeth and eat breakfast. So I know I won't be showering until at least 30-40 minutes. I still have in my head that I need to prepare my clothes, and then walk up the stairs back to the bathroom, then undress and then shower. However, this will not happen until 30-40 minutes have passed. I now have a PENDING intent to shower. It is PENDING for 30-40 minutes.
That is pretty much the difference between a Pending Intent and a Regular Intent. Regular Intents can be created without a Pending Intent, however, in order to create a Pending Intent you need to have a Regular Intent setup first.
A future intent that other apps can use.
And here's an example for creating one:
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendIntent = PendingIntent.getActivity(context, 0, intent, 0);
A PendingIntent is a token that you give to another application (e.g. Notification Manager, Alarm Manager or other 3rd party applications), which allows this other application to use the permissions of your application to execute a predefined piece of code.
To perform a broadcast via a pending intent so get a PendingIntent via PendingIntent.getBroadcast(). To perform an activity via an pending intent you receive the activity via PendingIntent.getActivity().
PendingIntent is basically an object that wraps another Intent object. Then it can be passed to a foreign application where you’re granting that app the right to perform the operation, i.e., execute the intent as if it were executed from your own app’s process (same permission and identity). For security reasons you should always pass explicit intents to a PendingIntent rather than being implicit.
PendingIntent aPendingIntent = PendingIntent.getService(Context, 0, aIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
A PendingIntent wraps the general Intent with a token that you give to foreign app to execute with your permission.
For eg:
The notification of your music app can't play/pause the music if you
didn't give the PendingIntent to send broadcast because your music app
has READ_EXTERNAL_STORAGE permission which the notification app
doesn't. Notification is a system service (so it's a foreign app).
A Pending Intent specifies an action to take in the future. It lets you pass a future Intent to another application and allow that application to execute that Intent as if it had the same permissions as your application, whether or not your application is still around when the Intent is eventually invoked.
It is a token that you give to a foreign application which allows the foreign application to use your application’s permissions to execute a predefined piece of code.
If you give the foreign application an Intent, and that application sends/broadcasts the Intent you gave, they will execute the Intent with their own permissions. But if you instead give the foreign application a Pending Intent you created using your own permission, that application will execute the contained Intent using your application’s permission.
To perform a broadcast via a pending intent so get a PendingIntent via PendingIntent.getBroadcast(). To perform an activity via an pending intent you receive the activity via PendingIntent.getActivity().
It is an Intent action that you want to perform, but at a later time. Think of it a putting an Intent on ice. The reason it’s needed is because an Intent must be created and launched from a valid Context in your application, but there are certain cases where one is not available at the time you want to run the action because you are technically outside the application’s context (the two common examples are launching an Activity from a Notification or a BroadcastReceiver.
By creating a PendingIntent you want to use to launch, say, an Activity while you have the Context to do so (from inside another Activity or Service) you can pass that object around to something external in order for it to launch part of your application on your behalf.
A PendingIntent provides a means for applications to work, even after their process exits. Its important to note that even after the application that created the PendingIntent has been killed, that Intent can still run. A description of an Intent and target action to perform with it. Instances of this class are created with getActivity(Context, int, Intent, int), getBroadcast(Context, int, Intent, int), getService (Context, int, Intent, int); the returned object can be handed to other applications so that they can perform the action you described on your behalf at a later time.
By giving a PendingIntent to another application, you are granting it the right to perform the operation you have specified as if the other application was yourself (with the same permissions and identity). As such, you should be careful about how you build the PendingIntent: often, for example, the base Intent you supply will have the component name explicitly set to one of your own components, to ensure it is ultimately sent there and nowhere else.
A PendingIntent itself is simply a reference to a token maintained by the system describing the original data used to retrieve it. This means that, even if its owning application’s process is killed, the PendingIntent itself will remain usable from other processes that have been given it. If the creating application later re-retrieves the same kind of PendingIntent (same operation, same Intent action, data, categories, and components, and same flags), it will receive a PendingIntent representing the same token if that is still valid, and can thus call cancel() to remove it.
In an easy language,
1. A description of an Intent and Target action to perform. First you have to create an intent and then you have to pass an specific java class which you want to execute, to the Intent.
2. You can call those java class which is your class action class by PendingIntent.getActivity, PendingIntent.getActivities(Context, int, Intent[], int), PendingIntent.getBroadcast(Context, int, Intent, int), and PendingIntent.getService(Context, int, Intent, int);
Here you see that Intent which is comes from the step 1
3. You should keep in mind that...By giving a PendingIntent to another application, you are granting it the right to perform the operation you have specified.
That is what I learned after a long reading.
In simple terms
A pending intent is basically an intent that you can pass to other apps or services like notification manager, alarm manager etc. and let them handle when is the right timing/behaviour for it to be executed.
As its name suggest .. PendingIntent
you can pend(do it after some time) it . It work as the other intent ..it is a way of giving your task to some other app to perform on your behalf.
Pending Intent
A pending intent is a wrapper around regular intent that is designed
to be used by another application.
It gives that other application the ability to perform the included
action as it was your application with all the permissions your
application has been granted
When you want to open some application components like Activity/Service/BroadcastReceiver at later time or after some specified time interval you have to send PendingIntent in this case. It acts like a permission slip you gave to another apps to run your application’s code on your behalf after some time. So PendingIntent works beyond process boundaries like you want AlarmManager which is an another app in another process then AlarmManager perfom action on your app specified by PendingIntent
Pending Intent is an intent who provides all permission to other application to do a particular works. When the main activity is destroyed, Android OS takes back the permission from it.
I have came across PendingIntents in Notifications. So here is a simple explanation:
We want to provide an Intent to Notification, in this case we want to open a Activity which performs Camera capture functionality. Here, if we pass simply Intent, the NotificationManager doesnt have this permission although my app has this permission stated in Manifest; due to this the action wont work as NotificationManager doesnt have the permission to do so.
But, if you use PendingIntent, here the permission that my app have will be used instead of NotificationManager. Therefore, even if NotificationManager doesnt have Camera permission and my app has it will still open up the activity and perform the app.
NOTE: Pending intent requires regular Intent to be setup first.