- Android — Event Handling
- Event Listeners & Event Handlers
- Event Listeners Registration
- Touch Mode
- Focus
- onTouchEvent()
- Event Handling Examples
- Event Listeners Registration Using an Anonymous Inner Class
- Exercise
- How to detect Android application open and close: Background and Foreground events.
- Detecting App Lifecycle Evnts
- Backgrounding
- Foregrounding
- Implementing a Foreground and Background Handler
- AppLifecycleHandler
- Update: Using Android Architecture Components
- Get Started – Android
- Before You Start
- Step 1: Configure Your Facebook App
- Step 2: Link Your Facebook Ad Account with Your App
- Step 3: Integrate the Facebook SDK in Your Android App
- Step 4: Add App Events
- Automatically Logged Events
- Disable Automatically Logged Events
- Disable Automatic SDK Initialization
- Disable Collection of Advertiser IDs
- Manually Log Events
- Event Parameters
- Step 5: Test Your Event Logging
- Enabling Debug Logs
- Learn More
- Example Apps
Android — Event Handling
Events are a useful way to collect data about a user’s interaction with interactive components of Applications. Like button presses or screen touch etc. The Android framework maintains an event queue as first-in, first-out (FIFO) basis. You can capture these events in your program and take appropriate action as per requirements.
There are following three concepts related to Android Event Management −
Event Listeners − An event listener is an interface in the View class that contains a single callback method. These methods will be called by the Android framework when the View to which the listener has been registered is triggered by user interaction with the item in the UI.
Event Listeners Registration − Event Registration is the process by which an Event Handler gets registered with an Event Listener so that the handler is called when the Event Listener fires the event.
Event Handlers − When an event happens and we have registered an event listener for the event, the event listener calls the Event Handlers, which is the method that actually handles the event.
Event Listeners & Event Handlers
Event Handler | Event Listener & Description | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
onClick() |
Step | Description |
---|---|
1 | You will use Android studio IDE to create an Android application and name it as myapplication under a package com.example.myapplication as explained in the Hello World Example chapter. |
2 | Modify src/MainActivity.java file to add click event listeners and handlers for the two buttons defined. |
3 | Modify the detault content of res/layout/activity_main.xml file to include Android UI controls. |
4 | No need to declare default string constants.Android studio takes care default constants. |
5 | Run the application to launch Android emulator and verify the result of the changes done in the aplication. |
Following is the content of the modified main activity file src/com.example.myapplication/MainActivity.java. This file can include each of the fundamental lifecycle methods.
Following will be the content of res/layout/activity_main.xml file −
Here abc indicates about tutorialspoint logo
Following will be the content of res/values/strings.xml to define two new constants −
Following is the default content of AndroidManifest.xml −
Let’s try to run your myapplication application. I assume you had created your AVD while doing environment setup. To run the app from Android Studio, open one of your project’s activity files and click Run icon from the toolbar. Android Studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
Now you try to click on two buttons, one by one and you will see that font of the Hello World text will change, which happens because registered click event handler method is being called against each click event.
Exercise
I will recommend to try writing different event handlers for different event types and understand exact difference in different event types and their handling. Events related to menu, spinner, pickers widgets are little different but they are also based on the same concepts as explained above.
Источник
How to detect Android application open and close: Background and Foreground events.
Dec 17, 2017 · 4 min read
This question seems to come up a lot. Especially if you are just starting out with Android developme n t. It’s simply because there is nothing obvious built into the Android SDK enabling developers to hook into application lifecycle events. Activities and Fragments have all the callbacks under the sun to detect lifecycle change, but there is nothing for the whole application. So how do you detect when a user backgrounds and foregrounds your app. This is an example of how your could detect Application lifecycle events. Feel free to adjust and enhance it to suit your needs, but this idea should be enough to work for most applications with one caveat, it will only work for Android API level 14+(IceCreamSandwich 🍦🥪).
Detecting App Lifecycle Evnts
Backgrounding
ComponentCallbacks2 — Looking at the documentation is not 100% clear on how you would use this. However, take a closer look and you will noticed the onTrimMemory method passes in a flag. These flags are typically to do with the memory availability but the one we care about is TRIM_MEMORY_UI_HIDDEN. By checking if the UI is hidden we can potentially make an assumption that the app is now in the background. Not exactly obvious but it should work.
Foregrounding
ActivityLifecycleCallbacks — We can use this to detect foreground by overriding onActivityResumed and keeping track of the current application state (Foreground/Background).
Implementing a Foreground and Background Handler
First, lets create our interface that will be implemented by a custom Application class. Something as simple as this:
Next, we need a class that is going to implement the ActivityLifecycleCallbacks and ComponentCallbacks2 we discussed earlier. So lets create an AppLifecycleHandler and implement those interfaces and override the methods required. And lets take an instance of the LifecycleDelegate as a constructor parameter so we can call the functions we defined on the interface when we detect a foreground or background event.
We outlined earlier that we could use onTrimMemory and the TRIM_MEMORY_UI_HIDDEN flag to detect background events. So lets do that now.
Add this into the onTrimMemory method callback body
So now we have the background event covered lets handle the foreground event. To do this we are going to use the onActivityResumed. This method gets called every time any Activity in your app is resumed, so this could be called multiple times if you have multiple Activities. What we will do is use a flag to mark it as resumed so subsequent calls are ignored, and then reset the flag when the the app is backgrounded. Lets do that now.
So here we create a Boolean to flag the application is in the foreground. Now, when the application onActivityResumed method is called we check if it is currently in the foreground. If not, we set the appInForeground to true and call back to our lifecycle delegate ( onAppForegrounded()). We just need to make one simple tweak to our onTrimMemory method to make sure that sets appInForeground to false.
Now we are ready to use our AppLifecycleHandler class.
AppLifecycleHandler
Now all we need to do is have our custom Application class implement our LifecycleDelegate interface and register.
And there you go. You now have a way of listening to your app going into the background and foreground.
This is only supposed to be used as an idea to adapt from. The core concept using onTrimMemory and onActivityResumed with some app state should be enough for most applications, but take the concept, expand it and break things out it to fit your requirements. For the sake of brevity I won’t go into how we might do multiple listeners in this post, but with a few tweaks you should easily be able to add a list of handlers or use some kind of observer pattern to dispatch lifecycle events to any number of observers. If anyone would like me to expand on this and provide a multi listener solution let me know in the comments and I can set something up in the example project on GitHub.
Update: Using Android Architecture Components
Thanks to Yurii Hladyshev for the comment.
If you are using the Android Architecture Components library you can use the ProcessLifecycleOwner to set up a listener to the whole application process for onStart and onStop events. To do this, make your application class implement the LifecycleObserver interface and add some annotations for onStop and onStart to your foreground and background methods. Like so:
Источник
Get Started – Android
This guide shows you how to add App Events to your new or existing app by integrating the Facebook SDK then logging these events.
Before You Start
Step 1: Configure Your Facebook App
Go to the App Dashboard, click My Apps, and create a new app if you don’t already have one. Navigate to Settings > Basic to view the App Details Panel with your App ID, your App Secret, and other details about your app.
Set up your app for advertising by adding the following details:
Save your changes.
To learn more about adding details to your app, such as an icon or category, visit the App Development docs.
Step 2: Link Your Facebook Ad Account with Your App
To run ads and measure installs in the Ads Manager, you are required to associate at least one Ad Account with your app.
- In the app dashboard click Settings > Advanced.
- In Authorized Ad Account IDs, add your Ad Account IDs. You can get your ad account IDs from your Ads Manager.
- If you also have a business account, in Authorized Businesses, add your Business Manager ID. You can find your Business Manager ID in the URL of your Business Manager.
Step 3: Integrate the Facebook SDK in Your Android App
If you’re adding the SDK to an existing project, start at step 3.
- Go to Android Studio | Start a new Android Studio project | Application name | Minimum SDK.
- Select API 15: Android 4.0.3 9 (IceCreamSandwich) or higher and click Next.
- Click Basic Activity and then click Next, and then Finish.
- In your project, open | Gradle Scripts | build.gradle (Project) and add the following to the buildscript < repositories <>> section to download the SDK from the Maven Central Repository:
Step 4: Add App Events
There are three ways events are tracked in your app:
Automatically Logged Events
When you use the Facebook SDK, certain events in your app are automatically logged and collected for Facebook unless you disable automatic event logging. These events are relevant for all use cases — targeting, measurement and optimization. There are three key events collected as part of the Automatic App Event Logging: App Install, App Launch, and Purchase. When automatic logging is enabled, advertisers are able to disable these events, as well as other Facebook internal events such as login impression events. However, if you have disabled automatic logging, but still want to log specific events, such as install or purchase events, manually implement logging for these events in your app.
The first time a new person activates your app or the first time your app starts on a particular device.
When a person launches your app, the Facebook SDK is initialized and the event is logged. However, if a second app launch event occurs within 60 seconds of the first, the second app launch event is not logged.
For the Facebook SDK for Android v4.18, and earlier, SDK initialization is a manual process that differs from the manual event logging process described in this doc. Please upgrade to the latest SDK version or scroll to the Legacy SDK Initialization section to add events manually.
When a purchase processed by Google Play has been completed. If you use other payments platforms, add purchase event code manually.
In-app purchase logging is automatically enabled for apps that have installed or upgraded to v4.39. For apps running an earlier version, enable in-app purchase events in Basic > Settings Android card in the app dashboard or add the purchase event code manually.
Facebook SDK Crash Report
(For Facebook Use Only.)
If your app crashed due to the Facebook SDK, a crash report is generated and sent to Facebook when your app is restarted. This report contains no user data and helps Facebook ensure the quality and stability of the SDK. To opt out of logging this event, disable automatically logged events.
Facebook SDK ANR Report
(For Facebook Use Only.)
If your app has an ANR (Application Not Responding) due to the Facebook SDK, an ANR report is generated and sent to Facebook when your app is restarted. This report contains no user data and helps Facebook ensure the quality and stability of the SDK. To opt out of logging this event, disable automatically logged events.
Disable Automatically Logged Events
To disable automatically logged events add the following to your AndroidManifest.xml file:
In some cases, you want to delay the collection of automatically logged events, such as to obtain user consent or fulfill legal obligations, instead of disabling it. In this case, call the setAutoLogAppEventsEnabled() method of the FacebookSDK class and set to true to re-enable event logging after the end-user provides consent.
To suspend logging again for any reason, set the setAutoLogAppEventsEnabled() method to false .
You can also disable automatic In-App Purchase event logging using the app dashboard. Go to the Android card under Basic > Settings and toggle the switch to No.
Disable Automatic SDK Initialization
To disable automatic SDK initialization, add the following to your AndroidManifest.xml file:
In some cases, you want to delay the SDK initialization, such as to obtain user consent or fulfill legal obligations, instead of disabling it. In this case, call the class method setAutoInitEnabled and set it to true to manually initialize the SDK after the end-user provides consent.
Disable Collection of Advertiser IDs
To disable collection of advertiser-id , add the following to your AndroidManifest.xml file:
In some cases, you want to delay the collection of advertiser_id , such as to obtain User consent or fulfill legal obligations, instead of disabling it. In this case, call the setAdvertiserIDCollectionEnabled() method of the FacebookSDK class and set it to true to re-enable collection of advertiser_id after the end-user provides consent.
To suspend collection for any reason, set the setAdvertiserIDCollectionEnabled() method to false .
Manually Log Events
Create an AppEventsLogger object using the helper methods to log your events, where this is the Activity your method is in.
You can then log your event to logger , where AppEventConstants.EVENT_NAME_X is one of the constants shown in the Standard Events table or from the Code Generator code.
You can also specify a set of parameters in a Bundle and a valueToSum property which is an arbitrary number that can represent any value, for example, a price or a quantity. When reported, all of the valueToSum properties are summed together. For example, if 10 people purchased one item and each item cost $10 (and passed in valueToSum ) then they would be added together to report $100.
Note, both valueToSum and parameters are optional.
To log a custom event, just pass the name of the event as a string. This function assumes that logger is an instance of AppEventsLogger and has been created using AppEventsLogger.newLogger() call.
Event Parameters
Each event can be logged with a valueToSum and a set of up to 25 parameters. They are passed via a Bundle where the key holds the parameter name and the value either a String or an int . If you provide another type of value that is not compliant such as a boolean , the SDK logs a warning to LogginBehavior.APP_EVENT .
Refer to the Standard Event Parameters Reference guide for parameters typically used with standard events. These parameters are intended to provide guidance, however, you can provide your own parameters as well. Your app should log parameters that you are interested in seeing breakdowns for in insights.
Do not use «event» as the name of a parameter. Custom parameters with the name «event» will not be logged. Use another name or add a prefix or suffix to the name, such as my_custom_event .
Step 5: Test Your Event Logging
The App Ads Helper allows you to test the app events in your app to ensure that your app is sending events to Facebook.
- Open the App Ads Helper.
- In Select an App, choose your app and choose Submit.
- Go to the bottom and choose Test App Events.
- Start your app and send an event. The event appears on the web page.
Enabling Debug Logs
Enable debug logs to verify App Event usage from the client side. The debug logs contain detailed requests and JSON responses. Enable debug logs by adding the following code after initializing the Facebook SDK for Android:
This is only for debugging purposes. Please disable debug logs before deploying your app to the public.
Learn More
For more information and helpful hints on App Events check out:
Example Apps
We have created some examples for different app types to show you how you can use app events. Each of the example apps provides a screen by screen breakdown of the different events with code examples. It is important to note that these examples are a starting point for your app and should be customized by you.
Источник