Intents in xamarin android

Xamarin: Android Activities, Context, Intents and Views

If you are coming from C#/Silverlight, Android can be a little diffusing. Android does not have the same structure than a Windows or Windows Phone app.

Activities

Android has Activities. Activities are the key classes of Android were all actions take place. Unlike other apps or programs, you do not have a “Main” program that is your starting point when launched.

In Android, the starting point is an Activity. The Activity needs to be declared as the starting point. When you start a new project in Xamarin, an Activity called “MainActivity” gets created automatically.

This Activity has some attributes:

The ‘Label’ attribute is what you will see in the Title bar when launching the app. The attribute ‘MainLauncher=true’ tells the application to start from here. Think of this as your MainPage.xaml.cs in a Windows Phone app.

Every Activity has its own OnCreate event, where you can put all your starting, button handlers, stylings etc. in.

But an Activity still has more. It has events like OnStart(), OnPause(), OnRresume() and OnStop() and OnDestroy() and OnRestart(). I won’t get into deep this time, as the Xamarin documentation has already a very good overview of those events: http://docs.xamarin.com/guides/android/application_fundamentals/activity_lifecycle/.

Those events are important to understand for a lot of your application logic, like:

  • saving data that has to be persistent
  • starting and pausing animations
  • register and unregister external events
  • fetch data that are passed from other Activities
  • and more (we will cover some of them in my further posts)

I absolutely recommend to go to the link above to read and understand those events.

Context

The Context is often needed in an Android application and allows your code to be run within an Activity.

The Context allows you for example:

  • to access Android services,
  • to access Application resources like images or styles,
  • to create views
  • to assign gestures to an Activity

Without Context, often code does not get accepted by the IDE or makes your code getting ignored while running the app. Luckily, all methods that I used so far have been telling me if they want a Context, so you need only learn to find out if you need Context for the Activity resources or Application resources.

Intents

But what if we want to have another page (like a separate about page for example)? How can we navigate between pages or call external functions?

This is what Intents are for. Intents are sending messages through the application if another function needs to be started, like the launch of a second page. Within these intents, we have declare the actions that the app needs to do, and if we need a callback, this will also be passed with an Intent.

Let’s hold this high level, here are some lines of code that navigate to a second page (Activity):

With this code, we are creating an new Intent with Context to our current running Activity to launch the SecondActivity.

To send data between Activities, we use the PutExtra() method of Intents:

Of course, we need also some code to read the passed data on our second page:

We could now use this data on our second page by assigning it to a control or function.

Passing data between activities works similar to passing QueryStrings in NavigationsService.Navigate() method on WindowsPhone, so you should get familiar with it very fast.

Views

The last part that is very important are Views. In a View you declare how the Activity looks like. Think of it as your MainPage.xaml page in a Windows Phone app.

Views can be very different, too. Let’s start with the simple View. In our getting started project, we also have a Layout file that holds our first View:

The View has a main LinearLayout which is acts as ContentPanel. All other controls like Buttons, TextViews etc. are going into this. There are a lot of properties that can be set, we’ll leave it this easy for now. If you want to know more about those properties, you can have a look at the Android documentation here: http://developer.android.com/guide/topics/ui/declaring-layout.html

This part is totally the same as with the one matching part in the Android SDK, so you will need to get familiar with the Android documentation as well.

To make a View visible, we need to assign it to an Activity. In our sample app, we are doing this with this line of code in our OnCreate event:

Читайте также:  Джойстик денди для андроид

This is the easy way for Views. But there are more complex Views in Android, too.

Views are also used in ListViews, where you declare the look of the items and the list in a Layout file, or also if you use the ActionBar with a tab navigation, and also in the menu of an ActionBar. I will cover all of these in my further blog posts, as we also need Adapters to get data binded to Views.

I hope you this post helps you to understand the high level structure of an Android application.

Источник

Creating a Service

Xamarin.Android services must obey two inviolable rules of Android services:

Another requirement of Android services is that they must be registered in the AndroidManifest.xml and given a unique name. Xamarin.Android will automatically register the service in the manifest at build time with the necessary XML attribute.

This code snippet is the simplest example of creating a service in Xamarin.Android that meets these two requirements:

At compile time, Xamarin.Android will register the service by injecting the following XML element into AndroidManifest.xml (notice that Xamarin.Android generated a random name for the service):

It is possible to share a service with other Android applications by exporting it. This is accomplished by setting the Exported property on the ServiceAttribute . When exporting a service, the ServiceAttribute.Name property should also be set to provide a meaningful public name for the service. This snippet demonstrates how to export and name a service:

