Android 6 changes and APIs

30
Android 6.0 APIs and Changes Malwinder Pal Singh Android Developer Mobile Programming LLC

Transcript of Android 6 changes and APIs

Page 1: Android 6 changes and APIs

Android 6.0 APIs and ChangesMalwinder Pal SinghAndroid DeveloperMobile Programming LLC

Page 2: Android 6 changes and APIs

ContentsAPIs

App LinkingDirect Share

ChangesRuntime PermissionsDoze

Page 3: Android 6 changes and APIs

App LinkingConcept

Associate an app with a web domain you own.

Implementation• In your app manifest, create intent filters for your website URIs.• Configure your app to request verification of app links.• Publish a Digital Asset Links JSON file on your websites to provide verification.

Page 4: Android 6 changes and APIs

App LinkingUnderstand URI Request Handling

When a clicked link or programmatic request invokes a web URI intent, the Android system uses the following criteria, in descending order, to determine how to handle the request:

• The user has set app link associations.• The user has set no association, and there is one supporting app.• The user has set no association, and there are multiple supporting apps.

Page 5: Android 6 changes and APIs

App LinkingRequest App Links Verification

• Enabling automatic verification

<activity ...>

    <intent-filter android:autoVerify="true">        <action android:name="android.intent.action.VIEW" />        <category android:name="android.intent.category.DEFAULT" />        <category android:name="android.intent.category.BROWSABLE" />        <data android:scheme="http" android:host="www.android.com" />        <data android:scheme="https" android:host="www.android.com" />    </intent-filter>

</activity>

Page 6: Android 6 changes and APIs

App LinkingRequest App Links Verification

• Supporting app linking for multiple hosts

The system must be able to verify every host specified in the app’s web URI intent filters’ data elements against the Digital Asset Links files hosted on the respective web domains.

If any verification fails, the app is not verified to be a default handler for any of the web URI patterns defined in the app's intent filters.

For example, an app with the following intent filters would fail verification if an assetlinks.json file were not found at both https://www.domain1.com/.well-known/assetlinks.json and https://www.domain2.com/.well-known/assetlinks.json.

Page 7: Android 6 changes and APIs

App LinkingRequest App Links Verification

• Supporting app linking for multiple subdomains

The Digital Asset Links protocol treats subdomains as unique, separate hosts.

If your intent filter lists both the www.example.com and mobile.example.com subdomains as hosts, you must host a separate assetlink.json file on each subdomain.

For example, an app with the following intent filter declaration would pass verification only if the website owner published valid assetlinks.json files at both https://www.example.com/.well-known/assetlinks.json and https://mobile.example.com/.well-known/assetlinks.json:

      <data android:scheme="http" android:host="www.example.com" />      <data android:scheme="https" android:host="mobile.example.com" />

Page 8: Android 6 changes and APIs

App LinkingDeclare Website Associations

https://domain[:optional_port]/.well-known/assetlinks.json

A website can declare associations with multiple apps within the same assetlinks.json file.

The system verifies the JSON file via the encrypted HTTPS protocol. Make sure that your hosted file is accessible over an HTTPS connection, regardless of whether your app's intent filter includes https

Demo

Page 9: Android 6 changes and APIs

App LinkingAssociating a website with multiple apps

A website can declare associations with multiple apps within the same assetlinks.json file.

[{  "relation": ["delegate_permission/common.handle_all_urls"],  "target": {    "namespace": "android_app",    "package_name": "example.com.app_one",    "sha256_cert_fingerprints":    ["14:6D:E9:83:C5:73:06:50:D8:EE:B9:95:2F:34:FC:64:16:A0:83:42:E6:1D:BE:A8:8A:04:96:B2:3F:CF:44:E5"]  }  },  {  "relation": ["delegate_permission/common.handle_all_urls"],  "target": {    "namespace": "android_app",    "package_name": "example.com.app_two",    "sha256_cert_fingerprints":    ["14:6D:E9:83:C5:73:06:50:D8:EE:B9:95:2F:34:FC:64:16:A0:83:42:E6:1D:BE:A8:8A:04:96:B2:3F:CF:44:E5"]  }}]

Page 10: Android 6 changes and APIs

App LinkingAssociating multiple websites with a single app

Multiple websites can declare associations with the same app in their respective assetlinks.json files. 

Both assetlinks.json should have same JSON Object for application linking.

Page 11: Android 6 changes and APIs

Direct ShareConcept

Define direct share targets that launch a specific activity in app.

These direct share targets are exposed to users via the Share menu.

This feature allows users to share content to targets, such as contacts, within other apps. For example, the direct share target might launch an activity in another social network app, which lets the user share content directly to a specific friend or community in that app.

Page 12: Android 6 changes and APIs

Implementation

To enable direct share targets you must define a class that extends the ChooserTargetService class.

Declare your service in the manifest. Within that declaration, specify the BIND_CHOOSER_TARGET_SERVICE permission and an intent filter using the SERVICE_INTERFACE action.

