Android Context Class more specific - android

For what purpose Context class is used in android?Please explain me in depth and be more specific .I read all other posts but none of them were specific enough to give me clear understanding.
I know Content class allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.
Like Here,
Intent intent=new Intent(this,new_class.class);
why we are passing Main activity context into the Intent constructor call.what type of information does this activity context contain,how will it help it ,what type of resource access is it providing to it ?(with example please).
Similarly,
here,
TextView textview=new TextView(this);
Why TextView need activity context?How does it help it.

There are already several good explanations of Context on Stackoverflow (see the linked questions and us the "search" feature. Also, the source code for Android is available on grepcode.com and you can look yourself if you are really interested. Why trust someone else's answer if you can look yourself? ;-)
However, I will answer your specific questions:
Intent intent=new Intent(this,new_class.class);
why we are passing Main activity context into the Intent constructor
call.what type of information does this activity context contain,how
will it help it ,what type of resource access is it providing to it
?(with example please).
In this case (the 2-argument constructor for Intent), the Context parameter is only used to determine the package name of the target Activity. Assuming that the package name of your application is "com.example.app", and MyActivity is an `Activity of your application, the following code snippets are all functionally identical:
Intent intent = new Intent(this, MyActivity.class);
Intent intent = new Intent(getApplicationContext(), MyActivity.class);
Intent intent = new Intent();
intent.setComponent(new ComponentName(this, "com.example.app.MyActivity");
Intent intent = new Intent();
intent.setComponent(new ComponentName(this, MyActivity.class);
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example.app", MyActivity.class);
Intent intent = new Intent();
intent.setClass(this, MyActivity.class);
Intent intent = new Intent();
intent.setClassName("com.example.app", "com.example.app.MyActivity");
Similarly, here,
TextView textview=new TextView(this);
Why TextView need activity context?How does it help it.
All Views need a Context. Think of the Context as the "owner of the View". This controls the lifetime of the View. In general, a View should have the same lifetime as its owning Activity, which is why you usually pass the Activity as the Context parameter when creating a View. When the Activity is destroyed, all of the owned Views are also destroyed. Additionally, the View uses the Context to gain access to resources (drawables, layouts, strings, themes, etc.).

It act as a Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.
You can get all the information from delveloper's official documentation... https://developer.android.com/reference/android/content/Context.html

Related

Android / Sending activity context through intent

I have 5 or so activities in Android (2 of them have been shown below), which share a common Navigation Drawer. If I log in into some account from the Navigation Drawer, after successful log in, the activity which was previously showing needs to be loaded. Is it possible to send activity context through intent?
FirstActivity.java
Intent intent1 = new Intent(FirstActivity.this, Login.class);
intent1.putExtra("activity", "FirstActivity");
startActivity(intent1);
finish();
SecondActivity.java
Intent intent2 = new Intent(SecondActivity.this, Login.class);
intent2.putExtra("activity", "SecondActivity");
startActivity(intent2);
finish();
When finding the name of the activity to return in log in activity, after successful log in.
Login.java
Intent intent3 = getIntent();
String activity = intent3.getStringExtra("activity");
...
Intent intent4 = new Intent(Login.this, Class.forName(activity));
startActivity(intent4);
finish();
returns the following error message:
W/System.err: java.lang.ClassNotFoundException: Home
at java.lang.Class.classForName(Native Method)
at java.lang.Class.forName(Class.java:453)
Does anyone know how to fix it up?
Making use of intent1.putExtra("activity", String.valueOf(FirstActivity.this)); also does not work out either, it says that com.example.nativeapp.FirstActivity#6a7640 is an invalid class name.
Should I convert the activity context to Serializable or Parcelable or even CharSequence when I try to send those variable values through intent? Activity or AppCompatActivity does not seem to inherit Serializable or Parcelable for that to work out it seems. CharSequence does not seem to make much difference from making use of String.
I know that I can create my own class to store global variables and activity contexts and my activity can inherit from that but since my activity already inherits NavigationDrawer, my activity cannot inherit a second class. Can I declare that as an interface and inherit an interface to access global variable values from interface? Getter and setter methods, for sure cannot work out in an interface, since no implementation of functions and no declaration of variable values are allowed in an interface.
One of the reasons why I have been considering to decide to make use of a central superclass for storing variable values and changing them from subclasses whenever that I am trying to move from one activity to another is that activity contexts like this, I am not sure how to pass them through intents. That intent, which should also be able to pass on within the other central global variables of the mobile application from one activity class to another. The central superclass, such as the NavigationDrawer which is an excellent candidate since all of my Android activity classes inherit from it would be best to use if all central global variables are stored in it and they are changed from subclasses whenever that I am trying to move from one activity to another.
How do I go about it?
you are trying to remember the last activity and then starting next specific activity.
This is the way to do it
change this
Intent intent = new Intent(Login.this, Class.forName(activity));
startActivity(intent);
finish();
to this-
Intent intent = getIntent();
String lastActivity = intent.getStringExtra("activity"); // lastActivity
if (lastActivity.equalsIgnoreCase("FirstActivity")) {
Intent intent = new Intent(Login.this, FirstActivity.class);
startActivity(intent);
finish();
} else if (lastActivity.equalsIgnoreCase("SecondActivity")) {
Intent intent = new Intent(Login.this, SecondActivity.class);
startActivity(intent);
finish();
}
create common method to optimize your code
You need to provide the fully qualified class name. Instead of "FirstActivity" you need to pass "my.fully.qualified.class.name.FirstActivity" where you provide the fully qualified class name.

Explicit intent and action performed

I am wondering how does the following code works (it starts an activity). I don't get how does the system figure out what is the action that should be preformed. No action is specified for the Intent. I would have expected a set_action.
Intent i = new Intent(this, ActivityTwo.class);
startActivity(i);
I am wondering how is it possible to have an Intent which action is not explicitely specified considering what I read in the documentation:
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.
I hope it make sense. Thank you for your help.
There are two types of intents in Android, implicit intents and explicit intents.
1) Implicit intent
You set an Action, Category and data type and let Android find an activity that fits the specified characteristics (has an intent filter with the specified Action, Category and Data Type).
2) Explicit intent
As the docs says:
An explicit intent is one that you use to launch a specific app
component, such as a particular activity or service in your app. To
create an explicit intent, define the component name for the Intent
object—all other intent properties are optional.
You tell which activity/service to open explicitly. So the system doesn't need to figure out which one to open, you're already telling it to open a specific Activity/Service.
The one you read in the docs is an implicit intent, this is the explicit one:
Intent i = new Intent(this, ActivityTwo.class);
There are multiple constructor functions for Intent class.
If checking the source code for public Intent(Context packageContext, Class cls), the following info is mentioned:
Create an intent for a specific component. All other fields (action, data,
* type, class) are null, though they can be modified later with explicit
* calls. This provides a convenient way to create an intent that is
* intended to execute a hard-coded class name, rather than relying on the
* system to find an appropriate class for you;

Different types of Android Intents

I have recently started a new Android project and I'm working off the previous developer's code. I'm relatively new to Android and I've come across something that I'm unsure of.
What is the difference between this:
Intent intent = new Intent("com.example.project.MENU");
and this:
Intent intent = new Intent(this, DisplayMenu.class);
I understand what the 2nd code snippet does, I just can't get my head around as to what the first one is doing? Is it referencing the file in the package? Thanks
The first one is an implicit intent, while the second is an explicit intent.
The first one fired an Intent for the action com.example.project.MENU. If you look inside you project AndroidManifest.xml you can see some <intent-filter> balise. This baslise register activity, service or broadcast receiver to different actions.
This mecanism can be used to allow third party app to launch some of your activities.
You can see more on this tutorial http://www.vogella.com/tutorials/AndroidIntent/article.html#intenttypes
Basically an Intent carries some information that are used by the system in order to determine which component should be called for executing the action.
These information are:
Component name: the name of the component that should be launched. (If present the Intent is Explicit)
Action: it specifies the generic action that should be executed (es. ACTION_VIEW, ACTION_SEND). It determines how the rest of the intent is strucutred.
Data: represents the URI that refers to the object that should be associated with the action. For example with the action ACTION_EDIT, the Data should contain the URI of the document that you want modify.
Category: Additional infromation (for example if you want that your app is shown in the launcher you can use CATEGORY_LAUNCHER)
Extras: keys-values pairs that carries additional information
Flags: it is like a metadata that specify how the intent should be managed by the system.
The Intent class provides a lot of different constructors.
The first one you asked for is public Intent (String action)
So, this sets the Action, and lets null all other fields.
The second one public Intent (Context packageContext, Class<?> cls) creates an intent for a specific component by its Component name. All other fields are null. This is a Explicit Intent, since you declare exactly which component should receive it.
The first one is used when you need to call Intent from System
such as Open Camera, Gallery, or Share something to other Application
for example
// this one call Camera to Capture Image
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// this one call gallery to let you select image
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
and That MediaStore.something here is just a Path to the system
for example
MediaStore.ACTION_IMAGE_CAPTURE = "android.media.action.IMAGE_CAPTURE"
Intent.ACTION_PICK = "android.intent.action.PICK"
The first type of intent is mostly used if you want to open another application from your application while the second type of intent is used to open another activity in your application.

ADT: Avoid duplicating code in package with dependency on another deployed package?

When I have e.g. a custom service and a custom activity in the same ADT project, then I can use this in the service, to start my activity:
Intent i = new Intent(context, MyCustomActivity.class);
startActivity(i);
However when I have the service and activity in separate projects, then I cannot do this since I do not have a direct reference to MyCustomActivity.class. This is problematic: I do not wish to include a JAR just to be able to fix that broken reference, since I assume this will increase the package size and create redundant data on the device (i.e. activity code is duplicated between the service and activity packages). So instead, I use this (perhaps there are other options?):
Intent i = new Intent("com.mypackage.myStringActionName");
startActivity(i); //is this a broadcast?
OR
Intent i = new Intent("com.mypackage.myStringActionName");
sendBroadcast(i);
...But I don't really like sending broadcasts when all I want is to direct the intent to a single activity to tell it to start.
So, what other ways are there to go about avoiding duplication (in ADT)? Or else a better way to send direct intents?
you can try this:
Intent i = new Intent();
i.setComponent(new ComponentName(packageName, classname));
startActivity(i);
the className must contains the packageName and main activity name

Use of Context in Explicit Intents

What is the difference between starting ActivityB from ActivityA using
1. startActivity(this, ActivityB.class);
versus
2. startActivity(getApplicationContext(), ActivityB.class);
I typically see 1. used more often in examples, but I haven't come across a reason for why this is the case.
Reference to Activity as a Context (this) might become obsolete if your Activity goes through configuration changes, like rotation, and is destroyed and created again. Context recieved by getApplicationContext(), however, persists through lifetime of the process.
However, It seems to me it only is an issue when you bind Activity to Service or other similar scenario, so it's safe to use this when you use it in intent to start another Activity.
There is no difference. According source code of Intent and ComponentName - only thing, that used form context - is getting package name by context.getPackageName(). Package name is the same for Activity.this and Activity.getApplicationContext(), so there is no difference.
I assume you are actually asking about the difference between
startActivity(new Intent(this, ActivityB.class));
and
startActivity(new Intent(getApplicationContext(), ActivityB.class));
There is no difference. Android needs the ComponentName (package name and class). The context is used to determine the package name.

Categories

Resources