Tuesday, November 15, 2016

User Defined Permission in Android


Add Security in your Android App @Customized Permission 

Hello All

As you know security  is a major concern for any kind of App.
Android provides it's own Security architecture with a set of Predefined permission.
Now the question is can you add your own defined permission in your App.
Answer is Yes
How???

To add your own permission in App you have to defined permission in the manifest file.
Then in any another app you use the defined permission to access the stuff of predefined App.

Just see the example.

I had created two Apps.

In the first app i defined the permission in manifest file as 

<permission android:name="com.example.ravigodara.permissiontestclient.mypermission"

    android:label="my_permission"

android:protectionLevel= "dangerous" /> 

Then add an Intent filter with an Action to access from outside as 
<activity android:name=".MainActivity">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    <intent-filter >
     <action android:name="com.example.ravigodara.permissiontestclient.MyAction" />
     <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

Nothing special in the layout of MainActivity only a Text Message is there.

In the second App i used defined permission by adding 

<uses-permission 
      android:name="com.example.ravigodara.permissiontestclient.mypermission"/>

The layout of second App contains a Button as 
<Button

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:text="New Button"

    android:id="@+id/button"

    android:layout_centerVertical="true"

    android:layout_centerHorizontal="true" /> 

And Java Code - MainActivity of second app is as 
package com.example.ravigodara.permissiontestserver;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "PerTest";
    Button button;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {

            @Override            public void onClick(View v) {
                Log.d(TAG, "Button pressed!!");
                Intent in = new Intent();
                in.setAction("com.example.ravigodara.permissiontestclient.MyAction");
                in.addCategory("android.intent.category.DEFAULT");
                startActivity(in);
            }
        });
    }
}




No comments:

Post a Comment