<service android:name=".ChooserTargetService"        android:label="@string/service_name"        android:permission="android.permission.BIND_CHOOSER_TARGET_SERVICE">    <intent-filter>        <action android:name="android.service.chooser.ChooserTargetService" />    </intent-filter>

</service>

Direct Share

Page 13: Android 6 changes and APIs

Implementation

For each activity that you want to expose to ChooserTargetService, add a <meta-data> element with the name"android.service.chooser.chooser_target_service" in app manifest.

<activity android:name=".MyShareActivity”        android:label="@string/share_activity_label">    <intent-filter>        <action android:name="android.intent.action.SEND" />    </intent-filter> <meta-data        android:name="android.service.chooser.chooser_target_service"        android:value=".ChooserTargetService" /></activity>

Direct Share

Page 14: Android 6 changes and APIs

Implementation

public class SampleChooserTargetService extends ChooserTargetService {

@OverrideList<ChooserTarget> onGetChooserTargets(ComponentName targetActivityName, IntentFilter matchedFilter) {

... }}

Direct Share

Page 15: Android 6 changes and APIs

Implementation

final List<ChooserTarget> targets = new ArrayList<>();

for (int i = 0; i < length; i++) {

final String targetName = ... final Icon targetIcon = ... final float targetRanking = ... final ComponentName targetComponentName = ... final Bundle targetExtras = ...

targets.add(new ChooserTarget( targetName, targetIcon, targetRanking, targetComponentName, targetExtras));

}

Direct Share

Page 16: Android 6 changes and APIs

Runtime PermissionsConcept

Users grant permissions to apps while the app is running, not when they install the app.

System permissions are divided into two categories, normal and dangerous:

• Normal permissions do not directly risk the user's privacy. If your app lists a normal permission in its manifest, the system grants the permission automatically.

• Dangerous permissions can give the app access to the user's confidential data. If your app lists a normal permission in its manifest, the system grants the permission automatically. If you list a dangerous permission, the user has to explicitly give approval to your app.

Page 17: Android 6 changes and APIs

Runtime PermissionsConcept

The effect of that declaration is different depending on the system version and your app's target SDK level:

• If targetSdkVersion SDK is 22 or lower: If you list a dangerous permission in your manifest, the user has to grant the permission when they install the app; if they do not grant the permission, the system does not install the app at all.

• If targetSdkVersion is 23 or higher: The app has to list the permissions in the manifest, and it must request each dangerous permission it needs while the app is running. The user can grant or deny each permission, and the app can continue to run with limited capabilities even if the user denies a permission request.

Beginning with Android 6.0, users can revoke permissions from any app at any time, even if the app targets a lower API level. You should test your app to verify that it behaves properly when it's missing a needed permission, regardless of what API level your app targets.

Page 18: Android 6 changes and APIs

Runtime PermissionsCheck For Permissions

If your app needs a dangerous permission, you must check whether you have that permission every time you perform an operation that requires that permission.

To check if you have a permission, call the ContextCompat.checkSelfPermission() method.

int permissionCheck = ContextCompat.checkSelfPermission(ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_CALENDAR);

If the app has the permission, the method returns PackageManager.PERMISSION_GRANTED , and the app can proceed with the operation.

If the app does not have the permission, the method returns PackageManager.PERMISSION_DENIED, and the app has to explicitly ask the user for permission

Page 19: Android 6 changes and APIs

Runtime PermissionsRequest Permissions

If your app needs a dangerous permission that was listed in the app manifest, it must ask the user to grant the permission. Android provides several methods you can use to request a permission. Calling these methods brings up a standard Android dialog, which you cannot customize.

Explain why the app needs permissions

To help find situations where the user might need an explanation, Android provides a utiltity method, shouldShowRequestPermissionRationale(). This method returns true if the app has requested this permission previously and the user denied the request.

If the user turned down the permission request in the past and chose the Don't ask again option in the permission request system dialog, this method returns false. The method also returns false if a device policy prohibits the app from having that permission.

Page 20: Android 6 changes and APIs

Runtime PermissionsRequest Permissions

Request the permissions you need

If your app doesn't already have the permission it needs, the app must call requestPermissions(Activity activity, String[] permissions,int requestCode)method to request the appropriate permissions. Your app passes the permissions it wants, and also an integer request code that you specify to identify this permission request.

Page 21: Android 6 changes and APIs

Runtime PermissionsRequest Permissions

