Monday 15 December 2014

Send Email with attachment without Intent

                                   Send Email with attachment without Intent


     Sending mail is one key feature in android and an easy one as well.

You may send mail using Intent as well but that requires user interface.

So, this blog will be useful to those who want to send mail in android as a background task without letting the user know. - See more at

Android Sending Email wihtout intent

 Step:1
activity_mail.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

 xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context=".MainActivity"

    android:background="@drawable/bg">


    <Button

        android:id="@+id/send"

        android:layout_width="150dp"

        android:layout_height="70dp"

        android:layout_centerInParent="true"

        android:background="@drawable/buttonclickcolor"

        android:text="Send Mail" />



</RelativeLayout>




Step:2

GMailSender.java


import javax.activation.DataHandler;

import javax.activation.DataSource;

import javax.activation.FileDataSource;

import javax.mail.BodyPart;

import javax.mail.Message;

import javax.mail.Multipart;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMultipart;  

import java.io.ByteArrayInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.security.Security;

import java.util.Properties;


public class GMailSender extends javax.mail.Authenticator {

private String mailhost = "smtp.gmail.com";

    private String user;

    private String password;

    private Session session;
    

    private Multipart _multipart = new MimeMultipart();

    static {

        Security.addProvider(new com.protect.appsecure.JSSEProvider());

    }

     public GMailSender(String user, String password) {

        this.user = user;

        this.password = password;

         Properties props = new Properties();

        props.setProperty("mail.transport.protocol", "smtp");

        props.setProperty("mail.host", mailhost);

        props.put("mail.smtp.auth", "true");

        props.put("mail.smtp.port", "465");

        props.put("mail.smtp.socketFactory.port", "465");

        props.put("mail.smtp.socketFactory.class",

                "javax.net.ssl.SSLSocketFactory");

        props.put("mail.smtp.socketFactory.fallback", "false");

        props.setProperty("mail.smtp.quitwait", "false");

         session = Session.getDefaultInstance(props, this);

    }

    protected PasswordAuthentication getPasswordAuthentication() {

        return new PasswordAuthentication(user, password);

    }
 
    public synchronized void sendMail(String subject, String body,

            String sender, String recipients) throws Exception {

        try {

            MimeMessage message = new MimeMessage(session);

            DataHandler handler = new DataHandler(new ByteArrayDataSource(

                    body.getBytes(), "text/plain"));

            message.setSender(new InternetAddress(sender));

            message.setSubject(subject);

            message.setDataHandler(handler);

            BodyPart messageBodyPart = new MimeBodyPart();

            messageBodyPart.setText(body);

            _multipart.addBodyPart(messageBodyPart);



            // Put parts in message

            message.setContent(_multipart);

            if (recipients.indexOf(',') > 0)

                message.setRecipients(Message.RecipientType.TO,

                        InternetAddress.parse(recipients));

            else

                message.setRecipient(Message.RecipientType.TO,

                        new InternetAddress(recipients));

            Transport.send(message);

        } catch (Exception e) {
 
        }

    }
 
    public void addAttachment(String filename) throws Exception {

        BodyPart messageBodyPart = new MimeBodyPart();

        DataSource source = new FileDataSource(filename);

        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName("download image");

         _multipart.addBodyPart(messageBodyPart);

    }
 
    public class ByteArrayDataSource implements DataSource {

        private byte[] data;

        private String type;

      public ByteArrayDataSource(byte[] data, String type) {

            super();

            this.data = data;

            this.type = type;

        }

         public ByteArrayDataSource(byte[] data) {

            super();

            this.data = data;

        }
         public void setType(String type) {

            this.type = type;

        }
         public String getContentType() {

            if (type == null)

                return "application/octet-stream";

            else

                return type;

        }
 
        public InputStream getInputStream() throws IOException {

            return new ByteArrayInputStream(data);

        }
 
        public String getName() {

            return "ByteArrayDataSource";

        }

        public OutputStream getOutputStream() throws IOException {

            throw new IOException("Not Supported");

        }

    }

}




Step:3

   
import java.security.AccessController;

import java.security.Provider;

public final class JSSEProvider extends Provider {

public JSSEProvider() {

super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");

        AccessController

                .doPrivileged(new java.security.PrivilegedAction<Void>() {

                    public Void run() {

                        put("SSLContext.TLS",

                                "org.apache.harmony.xnet.provider.jsse.SSLContextImpl");

                        put("Alg.Alias.SSLContext.TLSv1", "TLS");

                        put("KeyManagerFactory.X509",

                                "org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");

                        put("TrustManagerFactory.X509",

                                "org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");

                        return null;

                    }

                });

    }

}



Step: 4:-

    
import android.os.Bundle;
 
import android.app.Activity;
 
import android.util.Log;
 
import android.view.Menu;
 
import android.view.View;
 
import android.widget.Button;
 
import android.widget.Toast;
 
 
 
