Intents in Android: Introduction

Intent is an object that an android component can use to communicate with the Android OS.  There are various components in android, these are:

  • Activity
  • Services
  • Broadcast receivers ,and
  • Content providers.

Intents are multi-purpose communication tools, and the Intent class provides different constructors depending on what we are using the intent to do.

For example, usually, we use intents to tell the ActivityManager which child activity to start from a parent activity, so for this purpose we use following constructor:

public Intent(Context packageContext, Class<?>  cls)

Whenever we want an activity to start a second activity, we use intent. We can think of intent as “intent to do something”. It’s a type of message that allows us to bind separate objects (such as activities) together at runtime. If one activity wants to start a second activity, it does it by sending intent to Android. Android will start the second activity and pass it the intent.

We can create and send an intent using just a couple of lines of code. We start by creating the intent like this:

Intent intent = new Intent(ParentActivity.this, ChildActivity.class);

  • The first parameter tells Android which object the intent is from
  • We can use the word this to refer to the current activity.
  • The second parameter is the class name of the activity that needs to receive the intent.

Once we’ve created the intent, we pass it to Android like this:

startActivity(intent);

This tells Android to start the activity specified by the intent (We discuss this entire process in my upcoming post)

Types of Intents

We typically use intents in two ways:

  • Explicit Intents
  • Implicit Intents

Explicit Intents:

When we create Intent with a Context and a Class object, we are creating an explicit intent. We use explicit intents to start activities from within our application.

Implicit Intents

It may seem strange that two activities within our application must communicate via the ActivityManager, which is outside of our application. However, this pattern makes it easy for an activity in one application to work with an activity in another application. When an activity in our application wants to start an activity in another application, we create an implicit intent.

Use of Intents

  • In perhaps its most common use, an Intent object allows us to switch between activities.
  • But, of course, activities are classes. So, what happens to their data when we switch between them? Intents handle this problem for us, as well, by allowing us to pass data between activities.
  • Intents aren’t just about wiring up the activities of our app. They also make it possible to interact with other apps. For example, we could provide a link in our app for the user to send e-mail, make a phone call, interact with social media, and open a web page in a browser and have the e-mail, dialer, browser, or relevant social media app do all the work.

This is my first post on Intents (an introductory post), which will get you stated with Intent basics. But I hope you get the brief idea about what is Intents and why we use them. In my upcoming post we discuss how to start a child activity from a parent activity (Switching between activities).

Thanks a lot!!

Manali: A Euphoric Hill Station in Himachal

Himachal Pradesh is famous for his hilly locations, mountains, valleys and attracts tourists throughout the season with his natural novel surroundings . One of the most popular holiday destinations attracted by tourists and travelers is Manali. It is located in Kullu District of Himachal and about 250 km from the Shimla. This blissful city is also known as Valley of Gods or Adobe of Manu. We can enjoy and explore the felicity place in summers as well as in winters.

The place offers an adventurous ride for d sports lover enthusiasts in the form of Trekking, Skiing, River rafting, Paragliding, Fishing and Camping at hills etc.   Manali reflects natural beauty with exquisite views of the snow covered mountains, flower gardens and orchards full of green and red apples. Solang Valley is one of tourist magnet and popularly known as a winter sports location. Similarly Nehru kund is there, a clear water spring. Kothi village offers mesmerizing views of a deep gorge through which river Beas flow. Along with these aesthetic sites seeing, Rahalla falls completes a hilly experience for tourists.

Manali also offer a blend of culture and mythology. The Hadimba temple was built in 1533 A.D. , which is dedicated to wife of Bhima ( One of the Pandavas in Mahabharat) , Hadimba. Similarly, the manu temple is dedicated to the sage and lawgiver is located in old Manali. There is a temple dedicated to Lord Rama and sage Vasishta ,called the Vasishta Temple which is popular for its hot springs. There are few more old temples dedicated to Shiva and Sandhya Gaytri   in nearby town of Jagatsukh.

Old Manali is full of popular roadside eateries, hotels, cafes , restaurant and shops and the city markets from where one can buy woollens to local produce like jams preserves, baked goodies and Souvenirs.

Apart from all these, Manali has various other traveller attractions like Rotang Pass, the castle, Lahaul Valley, SpitiVillage, Chandertal Lake, Kothi, Gulaba, Pandoh Dam, Jagannath Devi temple, Manali Zoo, River Beads, Maanli wildlife etc.

Best season to plan for Manali is May to October, but we could also enjoy winters too. There are numerous good hotels, cottages, resorts available there like Club Mahindra, holiday Cottage, Snow Valley Resorts, Tree Hill Cottage, Shingar Regency etc.

Manali is readily accessible from Delhi , Shimla, Chandigarh and Ambala. We could plan through flights to Bhunter which is just 50 km away from Manali. We could easily plan our trip through travel organizers like Make my trip, Yatra, Goibibo etc.

await Operator Keyword in C#

The await operator is applied to a task in an asynchronous method to suspend the execution of the method until the awaited task completes. The task represents ongoing work.

The asynchronous method in which await is used must be modified by the async keyword. Such a method, defined by using the async modifier, and usually containing one or more await expressions, is referred to as an async method.

The task to which the await operator is applied typically is the return value from a call to a method that implements the Task-Based Asynchronous Pattern.

The following example illustrates the use of await in an async method, WaitAsynchronouslyAsync. Contrast the behavior of that method with the behavior of WaitSynchronously. Without an await operator applied to a task, WaitSynchronously runs synchronously despite the use of the async modifier in its definition and a call to Thread.Sleep in its body.

