Android Permissions

To protect the system’s integrity and the user’s privacy, Android runs each app in a limited access sandbox. If the app wants to use resources or information outside of its sandbox, the app has to explicitly request permission. Depending on the type of permission the app requests, the system may grant the permission automatically, or the system may ask the user to grant the permission.

Declaring Permissions

Declare that your app needs a permission by listing the permission in the App Manifest.

Depending on how sensitive the permission is, the system might grant the permission automatically, or the device user might have to grant the request.

For example, if your app requests permission to turn on the device’s flashlight, the system grants that permission automatically. But if your app needs to read the user’s contacts, the system asks the user to approve that permission.

Depending on the platform version, the user grants the permission either when they install the app (on Android 5.1 and lower) or while running the app (on Android 6.0 and higher).

Requesting Permissions

Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app.

It gives the user more control over the app’s functionality; for example, a user could choose to give a camera app access to the camera but not to the device location. The user can revoke the permissions at any time, by going to the app’s Settings screen.

System permissions are divided into two categories

  • Normal permissions do not directly risk the user’s privacy. If an app lists a normal permission in its manifest, the system grants the permission automatically. Complete list of normal permissions can be found here.
  • Dangerous permissions can give the app access to the user’s confidential data. For these permissions, the user has to explicitly give approval to the app. Complete list of dangerous permissions can be found here.

Handling Permissions at Runtime

For applications to support new Runtime Permissions, in `grade.build` file  set `compileSdkVersion`  and `targetSdkVersion` to 23.

Moving forward, in <ActivityClass>.java, before accessing any restricted content we will need to check for appropriate permission at runtime. This is to be done using Android `checkSelfPermission` API.
`int hasWriteContactsPermission = checkSelfPermission(Manifest.permission.WRITE_CONTACTS)`

If permission is granted, we are good to go else we need to request permission.

We will need to explicitly call `requestPermissions` API to show the request permission dialog box, Android will not do this for us.

In line 5, we get current status for the permission. If permission is granted, we continue with our action else we request user for permission.

Handling Permission Results

Permission results are communicated to the app via onRequestPermissionsResult callback method. Override this to handle the result.

If permission is granted, we continue with our intended actions.

In case, the permission is denied,  check with Android if we should show a permission rationale. `shouldShowRequestPermissionRationale` allows us to communicate purpose of the permission to user.

`shouldShowRequestPermissionRationale` returns `false` if the user has denied permission with option `Never ask again`. In this case we can not invoke the Android permission dialog via `requestPermissions` API and user will have to enable permission via app settings. It makes sense to let user know of the missing permission.

`shouldShowRequestPermissionRationale` Gets whether you should show UI with rationale for requesting a permission. You should do this only if you do not have the permission and the context in which the permission is requested does not clearly communicate to the user what would be the benefit from granting this permission.

pp1

Gotcha: Above implementation only works for Android API level 23 and is not compatible with older versions.

Better Fix: Use `com.android.support:support-v4` as specified in build.gradle line 24. Now your code should use Support library and and make following changes

And we are done here!!

For targeting Android M or higher, refer to wrapper library EasyPermissions.

 

Advertisements

ChromeExtensions Message Passing

Google Chrome is an extensively used browser and is quite popular among developer too. A part of Chrome’s appeal is owed to its excellent extensions. Its not really hard to write simple extension for added convenience.

I am a Ruby on Rails developer and spend quite good amount of time using Google Chrome for development and testing Rails applications. I prefer some background music while working, it helps me cut out out the crap and concentrate better on my work.

Youtube is excellent music service for me. With youtube autoplay enabled, the game becomes even simpler.

Only problem now is, when I have to pause music I have to switch to youtube tab and then hit the pause button. And same when I want resume it.  This is a pain.

Solution:  Build a chrome extension to play/pause youtube without having to switch tabs.
All it needs is a little javascript, html and may be some css if you want things to be a little more pretty. Since we won’t do any user-interface here, we don’t need to think html/css.