public class MainActivity extends Activity {
 
Button send;
 
 
 
@Override
 
protected void onCreate(Bundle savedInstanceState) {
 
super.onCreate(savedInstanceState);
 
setContentView(R.layout.activity_main);
 
 
 
        send = (Button) findViewById(R.id.send);
 
        send.setOnClickListener(new View.OnClickListener() {
 
 
 
            public void onClick(View v) {
 
                // TODO Auto-generated method stub
 
                new Thread(new Runnable() {
 
                    public void run() {
 
                        try {
 
                            GMailSender sender = new GMailSender(
 
                                    "ravi.sharma@oodlestechnologies.com",
 
                                    "Can't disclose, enter your password and your email");
 
 
 
                            sender.addAttachment(Environment.getExternalStorageDirectory().getPath()+"/image.jpg");
 
                            sender.sendMail("Test mail", "This mail has been sent from android app along with attachment",
 
                                    "ravi.sharma@oodlestechnologies.com",
 
                                    "ravisharmabpit@gmail.com");
 
                             
 
                             
 
                             
 
                             
 
                        } catch (Exception e) {
 
                            Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
 
                             
 
                        }
 
                    }
 
                }).start();
 
            }
 
        });
 
 
 
    }
 
 
 
}
- See more at: http://www.oodlestechnologies.com/blogs/Send-Mail-in-Android-without-Using-Intent#sthash.eUXWfjLg.dpuf

import android.os.Bundle;

import android.app.Activity;

import android.util.Log;

import android.view.Menu;

import android.view.View;

import android.widget.Button;

import android.widget.Toast;



public class MainActivity extends Activity {

Button send;



@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);



        send = (Button) findViewById(R.id.send);

        send.setOnClickListener(new View.OnClickListener() {



            public void onClick(View v) {

                // TODO Auto-generated method stub

                new Thread(new Runnable() {

                    public void run() {

                        try {

                            GMailSender sender = new GMailSender(

                                    "chandbecse@gmail.com",

                                    "******************");



                            sender.addAttachment(Environment.getExternalStorageDirectory().getPath()+"/image.jpg");

                            sender.sendMail("Test mail", "This mail has been sent from android app along with attachment",

                                    "chandbecse@gmail.com",

                                    "chandbecse@gmail.com");

                          
                            

                            

                        } catch (Exception e) {

                            Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
                        }

                    }

                }).start();

            }

        });

    }


}



This class uses GMailSender class to set the sender email id, password.

using addAttachment method we specify path of file to be attached.

sendMail has four parameters namely subject, body text, senders name, recipients.

Add appropriate file path depending on device and a valid one.




Add Android manifest.xml


<uses-permission android:name="android.permission.INTERNET" /> - See more at: http://www.oodlestechnologies.com/blogs/Send-Mail-in-Android-without-Using-Intent#sthash.eUXWfjLg.dpuf
<uses-permission android:name="android.permission.INTERNET" /> - See more at: http://www.oodlestechnologies.com/blogs/Send-Mail-in-Android-without-Using-Intent#sthash.eUXWfjLg.dpuf
<uses-permission android:name="android.permission.INTERNET" />


Add Jar for mail

jar file


Image








                                                        Thank you







<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 
 
    android:layout_width="match_parent"
 
    android:layout_height="match_parent"
 
    tools:context=".MainActivity"
 
    android:background="@drawable/bg">
 
 
    <Button
 
        android:id="@+id/send"
 
        android:layout_width="150dp"
 
        android:layout_height="70dp"
 
        android:layout_centerInParent="true"
 
        android:background="@drawable/buttonclickcolor"
 
        android:text="Send Mail" />
 
 
 
</RelativeLayout>
- See more at: http://www.oodlestechnologies.com/blogs/Send-Mail-in-Android-without-Using-Intent#sthash.eUXWfjLg.dpuf

Sending mail is one key feature in android and an easy one as well.

You may send mail using Intent as well but that requires user interface.

So, this blog will be useful to those who want to send mail in android as a background task without letting the user know. - See more at: http://www.oodlestechnologies.com/blogs/Send-Mail-in-Android-without-Using-Intent#sthash.eUXWfjLg.dpuf
Sending mail is one key feature in android and an easy one as well.

You may send mail using Intent as well but that requires user interface.

So, this blog will be useful to those who want to send mail in android as a background task without letting the user know. - See more at: http://www.oodlestechnologies.com/blogs/Send-Mail-in-Android-without-Using-Intent#sthash.eUXWfjLg.dpuf
Sending mail is one key feature in android and an easy one as well.

You may send mail using Intent as well but that requires user interface.

So, this blog will be useful to those who want to send mail in android as a background task without letting the user know. - See more at: http://www.oodlestechnologies.com/blogs/Send-Mail-in-Android-without-Using-Intent#sthash.eUXWfjLg.dpuf

Sunday 19 October 2014

Getting Address Using Latitude and Longitude




                                                  Getting Address Using Latitude and Longitude