private async void button1_Click(object sender, EventArgs e)
{
    // Call the method that runs asynchronously.
    string result = await WaitAsynchronouslyAsync();

    // Call the method that runs synchronously.
    //string result = await WaitSynchronously ();

    // Display the result.
    textBox1.Text += result;
}
// The following method runs asynchronously. The UI thread is not
// blocked during the delay. You can move or resize the Form1 window 
// while Task.Delay is running.
public async Task WaitAsynchronouslyAsync()
{
    await Task.Delay(10000);
    return "Finished";
}
// The following method runs synchronously, despite the use of async.
// You cannot move or resize the Form1 window while Thread.Sleep
// is running because the UI thread is blocked.
public async Task WaitSynchronously()
{
    // Add a using directive for System.Threading.
    Thread.Sleep(10000);
    return "Finished";
}

One important point about awaitables is this: it is the type that is awaitable, not the method returning the type. In other words, you can await the result of an async method that returns Task because the method returns Task, not because it’s async. So you can also await the result of a non-async method that returns Task:

public async Task MethodAsync()
{
  // Note that this is an async method, so we can use await in here.
  await ...
}
public Task NonAsyncMethod()
{
  // Note that this is not an async method, so we can't use await in here.
  ...
}
public async Task ComposeAsync()
{
  // We can await Tasks, regardless of where they come from.
  await NewStuffAsync();
  await MyOldTaskParallelLibraryCode();
}

async Modifier Keyword in C#

The async modifier indicates that the method, lambda expression, or anonymous method that it modifies is asynchronous. Such methods are referred to as async methods.

public async Task DoSomethingAsync()
{
    // . . . .
}

If you’re new to asynchronous programming, you can find an introduction of Asynchronous Programming in .NET using C# here.

An async method provides a convenient way to do potentially long-running work without blocking the caller’s thread. The caller of an async method can resume its work without waiting for the async method to finish.

Typically, a method modified by the async keyword contains at least one await expression or statement.

string Content = await getContentTask;

The method runs synchronously until it reaches its first await expression, at which point the method is suspended until the awaited task is complete. In the meantime, control returns to the caller of the method, as the example later in this topic shows.

If a method that’s modified by an async keyword doesn’t contain an await expression or statement, the method executes synchronously. A compiler warning alerts you to any async methods that don’t contain await because that situation might indicate an error.

When async modifies a method, a lambda expression, or an anonymous method, async is a keyword. In all other contexts, async is interpreted as an identifier. This distinction makes async a contextual keyword.

private async void DownloadFileButton_Click(object sender, EventArgs e)
{
  // Since we asynchronously wait, the UI thread is not blocked by the file download.
  await DownloadFileAsync(fileNameTextBox.Text);

  // Since we resume on the UI context, we can directly access UI elements.
  resultTextBox.Text = "File downloaded!";
}

Return Types

An async method can have a return type of Task or void. The method cannot declare any ref or out parameters, although it can call methods that have such parameters.

You specify Task as the return type of an async method if the return statement of the method specifies an operand of type TResult. You use Task if no meaningful value is returned when the method is completed. That is, a call to the method returns a Task, but when the Task is completed, any await expression that’s awaiting the Task evaluates to void.

The void return type is used primarily to define event handlers, where a void return type is required. The caller of a void-returning async method can’t await it and can’t catch exceptions that the method throws.

Asynchronous Programming in .NET

“Performance” is a term that is used a lot when talking about apps, but it’s actually a pretty vague term. There are at least two aspects of performance that most people think about: app launch time and throughput. Both of these can be measured and described with actual numbers. The true test of an app, however, is end-user perception.

Asynchronous programming is a means of parallel programming in which a unit of work runs separately from the main application thread and notifies the calling thread of its completion, failure or progress. You may be wondering when you should use asynchronous programming and what are its benefits and problem points.

The main benefits one can gain from using asynchronous programming are improved application performance and responsiveness. One particularly well suited application for the asynchronous pattern is providing a responsive UI in a client application while running a computationally or resource expensive operation.

Async and Await

The async and await keywords in C# are the heart of asynchronous programming. By using those two keywords, you can use resources in the .NET Framework or the Windows Runtime to create an asynchronous method almost as easily as you create a synchronous method. Asynchronous methods that you define by using async and await are referred to as async methods.

The following example shows an async method. Almost everything in the code should look completely familiar to you.

async Task AccessTheWebAsync()
{
    HttpClient client = new HttpClient();
    Task getStringTask = client.GetStringAsync("http://www.haidermrizvi.com");
    DoIndependentWork();
    string urlContents = await getStringTask;
    return urlContents.Length;
}

GetStringAsync returns a Task. That means that when you await the task you’ll get a string (urlContents).

The await operator suspends AccessTheWebAsync.

AccessTheWebAsync can’t continue until getStringTask is complete.
Meanwhile, control returns to the caller of AccessTheWebAsync.
Control resumes here when getStringTask is complete.
The await operator then retrieves the string result from getStringTask.

The following characteristics summarize what makes the previous example an async method.

  • The method signature includes an async modifier.
  • The name of an async method, by convention, ends with an “Async” suffix.
    • The return type is one of the following types:

    • Task if your method has a return statement in which the operand has type TResult.
    • Task if your method has no return statement or has a return statement with no operand.
      • The method usually includes at least one await expression, which marks a point where the method can’t continue until the awaited asynchronous operation is complete. In the meantime, the method is suspended, and control returns to the method’s caller. The next section of this topic illustrates what happens at the suspension point.

      Summary

      The new async and await keywords enable you to provide significant user experience improvements in your apps without much effort on your part. This term does not mean multithreaded code. By default, code written with async and await is single-threaded. But threaded code works well here.