Request the permissions you needif (ContextCompat.checkSelfPermission(thisActivity,

Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED) {

    // Should we show an explanation?

  if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,

            Manifest.permission.READ_CONTACTS)) {

    // Show an expanation to the user *asynchronously* -- don't block    // response! After the user sees the explanation, try again to // request the permission.

    } else {

        // No explanation needed, we can request the permission.    }}

Page 22: Android 6 changes and APIs

Runtime PermissionsRequest Permissions

Request the permissions you need

    else {

        // No explanation needed, we can request the permission.

        ActivityCompat.requestPermissions(thisActivity,                new String[]{Manifest.permission.READ_CONTACTS},                MY_PERMISSIONS_REQUEST_READ_CONTACTS);

        // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an        // app-defined int constant. The callback method gets the        // result of the request.

    }

When your app calls requestPermissions() , the system shows a standard dialog box to the user. Your app cannot configure or alter that dialog box.

Page 23: Android 6 changes and APIs

Runtime PermissionsRequest Permissions

Handle the permissions request response

When your app requests permissions, the system presents a dialog box to the user. When the user responds, the system invokes your app's onRequestPermissionsResult() method, passing it the user response. Your app has to override that method to find out whether the permission was granted. The callback is passed the same request code you passed to requestPermissions().

@Overridepublic void onRequestPermissionsResult(int requestCode,        String permissions[], int[] grantResults) {}

Page 24: Android 6 changes and APIs

Runtime PermissionsRequest Permissions

Handle the permissions request response

    switch (requestCode) {

        case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {

            // If request is cancelled, the result arrays are empty.            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the               // contacts-related task you need to do.            } else {                // permission denied, boo! Disable the                // functionality that depends on this permission.            }            return;        }        // other 'case' lines to check for other        // permissions this app might request    }}

Page 25: Android 6 changes and APIs

DozeConcept

Doze reduces battery consumption by deferring background CPU and network activity for apps when the device is unused for long periods of time.

Doze manage the behaviour of all apps running on Android 6.0 or higher, regardless whether they are specifically targeting API level 23.

Page 26: Android 6 changes and APIs

DozeUnderstanding Doze

In Doze mode, the system attempts to conserve battery by restricting apps' access to network and CPU-intensive services. It also prevents apps from accessing the network and defers their jobs, syncs, and standard alarms.

Over time, the system schedules maintenance windows less and less frequently, helping to reduce battery consumption in cases of longer-term inactivity when the device is not connected to a charger.As soon as the user wakes the device by moving it, turning on the screen, or connecting a charger, the system exits Doze and all apps return to normal activity.

Page 27: Android 6 changes and APIs

DozeUnderstanding Doze

Doze restrictions

• Network access is suspended.• The system ignores wake locks.• Standard AlarmManager alarms (including setExact() and setWindow()) are

deferred to the next maintenance window.• If you need to set alarms that fire while in Doze,

use setAndAllowWhileIdle() or setExactAndAllowWhileIdle().• Alarms set with setAlarmClock() continue to fire normally — the system

exits Doze shortly before those alarms fire.• The system does not perform Wi-Fi scans.

Page 28: Android 6 changes and APIs

DozeUnderstanding Doze

Adapting your app to DozeThe system Doze is particularly likely to affect activities that AlarmManager alarms and timers manage, because alarms in Android 5.1 (API level 22) or lower do not fire when the system is in Doze.To help with scheduling alarms, Android 6.0 (API level 23) introduces two new AlarmManager methods:

setAndAllowWhileIdle() and setExactAndAllowWhileIdle().With these methods, you can set alarms that will fire even if the device is in Doze.Neither setAndAllowWhileIdle() nor setExactAndAllowWhileIdle() can fire alarms more than once per 15 minutes per app.

The Doze restriction on network access is also likely to affect your app, especially if the app relies on real-time messages such notifications. If your app requires a persistent connection to the network to receive messages, you should use Google Cloud Messaging (GCM) if possible.

Page 29: Android 6 changes and APIs

DozeUnderstanding Doze

Using GCM to Interact with Your App While the Device is IdleGCM provides a single, persistent connection to the cloud; all apps needing real-time messaging can share this connection. This shared connection significantly optimizes battery consumption by making it unnecessary for multiple apps to maintain their own, separate persistent connections, which can deplete the battery rapidly.

GCM high-priority messages let you reliably wake your app to access the network, even if the user’s device is in Doze or the app is in App Standby mode.

{  "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",  "priority" : “high",  "notification" : {    "body" : "This week’s edition is now available.",    "title" : "NewsMagazine.com",    "icon" : "new",  },  "data" : {    "volume" : "3.21.15",    "contents" : "http://www.news-magazine.com/world-week/21659772"  }}

Page 30: Android 6 changes and APIs

Auto Backup for AppsUnderstanding Doze

Using GCM to Interact with Your App While the Device is IdleGCM provides a single, persistent connection to the cloud; all apps needing real-time messaging can share this connection. This shared connection significantly optimizes battery consumption by making it unnecessary for multiple apps to maintain their own, separate persistent connections, which can deplete the battery rapidly.

GCM high-priority messages let you reliably wake your app to access the network, even if the user’s device is in Doze or the app is in App Standby mode.

{  "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",  "priority" : “high",  "notification" : {    "body" : "This week’s edition is now available.",    "title" : "NewsMagazine.com",    "icon" : "new",  },  "data" : {    "volume" : "3.21.15",    "contents" : "http://www.news-magazine.com/world-week/21659772"  }}