public static JSONObject getLocationInfo(double lat, double lng) {
   
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();

            StrictMode.setThreadPolicy(policy);

            HttpGet httpGet = new HttpGet(
                    "http://maps.googleapis.com/maps/api/geocode/json?latlng="
                            + lat + "," + lng + "&sensor=true");
            HttpClient client = new DefaultHttpClient();
            HttpResponse response;
            StringBuilder stringBuilder = new StringBuilder();

            try {
                response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();
                InputStream stream = entity.getContent();
                int b;
                while ((b = stream.read()) != -1) {
                    stringBuilder.append((char) b);
                }
            } catch (ClientProtocolException e) {

            } catch (IOException e) {

            }

            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject = new JSONObject(stringBuilder.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return jsonObject;
        }
        return null;
    }

    public static String getCurrentLocationViaJSON(double lat, double lng) {

        JSONObject jsonObj = getLocationInfo(lat, lng);
        Log.i("JSON string =>", jsonObj.toString());

        String Address1 = "";
        String Address2 = "";
        String City = "";
        String State = "";
        String Country = "";
        String County = "";
        String PIN = "";

        String currentLocation = "";

        try {
            String status = jsonObj.getString("status").toString();
            Log.i("status", status);

            if (status.equalsIgnoreCase("OK")) {
                JSONArray Results = jsonObj.getJSONArray("results");
                JSONObject zero = Results.getJSONObject(0);
                JSONArray address_components = zero
                        .getJSONArray("address_components");

                for (int i = 0; i < address_components.length(); i++) {
                    JSONObject zero2 = address_components.getJSONObject(i);
                    String long_name = zero2.getString("long_name");
                    JSONArray mtypes = zero2.getJSONArray("types");
                    String Type = mtypes.getString(0);

                    if (Type.equalsIgnoreCase("street_number")) {
                        Address1 = long_name + " ";
                    } else if (Type.equalsIgnoreCase("route")) {
                        Address1 = Address1 + long_name;
                    } else if (Type.equalsIgnoreCase("sublocality")) {
                        Address2 = long_name;
                    } else if (Type.equalsIgnoreCase("locality")) {
                        // Address2 = Address2 + long_name + ", ";
                        City = long_name;
                    } else if (Type
                            .equalsIgnoreCase("administrative_area_level_2")) {
                        County = long_name;
                    } else if (Type
                            .equalsIgnoreCase("administrative_area_level_1")) {
                        State = long_name;
                    } else if (Type.equalsIgnoreCase("country")) {
                        Country = long_name;
                    } else if (Type.equalsIgnoreCase("postal_code")) {
                        PIN = long_name;
                    }

                }

                currentLocation = Address1 + "," + Address2 + "," + City + ","
                        + State + "," + Country + "," + PIN;

            }
        } catch (Exception e) {

        }
        return currentLocation;
    }

Interview Question - Photon Technologies Pvt Ltd

                             

                                 Interview Question - Photon Technologies Pvt Ltd......



1) What Is the Google Android SDK?
-->  The Google Android SDK is a toolset that developers need in order to write apps on Android enabled devices. It contains a graphical interface that emulates an Android driven handheld environment, allowing them to test and debug their codes.

2) What is the 
Android Architecture?
-->  Android Architecture is made up of 4 key components:
- Linux Kernel
- Libraries
- Android Framework
- Android Applications

3) Describe the 
Android Framework.
-->  The Android Framework is an important aspect of the Android Architecture. Here you can find all the classes and methods that developers would need in order to write applications on the Android environment.

4) What is 
AAPT?
-->  AAPT is short for Android Asset Packaging Tool. This tool provides developers with the ability to deal with zip-compatible archives, which includes creating, extracting as well as viewing its contents.


5) What is the importance of having an emulator within the Android environment?
-->  The emulator lets developers “play” around an interface that acts as if it were an actual mobile device. They can write and test codes, and even debug. Emulators are a safe place for testing codes especially if it is in the early design phase.


6) What are 
Intents?
-->  Intents displays notification messages to the user from within the Android enabled device. It can be used to alert the user of a particular state that occurred. Users can be made to respond to intents.

7) Differentiate Activities from Services.
-->  Activities can be closed, or terminated anytime the user wishes. On the other hand, services are designed to run behind the scenes, and can act independently. Most services run continuously, regardless of whether there are certain or no activities being executed.

8) What are containers?-->  Containers, as the name itself implies, holds objects and widgets together, depending on which specific items are needed and in what particular arrangement that is wanted. Containers may hold labels, fields, buttons, or even child containers, as examples.

9) What is 
Orientation?-->  Orientation, which can be set using setOrientation(), dictates if the LinearLayout is represented as a row or as a column. Values are set as either HORIZONTAL or VERTICAL.

10) What is the importance of Android in the mobile market?-->  Developers can write and register apps that will specifically run under the Android environment. This means that every mobile device that is Android enabled will be able to support and run these apps. With the growing popularity of Android mobile devices, developers can take advantage of this trend by creating and uploading their apps on the Android Market for distribution to anyone who wants to download it.

11) What do you think are some 
disadvantages of Android?-->  Given that Android is an open-source platform, and the fact that different Android operating systems have been released on different mobile devices, there’s no clear cut policy to how applications can adapt with various OS versions and upgrades.
-->  One app that runs on this particular version of Android OS may or may not run on another version.
-->  Another disadvantage is that since mobile devices such as phones and tabs come in different sizes and forms, it poses a challenge for developers to create apps that can adjust correctly to the right screen size and other varying features and specs.

12 *) What is 
adb?-->  Adb is short for Android Debug Bridge. It allows developers the power to execute remote shell commands. Its basic function is to allow and control communication towards and from the emulator port.