The AndroidManifest.xml element for this service will then look something like:

Services have their own lifecycle with callback methods that are invoked as the service is created. Exactly which methods are invoked depends on the type of service. A started service must implement different lifecycle methods than a bound service, while a hybrid service must implement the callback methods for both a started service and a bound service. These methods are all members of the Service class; how the service is started will determine what lifecycle methods will be invoked. These lifecycle methods will be discussed in more detail later.

By default, a service will start in the same process as an Android application. It is possible to start a service in its own process by setting the ServiceAttribute.IsolatedProcess property to true:

The next step is to examine how to start a service and then move on to examine how to implement the three different types of services.

A service runs on the UI thread, so if any work is to be performed which blocks the UI, the service must use threads to perform the work.

Starting A Service

The most basic way to start a service in Android is to dispatch an Intent which contains meta-data to help identify which service should be started. There are two different styles of Intents that can be used to start a service:

Explicit Intent – An explicit Intent will identify exactly what service should be used to complete a given action. An explicit Intent can be thought of as a letter that has a specific address; Android will route the intent to the service that is explicitly identified. This snippet is one example of using an explicit Intent to start a service called DownloadService :

Implicit Intent – This type of Intent loosely identifies the type of action that the user wishes to perform, but the exact service to complete that action is unknown. An implicit Intent can be thought of as a letter that is addressed «To Whom It May Concern. «. Android will examine the contents of the Intent, and determine if there is an existing service which matches the intent.

An intent filter is used to help match the implicit intent with a registered service. An intent filter is an XML element that is added to AndroidManifest.xml which contains the necessary meta-data to help match a Service with an implicit intent.

If Android has more than one possible match for an implicit intent, then it may ask the user to select the component to handle the action:

Starting in Android 5.0 (AP level 21) an implicit intent cannot be used to start a service.

Where possible, applications should use explicit Intents to start a service. An implicit Intent does not ask for a specific service to start – it is a request for some service installed on the device to handle the request. This ambiguous request can result in the wrong service handling the request or another app needlessly starting (which increases the pressure for resources on the device).

Читайте также:  Make an android apple

How the Intent is dispatched depends on the type of service and will be discussed in more detail later in the guides specific to each type of service.

Источник

Xamarin – Android Intents

We’ve already seen what are Activities, the most basic pieces of every Android app and today’s topic is associated with it. We’re going to see how to communicate between Activities (or Application Blocks) using Intents.

Table of Contents

Android Application Blocks

Android apps are composed of Application Blocks, which are special kind of Android classes consisting several elements bundled together, including:

Everything that comes in such package is coordinated by AndroidManifest.XML file. Especially, in this XML file (or by using various attributes on Activity class) it’s possible to register our Application Block to be “callable” by the others.

We’ll see more details in a while, but generally your app block is “callable” when it can be used by the other apps – probably you’ve already seen Application Chooser screen on your Android phone, e.g. when you wanted to open downloaded movie and the system asked you which video player you want to use. The same can be done with your own app – if you’re developing a dialer app, you can register it to be callable for ACTION_DIAL Activity Action. Then, as soon as any other app uses Intent to make a phone call (which we’ll see in this post), Application Chooser appears and your app will be one of the possible ones to use for making this phone call.

What is an Intent ?

Android system is designed to be loosely-coupled. Moreover, there is a principle of least privilege introduced in system’s architecture. It means that each app has access only to Blocks which it requires to work. Different Blocks don’t know much about each other (even if defined within the same application). Here’s where an Intent comes into play. Application Blocks use Intents to asynchronously communicate with each other.

In general, you can think of an Intent literally – it’s the intent (or a will) to do something. By sending Intents between different components, we can coordinate complex actions such as launching email app to send a message, using Location for obtaining user’s coordinates or navigating between application’s screens.

For me, we can think of Intents and their usage from two perspectives:

  1. Intent as anintent – a will to do something. In this case, you use Intent to execute some action. When creating a new Intent you need to tell it what you want to do and give it necessary parameters for such operation (e.g. for send email action, you need to provide email address parameter)
  2. Intent as amessage – bidirectional information having sender, recipient and potentially some content. This can be for instance navigating to a new screen (Activity), where sender is the original Activity, recipient is the destination Activity to be opened and the content may consist some parameters to pass between two screens.

We’ll now see those two approaches in details.

Intent as an intent