How it Works ?

Extensions allow you to add functionality to Chrome without diving deeply into native code. You can create new extensions for Chrome with those core technologies that you're already familiar with from web development: HTML, CSS, and JavaScript.

We’ll do this by implementing a UI element Chrome calls  browser action, which allows us to place a clickable icon right next to Chrome’s Omnibox for easy access. Clicking that icon will play/pause the youtube video irrespective of the current active tab.

ChromeExtYTPP

Lets get started…

Every chrome extension needs to have a file named manifest.json in extension root directory. Lets create one.

manifest_version:2 We are using Chrome Extension menifest specification version 2.

name:YTPP Name for extension

version:0.1 Release version number. We need to increment this with every future release.

description:"YTPP: YouTube Play/Pause without switching tabs" Short description for out extension.

icons: {"128": "icon.png", "48": "icon_48.png", "16": "icon_16.png"} Icon files for different sizes.

author: {"name": "spidergears", "twitter_handle": "spider_gears", "github": "http://github.com/spidergears"} Author Info

browser_action: { "default_icon": "icon.png", "default_title": "YTPP"} Specifications for browser action.

"permissions": ["tabs"] List of browser permissions extension needs to be functional.

"background": {"scripts": ["ytpp_background_script.js"]} Register javascript to be run background. Will call code from this script on click of the browser action button.

"content_scripts": [{"matches": ["http://www.youtube.com/*", "https://www.youtube.com/*"], "js": ["ytpp_content_script.js"]}] Register javascript to be inject into page content. matches keys helps specify on which all websites will the script be injected.

We have manifest file ready. Lets bring in our content and background scripts.

Background Script

Background scripts are a part of background page that  runs in the extension process. Background page exists for the lifetime of the extension, and only one instance of it at a time is active. (Exception: if your extension uses incognito “split” mode, a second instance is created for incognito windows.)

In a typical extension with a background page, the UI — browser action button in our case is implemented by dumb views. When the view needs some state, it requests the state from the background page. When the background page notices a state change, the background page tells the views to update.

Now we want to play/pause youtube media when `browser action` button is clicked.

To accomplish this, we attach a click listener to our `action button` . On button click we loop through all open tabs and check if they are tabs running youtube. For all tabs running youtube, we send a message to our injected script. The inject script, on receipt of message will actually take action to play/pause youtube media.

Content Script

Content scripts are JavaScript files that run in the context of web pages. By using the standard Document Object Model (DOM), they can read details of the web pages the browser visits, or make changes to them.

Here are some examples of what content scripts can do:

  • Find unlinked URLs in web pages and convert them into hyperlinks
  • Increase the font size to make text more legible
  • Find and process microformat data in the DOM

However, content scripts have some limitations. They cannot:

These limitations aren’t as bad as they sound. Content scripts can indirectly use the chrome.* APIs, get access to extension data, and request extension actions by exchanging messages with their parent extension. Content scripts can also make cross-site XMLHttpRequests to the same sites as their parent extensions, and they can communicate with web pages using the shared DOM.

Let’s setup our content script that will be injected into the page. Our script will listen for a message from our browser action button. On message receipt it will grab the youtube play/pause button and click it to toggle media playback.

Easy!!!

Full source code is available in Github Repository.

Extension is published here.

 

Create a Github Repo from the Command Line

Git is a great version control system and Github is superb hosting service for git based repositories.

Github provides a nice web interface to create (blank) repositories at the start of project. But why visit github.com to  create  a blank repository, so here’s a simple bash script  to make this simple task even simpler.

Script is based on Curl and GithubApi.

 

Add this to bash_profile and reload it. Done 🙂
Use git-create to summon 146822610729350.

Be sure to configure github username and access_token in global git configure file.

Hint:

git config --global user.name <username>

git config --global user.token <access_token>