13 *) What is the function of an intent filter?-->  Because every component needs to indicate which intents they can respond to, intent filters are used to filter out intents that these components are willing to receive. One or more intent filters are possible, depending on the services and activities that is going to make use of it.

14) Enumerate the three key loops when monitoring an activity?- Entire lifetime – activity happens between onCreate and onDestroy
- Visible lifetime – activity happens between onStart and onStop
- Foreground lifetime – activity happens between onResume and onPause

15 *) When is the 
onStop() method invoked?-->  A call to onStop method happens when an activity is no longer visible to the user, either because another activity has taken over or if in front of that activity.

16) Is there a case wherein other qualifiers in multiple resources take precedence over locale?-->  Yes, there are actually instances wherein some qualifiers can take precedence over locale. There are two known exceptions, which are the MCC (mobile country code) and MNC (mobile network code) qualifiers.

17) What are the different states wherein a process is based?-->  There are 4 possible states:
- foreground activity
- visible activity
- background activity
- empty process

18) How can the ANR be prevented?-->  One technique that prevents the Android system from concluding a code that has been responsive for a long period of time is to create a child thread. Within the child thread, most of the actual workings of the codes can be placed, so that the main thread runs with minimal periods of unresponsive times.
19) What is the AndroidManifest.xml?-->  This file is essential in every application. It is declared in the root directory and contains information about the application that the Android system must know before the codes can be executed.


20) Enumerate the steps in creating a bounded service through AIDL.1. create the .aidl file, which defines the programming interface
2. implement the interface, which involves extending the inner abstract Stub class as well as implanting its methods.
3. expose the interface, which involves implementing the service to the clients.

21) What is the importance of 
Default Resources?-->  When default resources, which contain default strings and files, are not present, an error will occur and the app will not run. Resources are placed in specially named subdirectories under the project res/ directory.


22) When does
 ANR occur?-->  The ANR dialog is displayed to the user based on two possible conditions. One is when there is no response to an input event within 5 seconds, and the other is when a broadcast receiver is not done executing within 10 seconds.

23) What is AIDL?-->  AIDL, or Android Interface Definition Language, handles the interface requirements between a client and a service so both can communicate at the same level through interprocess communication or IPC. This process involves breaking down objects into primitives that Android can understand. This part is required simply because a process cannot access the memory of the other process.

24) What data types are 
supported by AIDL?-->  AIDL has support for the following data types:
-string
-charSequence
-List
-Map
-all native Java data types like int,long, char and Boolean

25) What is a 
Fragment?-->  A fragment is a part or portion of an activity. It is modular in a sense that you can move around or combine with other fragments in a single activity. Fragments are also reusable.

26) What is a 
visible activity?-->  A visible activity is one that sits behind a foreground dialog. It is actually visible to the user, but not necessarily being in the foreground itself.

27) What are the 
core components under the Android application architecture?-->  There are 5 key components under the Android application architecture:
- services
- intent
- resource externalization
- notifications
- content providers


28 *) What is a 
Sticky Intent?-->  A Sticky Intent is a broadcast from sendStickyBroadcast() method such that the intent floats around even after the broadcast, allowing others to collect data from it.


29 *) What is an 
action?-->  In Android development, an action is what the intent sender wants to do or expected to get as a response. Most application functionality is based on the intended action.


30) What 
language is supported by Android for application development?-->  The main language supported is Java programming language. Java is the most popular language for app development, which makes it ideal even for new Android developers to quickly learn to create and deploy applications in the Android environment.

Thursday 16 October 2014

current running application package name


                                                 You can get current name package


To check the curreent running package name

ActivityManager am = (ActivityManager) mContext
                .getSystemService(Activity.ACTIVITY_SERVICE);
        String packageName = am.getRunningTasks(1).get(0).topActivity
                .getPackageName();


Requires permission: 
                              android.permission.GET_TASKS 

Reading inbox SMS



                                               Reading inbox SMS using Activity


Android Reading Inbox SMS



import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;

public class SMSRead extends Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      TextView view = new TextView(this);
      Uri uriSMSURI = Uri.parse("content://sms/inbox");
      Cursor cur = getContentResolver().query(uriSMSURI, null, null, null,null);
      String sms = "";
      while (cur.moveToNext()) {
          sms += "From :" + cur.getString(2) + " : " + cur.getString(11)+"\n";        
      }
      view.setText(sms);
      setContentView(view);
  }
}


Add below permission to AndroidManifest.xml

 
<uses-permission name="android.permission.READ_SMS" />



Receing and Diplay for incoming sms using broadcastreceiver


                                            Read and Display an Incoming SMS-Android Phones

User Define in Manifest :-
    Declare receiver in AndroidManifest

<receiver android:name=".IncomingSms">  
     <intent-filter>
         <action android:name="android.provider.Telephony.SMS_RECEIVED" />
     </intent-filter>
 </receiver>

   SMS permission in AndroidManifest

<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>

Complete code for AndroidManifest.xml File :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidexample.broadcastreceiver"
    android:versionCode="1"
    android:versionName="1.0" >
       
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.androidexample.broadcastreceiver.BroadcastNewSms"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
       
        <receiver android:name="com.androidexample.broadcastreceiver.IncomingSms">  
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>
       
    </application>
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
   
    <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
   