In order to trigger another (external) action, e.g. camera recording or email sending, we can create an Intent and start a new Activity. Let’s see it by the example I implemented in MoneyBack – I added an additional ListActivity ( PeopleListActivity class) which is the list of people added to app’s database. When a person on the list is clicked, I create an Intent in order to call his/her phone number as the following code presents:

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

private void ListView_ItemClick ( object sender , AdapterView. ItemClickEventArgs e )
<
var person = _peopleList [ e . Position ];
var uri = Android . Net . Uri . Parse ( » tel: » + person . PhoneNumber );
var intent = new Intent ( Intent . ActionDial , uri );
StartActivity ( intent );
>

What those 4 lines of code do, is when tapping an entry from the list:

MoneyBack – people list Activity

it opens the phone dialer app with selected person’s phone number to call:

Phone Dialer opened

NOTE: If I had more than one dialer app installed (if the other dialer app has itself registered as receiver for ACTION_DIAL, of course) Android would ask me to choose which app I want to use.

How did that happen? First actually interesting line of code is the following one:

It creates a new Intent, giving to it – as we said in the previous paragraph – two things:

  • what we want to do – it this case, we set action to Intent.ActionDial , which corresponds to ACTION_DIAL Activity Action
  • operation’s parameters – in our case there is just one parameter, which is the phone number in URI format
Читайте также:  Как настроить поисковик по умолчанию андроид

For each type of Activity Action you want to trigger, you can find what parameters it needs in official Android Documentation.

In the end, we just need to finally start a new Activity with the Intent we just created:

and we’re all done.

Intent as a message

Now, let’s think about our app as a set of Activities, which are loosly-coopled. We have MainActivity class, which represents the main screen of our app. We’ve also built another Activity, which we want to open from the main one. In that case, we already see everything which fits into intent-as-a-message template – two Activities want to “talk” with each other.

In MoneyBack I changed the MainActivity to look as follows:

MoneyBack – MainActivity

When clicking on “People Management” button, I’d like another Activity (represented by PeopleActivity class) to open.

In order to achieve that, MoneyBack executes the following code when clicking on the button:

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

private void _btnPeople_Click ( object sender , EventArgs e )
<
var intent = new Intent ( this , typeof ( PeopleActivity ));
StartActivity ( intent );
>

What you can see here, is that we create a new Intent that takes two parameters:

  • Context – being the class storing information about current application’s/Activity’s state, from the place where the Intent is created; in our case, we set it to this , which is the calling Activity class reference. Context is our message’s sender
  • Type – this is our message’s recipient; in our case it’s the Type of destination Activity we want to start ( PeopleActivity )

NOTE: Notice that we have no content provided in that case.

Then we just start the Activity as in the previous example and another screen appears:

MoneyBack – PeopleActivity

If the back button is now pressed, it goes back to previous (calling) Activity. That’s how the Activities stack is built, by the way 😉

Passing additional content using Intent as a message

I mentioned we can also pass some additional data (message’s content) within an Intent. In the above example we didn’t do it, because there is no sense to pass anything from MainActivity to PeopleActivity for now. However, if we’d like to do that, we can add a simple modification to button’s pressing code in MainActivity :

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

private void _btnPeople_Click ( object sender , EventArgs e )
<
var intent = new Intent ( this , typeof ( PeopleActivity ));
var msgContent = » Hello! This is a secret sent from MainActivity! Don’t tell anyone! » ;
intent . PutExtra ( » secret_message » , msgContent );
StartActivity ( intent );
>

As you see, I used PutExtra method of the Intent class to insert msgContent into Intent’s simple key-value Bundle Dictionary called Extras, using “secret_message” string as a key. Then, in the destination Activity’s OnCreate method we can retrieve such value back using Intent.Extras.GetString (for String data type) method:

This kind of data-passing between Activities using Intent.Extras should be used only for simple, mostly key-value data transferring. There are other methods for passing/storing more complex data in an app or between different applications.

Summary

Today we’ve seen what is an Intent, how to use it to trigger external actions such as calling a phone number, sending email etc., but also how to use it to handle navigation between Activities. We’ve also passed key-value data between two Activities using Intent.Extras .

Intent, as well as Activity, is one of the fundamental concepts of Android. It’s essential to know how Intents work, how they relate to Activities, Services (which we’ll also cover one day) and Application Blocks. I hope you’ll find it useful 😉

In this short post, I’m going to show you a very handy feature of Android Debug…

Today we’re going to take a look at Android’s most basic and in the same…

In this post, we’re going to see how to provide a nice Android UI control…

Источник

Оцените статью