Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Introducing Intents2:23 with Ben Jakuben
Activities (and many other things in Android) are started using an object called an Intent. The intent of this Intent is to start another Activity. :)
So, when you as a person intend to do a task, it means that you've thought about 0:00 what you wanna do, and you're intent is to do it. 0:04 You just need to start and maybe you need a little help. 0:07 In Android, it's the same basic idea, 0:10 but it's wrapped up in an intent object that we can use in code. 0:12 An intent is what we use when we intend to do something in an Android app. 0:16 We usually use them to start a new task, and 0:20 that task can be something like starting a new activity, or 0:22 maybe handing something off to another app like a video player, or a messaging app. 0:25 Back in our code, let's declare a new intent object named, simply, intent. 0:30 We'll set it equal to a new Intent, with parentheses, and add a semicolon. 0:35 Now, there are a few different constructors we can use. 0:40 So, if we go back between the parentheses, we can hit Cmd+P on a Mac, or 0:43 Ctrl+P on Windows, to bring up some help. 0:47 We're going to start a new activity, which is defined in a class file. 0:50 Thus, we want the fourth option shown here, that accepts the current context, 0:54 and a class as a parameter. 0:58 Remember that context is really important in Android. 1:01 We discussed it briefly before, but it is essentially the specific context or 1:04 environment within which our code is running. 1:08 This code is in an activity, and 1:11 the activity class is a sub class of the context class. 1:13 So we can use the current activity as our context. 1:16 This is easily achieved with the this keyword. 1:19 And in this case, it's now referring to this current class. 1:22 There are other ways to access the context. 1:25 For example, we could type getApplicationContext, 1:27 which is a method available in the activity class. 1:30 But let's undo that, go with this, and now for 1:33 the second parameter, we want the activity class that we want to start. 1:36 So we type StoryActivity and then we type .class to reference the actual class. 1:41 When our app is actually running, it needs the class object 1:47 rather than simply the name which is why we use this class property. 1:50 Okay, next, just one more line of code. 1:53 We need to express this intention somehow. 1:55 This is often done using the method from the activity base class called, 1:58 startActivity. 2:01 And look at that. 2:04 It takes an intent as its parameter. 2:05 Type that and try it out, and see what happens. 2:07 Okay, we can type a name again. 2:12 Hit enter. 2:17 Start the adventure. 2:18 All right, and we're taken to our new blank story activity. 2:19
You need to sign up for Treehouse in order to download course files.Sign up