</manifest>
===================================================================

IncomingSms.java file details :
    I have made broadcast event reciever in this file
     1. Created class IncomingSms with extends BroadcastReceiver class

public class IncomingSms extends BroadcastReceiver

      2. Get the object of SmsManager to find out received sms details

// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();

      3.  Create method receiver()

public void onReceive(Context context, Intent intent)

        4. Get / Read current Incomming SMS data

// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();

try {
   
    if (bundle != null) {
       
        final Object[] pdusObj = (Object[]) bundle.get("pdus");
       
        for (int i = 0; i < pdusObj.length; i++) {
           
            SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
            String phoneNumber = currentMessage.getDisplayOriginatingAddress();
           
            String senderNum = phoneNumber;
            String message = currentMessage.getDisplayMessageBody();

            Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);
           

           // Show alert
            int duration = Toast.LENGTH_LONG;
            Toast toast = Toast.makeText(context, "senderNum: "+ senderNum + ", message: " + message, duration);
            toast.show();
           
        } // end for loop
      } // bundle is null

} catch (Exception e) {
    Log.e("SmsReceiver", "Exception smsReceiver" +e);
   
}
========================================================================
     Complete code for  IncomingSms.java file :

public class IncomingSms extends BroadcastReceiver {
   
    // Get the object of SmsManager
    final SmsManager sms = SmsManager.getDefault();
   
    public void onReceive(Context context, Intent intent) {
   
        // Retrieves a map of extended data from the intent.
        final Bundle bundle = intent.getExtras();

        try {
           
            if (bundle != null) {
               
                final Object[] pdusObj = (Object[]) bundle.get("pdus");
               
                for (int i = 0; i < pdusObj.length; i++) {
                   
                    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    String phoneNumber = currentMessage.getDisplayOriginatingAddress();
                   
                    String senderNum = phoneNumber;
                    String message = currentMessage.getDisplayMessageBody();

                    Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);
                   

                   // Show Alert
                    int duration = Toast.LENGTH_LONG;
                    Toast toast = Toast.makeText(context,
                                 "senderNum: "+ senderNum + ", message: " + message, duration);
                    toast.show();
                   
                } // end for loop
              } // bundle is null

        } catch (Exception e) {
            Log.e("SmsReceiver", "Exception smsReceiver" +e);
           
        }
    }  
}








Saturday 20 September 2014

Device Administration Overview Lock,swipe and ect..


                            Lock and Wipe all data from device


                                                                                                             கே.சந்திரசேகர்

A system administrator writes a device admin application that enforces remote/local device security policies.

    The application is installed on a user’s device.

    The system prompts the user to enable the device admin application.
    screens/Device-Policy-Admin.png




    Once the users enable the device admin application, they are subject to its policies.

When enabled, in addition to enforcing security policies, the admin application can:

    Prompt the user to set a new password

    Lock the device immediately

    Perform a factory reset on the device, wiping the user data (if it has permission)

If a device contains multiple enabled admin applications, the strictest policy is enforced.

If users do not enable the device admin app, it remains on the device, but in an inactive state.

    Users will not be subject to its policies, but the application may disable some or all of its functionality.

If a user fails to comply with the policies (for example, if a user sets a password that violates the guidelines), it is up to the application to decide how to handle this.

    For example, the application may prompt the user to set a new password or disable some or all of its functionality.

To uninstall an existing device admin application, users need to first deactivate the application as a device administrator.

    Upon deactivation, the application may disable some or all of its functionality, delete its data, and/or perform a factory reset (if it has permission).

Security Policies

An admin application may enforce security policies regarding the device’s screen lock PIN/password, including:

    The maximum inactivity time to trigger the screen lock

    The minimum number of PIN/password characters

    The maximum number of failed password attempts

    The minimum number of uppercase letters, lowercase letters, digits, and/or special password characters (Android 3.0)

    The password expiration period (Android 3.0)

    A password history restriction, preventing users from reusing the last n unique passwords (Android 3.0)

Additionally, a security policy can require device storage encryption as of Android 3.0 and disabling of camera as for Android 4.0.
The Device Administration Classes

The Device Administration API includes the following classes:

DeviceAdminReceiver

    Base class for implementing a device administration component. This class provides a convenience for interpreting the raw intent actions that are sent by the system. Your Device Administration application must include a DeviceAdminReceiver subclass.
DevicePolicyManager

    A class for managing policies enforced on a device. Most clients of this class must have published a DeviceAdminReceiver that the user has currently enabled. The DevicePolicyManager manages policies for one or more DeviceAdminReceiver instances.
DeviceAdminInfo

    This class is used to specify metadata for a device administrator component.

Creating the Manifest

The manifest of your admin application must register your DeviceAdminReceiver as a <receiver>.

The <receiver> should set android:permission="android.permission.BIND_DEVICE_ADMIN" to ensure that only the system is allowed to interact with the broadcast receiver.

The <receiver> must have an <intent-filter> child element including one or more of the following <action>s, as defined in the DeviceAdminReceiver class:

ACTION_DEVICE_ADMIN_ENABLED

    (Required) This is the primary action that a device administrator must implement to be allowed to manage a device. This is sent to a device administrator when the user enables it for administration.
ACTION_DEVICE_ADMIN_DISABLE_REQUESTED

    Action sent to a device administrator when the user has requested to disable it, but before this has actually been done.
ACTION_DEVICE_ADMIN_DISABLED

    Action sent to a device administrator when the user has disabled it.
ACTION_PASSWORD_CHANGED

    Action sent to a device administrator when the user has changed the password of their device.
ACTION_PASSWORD_EXPIRING

    Action periodically sent to a device administrator when the device password is expiring.
ACTION_PASSWORD_FAILED

    Action sent to a device administrator when the user has failed at attempted to enter the password.
ACTION_PASSWORD_SUCCEEDED

    Action sent to a device administrator when the user has successfully entered their password, after failing one or more times.

<receiver android:name="MyDeviceAdminReceiver"
   android:permission="android.permission.BIND_DEVICE_ADMIN">
   <intent-filter>
      <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
      <action android:name="android.app.action.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED" />
      <action android:name="android.app.action.ACTION_DEVICE_ADMIN_DISABLED" />
      </intent-filter>
      <!-- ... -->
</receiver>


Your <receiver> element must also include a <meta-data> child element specifying an XML resource declaring the policies used by your admin application.

    The android:name attribute must be android.app.device_admin.

    The android:resource must reference an XML resource in your application.

    For example:

<meta-data android:name="android.app.device_admin"
           android:resource="@xml/device_admin_sample" />

An example XML resource requesting all policies would be:

<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
        <uses-policies>
                <limit-password />
                <watch-login />
                <reset-password />
                <force-lock />
                <wipe-data />
                <expire-password />
                <encrypted-storage />
                <disable-camera />
        </uses-policies>
</device-admin>


Your application needs to list only those policies it actually uses.
The DeviceAdminReceiver Class

The DeviceAdminReceiver class defines a set of methods that you can override to handle the device administration events broadcast by the system:

void onEnabled(Context context, Intent intent)

    Called after the administrator is first enabled, as a result of receiving ACTION_DEVICE_ADMIN_ENABLED. At this point you can use DevicePolicyManager to set your desired policies.
CharSequence onDisableRequested(Context context, Intent intent)

    Called when the user has asked to disable the administrator, as a result of receiving ACTION_DEVICE_ADMIN_DISABLE_REQUESTED. You may return a warning message to display to the user before being disabled, or null for no message.
void onDisabled(Context context, Intent intent)

    Called prior to the administrator being disabled, as a result of receiving ACTION_DEVICE_ADMIN_DISABLED. Upon return, you can no longer use the protected parts of the DevicePolicyManager API.
void onPasswordChanged(Context context, Intent intent)

    Called after the user has changed their password, as a result of receiving ACTION_PASSWORD_CHANGED.
void onPasswordExpiring(Context context, Intent intent)

    Called periodically when the password is about to expire or has expired, as a result of receiving ACTION_PASSWORD_EXPIRING. (API 11)
void onPasswordFailed(Context context, Intent intent)

    Called after the user has failed at entering their current password, as a result of receiving ACTION_PASSWORD_FAILED.
void onPasswordSucceeded(Context context, Intent intent)

    Called after the user has succeeded at entering their current password, as a result of receiving ACTION_PASSWORD_SUCCEEDED.

Testing Whether the Admin Application is Enabled

You can query the DevicePolicyManager to test if your admin application is enabled:

DevicePolicyManager devicePolicyManager
        = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
ComponentName deviceAdminComponentName
        = new ComponentName(this, MyDeviceAdminReceiver.class);
boolean isActive = devicePolicyManager.isAdminActive(deviceAdminComponentName);

You could then enable or disable features of your application depending on whether it is an active device administrator.
Enabling the Application

Your application must explicitly request the user to enable it for device administration. To do so:

    Create an implicit Intent with the DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN action:

    Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);

    Add an extra identifying your DeviceAdminReceiver component:

    ComponentName deviceAdminComponentName
            = new ComponentName(this, MyDeviceAdminReceiver.class);
    intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceAdminComponentName);

    Optionally, provide an explanation as to why the user should activate the admin application:

    intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Your boss told you to do this");

    Use the Intent with startActivityForResult() to display the activation dialog:

    startActivityForResult(intent, ACTIVATION_REQUEST);

    You can test for successful activation in your Activity’s onActivityResult() method:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case ACTIVATION_REQUEST:
                if (resultCode == Activity.RESULT_OK) {
                    Log.i("DeviceAdminSample", "Administration enabled!");
                } else {
                    Log.i("DeviceAdminSample", "Administration enable FAILED!");
                }
                return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

Setting Password Quality Policies

DevicePolicyManager includes APIs for setting and enforcing the device screen lock password policy.

    The setPasswordQuality() lets you set basic password requirements for your admin application, using these constants:

    PASSWORD_QUALITY_ALPHABETIC

        The user must enter a password containing at least alphabetic (or other symbol) characters.
    PASSWORD_QUALITY_ALPHANUMERIC

        The user must enter a password containing at least both numeric and alphabetic (or other symbol) characters.
    PASSWORD_QUALITY_NUMERIC

        The user must enter a password containing at least numeric characters.
    PASSWORD_QUALITY_SOMETHING

        The policy requires some kind of password, but doesn’t care what it is.
    PASSWORD_QUALITY_UNSPECIFIED

        The policy has no requirements for the password.
    PASSWORD_QUALITY_COMPLEX

        (API 11) The user must have entered a password containing at least a letter, a numerical digit and a special symbol.

    Once you have set the password quality, you may also specify a minimum length (except with PASSWORD_QUALITY_SOMETHING and PASSWORD_QUALITY_UNSPECIFIED) using the setPasswordMinimumLength() method.

    For example:

    devicePolicyManager.setPasswordQuality(deviceAdminComponentName, PASSWORD_QUALITY_ALPHANUMERIC);
    devicePolicyManager.setPasswordMinimumLength(deviceAdminComponentName, 6);

Your application’s policy metadata resource must request the <limit-password /> policy to control password quality; otherwise these methods throw a security exception.
Setting Password Quality Policies, API 11

Beginning with Android 3.0, the DevicePolicyManager class includes methods that give you greater control over the contents of the password. Here are the methods for fine-tuning a password’s contents:

    setPasswordMinimumLetters()

    setPasswordMinimumLowerCase()

    setPasswordMinimumUpperCase()

    setPasswordMinimumNonLetter()

    setPasswordMinimumNumeric()

    setPasswordMinimumSymbols()

You can also set the password expiration timeout, and prevent users from reusing the last n unique passwords:

    setPasswordExpirationTimeout()

    setPasswordHistoryLength()

Additionally, Android 3.0 introduced support for a policy requiring the user to encrypt the device, which you can set with:

    setStorageEncryption()

Your application’s policy metadata resource must request the <limit-password /> policy to control password quality; otherwise these methods throw a security exception.

Similarly, it must request the <expire-password /> and <encrypted-storage /> policies to control those features without throwing a security exception.
Setting the Device Password

You can test if the current device password meets the quality requirements by calling DevicePolicyManager.isActivePasswordSufficient(), which returns a boolean result.

If necessary, you can start an activity prompting the user to set a password as follows:

Intent intent = new Intent(DevicePolicyManager.ACTION_SET_NEW_PASSWORD);
startActivity(intent);

Your application can also perform a password reset on the device using DevicePolicyManager.resetPassword(). This can be useful if your application is designed to support remote administration, with a new password being provided from a central administration system.

Your application’s policy metadata resource must request the <reset-password /> policy to reset the password; otherwise resetPassword() throws a security exception.
Locking and Wiping the Device

Your application can lock the device programmatically using DevicePolicyManager.lockNow().

You can wipe the user data of the device, performing a factory reset, using DevicePolicyManager.wipeData().

Additionally, you can set the maximum number of allowed failed password attempts before the device is wiped automatically by calling DevicePolicyManager.setMaximumFailedPasswordsForWipe()

Your application’s policy metadata resource must request the <wipe-data /> policy to wipe the data either explicitly or set the maximum failed passwords for wipe; otherwise a security exception is thrown. setMaximumFailedPasswordsForWipe() also requires the <watch-login /> policy.

The lockNow() method requires your application to request the <force-lock /> policy to avoid throwing a security exception.
Device Administration Demo

In this example app, you will see how to write an application that requests to device administration privileges, and once it gets them, allows user to lock or reset the device.

We are going to look at the following files:

    Android Manifest File

    XML Resource File

    Device Admin Receiver Component

    Activity

The source code for this project is available at https://thenewcircle.com/static/courseware/android/DevicePolicyDemo.zip
Android Manifest File

This is where we register our device administration receiver component. It appears as another receiver declaration.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.marakana.android.devicepolicydemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".DevicePolicyDemoActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- This is where we register our receiver -->
        <receiver
            android:name=".DemoDeviceAdminReceiver"
            android:permission="android.permission.BIND_DEVICE_ADMIN" >
            <intent-filter>

                <!-- This action is required -->
                <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
            </intent-filter>

            <!-- This is required this receiver to become device admin component. -->
            <meta-data
                android:name="android.app.device_admin"
                android:resource="@xml/device_admin_sample" />
        </receiver>
    </application>

</manifest>

Notice that <receiver> element now includes required android:permission="android.permission.BIND_DEVICE_ADMIN" permission declaration.

We also must include the appropriate intent action filter android.app.action.DEVICE_ADMIN_ENABLED as well as the <meta-data/> element that specifies that this receiver users @xml/device_admin_sample resource, which we’ll look at next.
XML Resource File

This XML resource file, referenced from AndroidManifest.xml specifies what policies we are interested in.

<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
        <uses-policies>
                <limit-password />
                <watch-login />
                <reset-password />
                <force-lock />
                <wipe-data />
                <expire-password />
                <encrypted-storage />
        </uses-policies>
</device-admin>


In this example, we ask for most of the available policies merely to illustrate what is available. In a real-world example, you should only ask for policies that you really require.
Device Admin Receiver Component

This is the main device administration component. It is basically a specialized BroadcastReceiver class that implements some callbacks specific to device administration.

package com.marakana.android.devicepolicydemo;

import android.app.admin.DeviceAdminReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

/**
 * This is the component that is responsible for actual device administration.
 * It becomes the receiver when a policy is applied. It is important that we
 * subclass DeviceAdminReceiver class here and to implement its only required
 * method onEnabled().
 */
public class DemoDeviceAdminReceiver extends DeviceAdminReceiver {
        static final String TAG = "DemoDeviceAdminReceiver";

        /** Called when this application is approved to be a device administrator. */
        @Override
        public void onEnabled(Context context, Intent intent) {
                super.onEnabled(context, intent);
                Toast.makeText(context, R.string.device_admin_enabled,
                                Toast.LENGTH_LONG).show();
                Log.d(TAG, "onEnabled");
        }

        /** Called when this application is no longer the device administrator. */
        @Override
        public void onDisabled(Context context, Intent intent) {
                super.onDisabled(context, intent);
                Toast.makeText(context, R.string.device_admin_disabled,
                                Toast.LENGTH_LONG).show();
                Log.d(TAG, "onDisabled");
        }

        @Override
        public void onPasswordChanged(Context context, Intent intent) {
                super.onPasswordChanged(context, intent);
                Log.d(TAG, "onPasswordChanged");
        }

        @Override
        public void onPasswordFailed(Context context, Intent intent) {
                super.onPasswordFailed(context, intent);
                Log.d(TAG, "onPasswordFailed");
        }

        @Override
        public void onPasswordSucceeded(Context context, Intent intent) {
                super.onPasswordSucceeded(context, intent);
                Log.d(TAG, "onPasswordSucceeded");
        }



}

Notice that we subclass DeviceAdminReceiver class. This is the required for this component to be able to receive policy notifications.

We also must implement the required onEnabled() method that is called when the policy administration is first enabled.

We don’t really do much here other than log what happened to visually illustrate the execution of this code.
Activity

The activity acts as our demo client in this case. The significant methods are onClick(), onCheckedChanged() and onActivityResult().

package com.marakana.android.devicepolicydemo;

import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;
import android.widget.ToggleButton;

public class DevicePolicyDemoActivity extends Activity implements
                OnCheckedChangeListener {
        static final String TAG = "DevicePolicyDemoActivity";
        static final int ACTIVATION_REQUEST = 47; // identifies our request id
        DevicePolicyManager devicePolicyManager;
        ComponentName demoDeviceAdmin;
        ToggleButton toggleButton;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);

                toggleButton = (ToggleButton) super
                                .findViewById(R.id.toggle_device_admin);
                toggleButton.setOnCheckedChangeListener(this);

                // Initialize Device Policy Manager service and our receiver class
                devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
                demoDeviceAdmin = new ComponentName(this, DemoDeviceAdminReceiver.class);
        }

        /**
         * Called when a button is clicked on. We have Lock Device and Reset Device
         * buttons that could invoke this method.
         */
        public void onClick(View v) {
                switch (v.getId()) {
                case R.id.button_lock_device:
                        // We lock the screen
                        Toast.makeText(this, "Locking device...", Toast.LENGTH_LONG).show();
                        Log.d(TAG, "Locking device now");
                        devicePolicyManager.lockNow();
                        break;
                case R.id.button_reset_device:
                        // We reset the device - this will erase entire /data partition!
                        Toast.makeText(this, "Locking device...", Toast.LENGTH_LONG).show();
                        Log.d(TAG,
                                        "RESETing device now - all user data will be ERASED to factory settings");
                        devicePolicyManager.wipeData(ACTIVATION_REQUEST);
                        break;
                }
        }

        /**
         * Called when the state of toggle button changes. In this case, we send an
         * intent to activate the device policy administration.
         */
        public void onCheckedChanged(CompoundButton button, boolean isChecked) {
                if (isChecked) {
                        // Activate device administration
                        Intent intent = new Intent(
                                        DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
                        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
                                        demoDeviceAdmin);
                        intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
                                        "Your boss told you to do this");
                        startActivityForResult(intent, ACTIVATION_REQUEST);
                }
                Log.d(TAG, "onCheckedChanged to: " + isChecked);
        }

        /**
         * Called when startActivityForResult() call is completed. The result of
         * activation could be success of failure, mostly depending on user okaying
         * this app's request to administer the device.
         */
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                switch (requestCode) {
                case ACTIVATION_REQUEST:
                        if (resultCode == Activity.RESULT_OK) {
                                Log.i(TAG, "Administration enabled!");
                                toggleButton.setChecked(true);
                        } else {
                                Log.i(TAG, "Administration enable FAILED!");
                                toggleButton.setChecked(false);
                        }
                        return;
                }
                super.onActivityResult(requestCode, resultCode, data);
        }

}


onCheckedChanged() is invoked when the toggle button changes state. It sends an intent requesting that this application be granted device administration permissions on this device. User has to allow this request. The result of user’s action is then passed to onActivityResult() method.

onClick() method processes button clicks for lock and reset buttons. Note that its calls to DevicePolicyManager will lock and wipe out the device user data partition, respectively



source code with reference