Thursday 28 July 2011

Alert Dialog

I found people facing problem with AlertDialog as:
1. AlertDialog disappears when device rotates from portrait to landscape or vice-versa.
2. The developer does not want AlertDialog to disappear until the condition is satisfied when button clicked

To get these things done, you need to override the method:

@Override
protected Dialog onCreateDialog(int id) { 
    LayoutInflater inflator = LayoutInflater.from(context);
    View view = inflator.inflate(R.layout.yourview, null);
    Button positive = (Button)view.findViewById(R.id.btn_positive);
    Button negative = (Button)view.findViewById(R.id.btn_negative);
   
    positive.setOnClickListener(new Button.OnClickListener(){
        public void onClick(View v) {
            removeDialog(0);
        }
    });
   
    negative.setOnClickListener(new Button.OnClickListener(){
        public void onClick(View v) {
            removeDialog(0);
        }
    });
   
    AlertDialog dialog = new AlertDialog.Builder(this).create();
    dialog.setView(view);
   
    return dialog;
}


Intercept Call Activity

How to listen for Incoming and Outgoing call and perform our task accordingly. Here is how to do it:

public class MyPhoneStateListener extends Service{

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
            StateListener phoneStateListener = new StateListener();
            TelephonyManager telephonymanager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
            telephonymanager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
        }catch(Exception e){ }

    }

    class StateListener extends PhoneStateListener{
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);
            switch(state){
                case TelephonyManager.CALL_STATE_RINGING:
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    break;
                case TelephonyManager.CALL_STATE_IDLE:
                    break;
            }
        }
    };

    @Override
    public void onDestroy() {
       
    }

}

NoteWhile stopping service don't foget to remove the listener and add these permissions to your manifest file:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />







Tuesday 26 July 2011

Send Mail Using Intent

You can send Mail Using one of Email Client installed on device.

Note: It will ask user to choose the email client and then user have to send it by himself /herself.

public void sendMail(Context context,String address){
        //Creating intent for sending mail....
        String[] recipients = new String[]{address,};
        Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
        emailIntent.setType("message/rfc822");
        emailIntent.putExtra( Intent.EXTRA_SUBJECT,"");      //Subject of message
        emailIntent.putExtra( Intent.EXTRA_TEXT,"");          //Body of message
        emailIntent.putExtra( android.content.Intent.EXTRA_EMAIL,recipients);
        try {
            context.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
        }catch (ActivityNotFoundException e) {
            Toast.makeText(context,"No Email Client Available.",Toast.LENGTH_SHORT).show();
        }
}

Monday 25 July 2011

Simulator or Device

You can check if your app is running over Simulator or Device.

public static boolean isSimulator(Context context){
        boolean isSimulator = false;
        TelephonyManager tManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        String uuid = tManager.getDeviceId();
        if(null==uuid ||uuid.equals("000000000000000")){
            isSimulator = true;
        }
        return isSimulator;
}

Permission:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

 

GPS availability

How to check if GPS is enabled on the device or not.

public static boolean isGpsEnabled(LocationManager manager){
        if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
            return false;
        }
        return true;
}

Permission:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
 Use this for network-based location.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
 Use this for GPS based location but it includes network-based location property too.

MMS Listener

How to listen for Incoming MMS and Retrieve it's content? Here is the solution:

public class MmsListener extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        if(intent.getAction().equals("android.provider.Telephony.WAP_PUSH_RECEIVED")){
            Bundle bundle = intent.getExtras();
            try{
                if (bundle != null){
                    //Retrieve MMS---
                    String type = intent.getType();
                    if(type.trim().equalsIgnoreCase("application/vnd.wap.mms-message")){
                        byte[] buffer = bundle.getByteArray("data");
                        String incomingNumber = new String(buffer);
                        int indx = incomingNumber.indexOf("/TYPE");
                        if(indx>0 && (indx-15)>0){
                            int newIndx = indx - 15;
                            incomingNumber = incomingNumber.substring(newIndx, indx);
                            indx = incomingNumber.indexOf("+");
                            if(indx>0){
                                incomingNumber = incomingNumber.substring(indx);
                                System.out.println("Mobile Number: " + incomingNumber);
                            }
                        }
                    }
                }
            }catch(Exception e){
/                       Log.d("MMS data Exception caught", e.getMessage());
            }
        }
              
    }

}


Note: In your manifest file add the BroadcastReceiver -

<receiver android:name=".listener.MmsListener">
    <intent-filter>
        <action android:name="android.provider.Telephony.WAP_PUSH_RECEIVED" />
        <data android:mimeType="application/vnd.wap.mms-message" />
    </intent-filter>
</receiver>

Permission:
<uses-permission android:name="android.permission.RECEIVE_MMS"/>



SMS Listener

How to listen for Incoming SMS and Retrieve it's content? Here is the solution:

public class SmsListener extends BroadcastReceiver{

    private SharedPreferences preferences;
   
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
            Bundle bundle = intent.getExtras();           //---get the SMS message passed in---
            SmsMessage[] msgs = null;
            String msg_from;
            if (bundle != null){
                //---retrieve the SMS message received---
                try{
                    Object[] pdus = (Object[]) bundle.get("pdus");
                    msgs = new SmsMessage[pdus.length];
                    for(int i=0; i<msgs.length; i++){
                        msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                        msg_from = msgs[i].getOriginatingAddress();
                        String msgBody = msgs[i].getMessageBody();
                    }
                }catch(Exception e){
//                            Log.d("Exception caught",e.getMessage());
                }
            }
        }
    }
}

Note: In your manifest file add the BroadcastReceiver:

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

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

Note: Useful link-


Friday 22 July 2011

BarCode Scanner

If the Barcode Scanner is installed on your Android device, then you can scan and return the result.Let's see how to do it:

public Button.OnClickListener mScan = new Button.OnClickListener() {
    
   public void onClick(View v) {
        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
        intent.setPackage("com.google.zxing.client.android");
        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
        startActivityForResult(intent, 0);
    }
}; 

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
     
    if (requestCode == 0) {
        if (resultCode == RESULT_OK) {
            String contents = intent.getStringExtra("SCAN_RESULT");
            String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
            // Handle successful scan
        } else if (resultCode == RESULT_CANCELED) {
            // Handle cancel
        }
    }
}

 

Add Event to Calender

Add Events to Calender

public static void addCalendarEvent(Context context,String title,String location, long eventStartInMillis, long eventEndInMillis) {
             Intent intent = new Intent(Intent.ACTION_EDIT);
            intent.setType("vnd.android.cursor.item/event");
            intent.putExtra("title", title);
            intent.putExtra("eventLocation", location);
            intent.putExtra("beginTime", eventStartInMillis);
            intent.putExtra("endTime", eventEndInMillis);
            intent.getSerializableExtra(title);
            context.startActivity(Intent.createChooser(intent,"Save To calendar..."));
    }

Vibrate Device

Let's make device vibrate:

public void startVibration(Context context){
        Vibrator vibr = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        vibr.vibrate(600);
}

Permission:
<uses-permission android:name="android.permission.VIBRATE" />

Checking Data Connection

You can check if the Data Connection is enabled or not on the device:

public boolean isDataConnectionAvailable(Context context){
        ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if(info == null)
            return false;

        return connectivityManager.getActiveNetworkInfo().isConnected();
 }

Permission:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Thursday 21 July 2011

Retrive Configured Email Accounts

You can retrieve the email accounts configured on the device's native email client.

public Vector fetchConfiguredEmail(Context context){
        AccountManager accManager = AccountManager.get(context);
        Account acc[] = accManager.getAccounts();
        int accCount = acc.length;
        Vector accounts = new Vector();
        for(int i = 0; i < accCount; i++){
            if(acc[i].name.trim().indexOf("@")!=-1){
                accounts.add(acc[i].name);
            }
        }
        return accounts;
}

Permission: You need to add this permission to your manifest file:
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>

Send SMS

How to send SMS programmatically:

public static void sendSms(Context context,String number,String body) {
        try{
            SmsManager sms = SmsManager.getDefault();
            sms.sendTextMessage(number, null, body, null, null);
           }catch(Exception e){  }
 }

Note: Message length is limited to apprx. 160 characters.

Email Client for other account

Hi Guys,
        Here is the Email Client for other accounts. Using this you can fetch and send emails.

Note:  Keep in mind that settings are very important in this case.

The class to fetch email.
MailServerSettings.java

public class MailServerSettings {

    private static Session mSession;
    private Context mContext;
    private String mSmtpServer, mSmtpPort, mUser, mPwd, mServer, mSmtpServe, mPort, mSecurity;

    public MailServerSettings(Context context, String emailid, String pwd, String server, String port, String security, String accType, String smtpServer, String smtpPort, String smtpSecurity) throws Exception{
        try{
            mContext = context;
            mUser = emailid;
            mPwd = pwd;
            mServer = server;
            mSmtpServe = smtpServer;
            mPort = smtpPort;
            mSecurity = smtpSecurity;
          
            Properties props = new Properties();
            Store store = null;
            if(accType.equalsIgnoreCase("IMAP")){
                props = setIMAPProperties(port, security);
                if(security.trim().equalsIgnoreCase("none")){
                    mSession = Session.getDefaultInstance(props);
                }else{
                    try{
                        mSession = Session.getDefaultInstance(props,new javax.mail.Authenticator() {
                            protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(mUser,mPwd);
                            }
                        });
                    }catch(Exception e){
                        mSession = Session.getInstance(props,new javax.mail.Authenticator() {
                            protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(mUser,mPwd);
                            }
                        });
                    }
                }
              
                store = mSession.getStore("imap");
              
            }else{
                props = setPOP3Properties(port, security);
                if(security.trim().equalsIgnoreCase("none")){
                    mSession = Session.getDefaultInstance(props);
                }else{
                    try{
                        mSession = Session.getDefaultInstance(props,new javax.mail.Authenticator() {
                            protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(mUser,mPwd);
                            }
                        });
                    }catch(Exception e){
                        mSession = Session.getInstance(props,new javax.mail.Authenticator() {
                            protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(mUser,mPwd);
                            }
                        });
                    }
                }
              
                store = mSession.getStore("pop3");
            }
          
            store.connect(mServer, mUser, mPwd);
            fetchMail(store, emailid, pwd, security, accType, index);
            store.close();
          
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }
    }
  
//To verify outgoing server settings...
public MailServerSettings(Context context, String emailid, String pwd, String server, String port, String security) throws Exception{
        mContext = context;
        mUser = emailid;
        mPwd = pwd;
        mServer = server;
        Properties props = new Properties();
        props = setSMTPProperties(emailid, pwd, server, port, security);
        if(security.trim().equalsIgnoreCase("none")){
            mSession = Session.getInstance(props);
        }
        else
        {
            try{
                mSession = Session.getInstance(props, new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(mUser,mPwd);
                    }
                });
            }catch(Exception e){
                mSession = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(mUser,mPwd);
                    }
                });
            }
        }
        Transport trnsport = mSession.getTransport("smtp");
        trnsport.connect(server, emailid, pwd);
        trnsport.close();
    }

private Properties setIMAPProperties(String port, String security){
        Properties properties = new Properties();
        properties.setProperty("mail.imap.port", port);
        if(security!= null){
            if(security.trim().equalsIgnoreCase("ssl")){
                properties.setProperty("mail.imap.socketFactory.port", port);
                properties.setProperty("mail.imap.ssl.enable", "true");
                properties.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            }else if(security.trim().equalsIgnoreCase("ssl (accept all certificates)")){
                properties.setProperty("mail.imap.socketFactory.port", port);
                properties.setProperty("mail.imap.ssl.enable", "true");
                properties.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            }
        }
        return properties;
}

private Properties setPOP3Properties(String port, String security){
        Properties props = new Properties();
        props.setProperty("mail.pop3.port", port);
        props.setProperty("mail.pop3.ssl", "false");
        if(security!= null){
            if(security.trim().equalsIgnoreCase("ssl")){
                props.setProperty("mail.pop3.starttls.enable", "true");//For yahoo
                props.setProperty("mail.pop3.ssl", "true");
                props.setProperty("mail.pop3.ssl.enable", "true");
                props.setProperty("mail.pop3.socketFactory.port", port);
                props.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            }else if(security.trim().equalsIgnoreCase("ssl (accept all certificates)")){
                props.setProperty("mail.pop3.starttls.enable", "true");//For yahoo
                props.setProperty("mail.pop3.socketFactory.port", port);
                props.setProperty("mail.pop3.ssl", "true");
                props.setProperty("mail.pop3.ssl.enable", "true");
                props.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            }
        }
        return props;
 }
  
private Properties setSMTPProperties(String emailid, String pwd, String server,String port, String security){
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", server);
        props.put("mail.smtp.port", port);
        if(security.trim().equalsIgnoreCase("none")){
            props.put("mail.smtp.auth", "false");
        }else{
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.socketFactory.port", port);
            props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.socketFactory.fallback", "false");
        }
      
        props.put("mail.smtp.user", emailid);
        props.put("mail.smtp.password", pwd);
      
        //For Hotmail set auth...
        if(security.trim().equalsIgnoreCase("none")){
            props.put("mail.smtp.auth", "false");
        }else{
            props.put("mail.smtp.auth", "true");
        }
        return props;
  }

private void fetchMail(Store store, String user, String pwd, String security, String type){
        try{
            Folder folder = store.getFolder("INBOX");
            folder.open(Folder.READ_ONLY);
            Message[] message = folder.getMessages();
            int n = message.length;
          
             Address[] from = message[n-1].getFrom(); //Fetch the latest email ....
             String sub = message[n-i].getSubject();
             String recipients = from[0].toString();
             int start = recipients.trim().indexOf("<");
             int end = recipients.trim().lastIndexOf(">");
             if(end == -1)
                 end = recipients.trim().length();
             String add = recipients.substring(start+1, end);
            String text = "Message to send.";
          
            SendMail m = new SendMail(mSmtpServer, mSmtpPort, mSmtpPort);
            m.setCredential(mUser, mPwd);
            String[] toArr = { add };
            m.setEmail(toArr, mUser, "subject",text);
            try {
                m.send();
            } catch (AddressException e) {
                 java.lang.System.out.println("Email sent failed. Error: " + e.getMessage());
            } catch (MessagingException e) {
                 java.lang.System.out.println("Email sent failed. Error: " + e.getMessage());
            }
          
            folder.close(false);
            store.close();

        }catch(Exception e){ }
 }

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(mUser, mPwd);
    }
}

The class to send email.
SendMail.java

public class SendMail extends javax.mail.Authenticator {
  private String _user;
  private String _pass;

  private String[] _to;
  private String _from;

  private String _port;
  private String _sport;

  private String _host;

  private String _subject;
  private String _body;

  private boolean _auth;

  private Multipart _multipart;

  private SendMail() {
      _auth = true; // smtp authentication - default on
      _multipart = new MimeMultipart();
  }

  public SendMail(String smtpserver, String smtpport, String smtpsocketfactoryport) {
      _host = smtpserver; // default smtp server
      _port = smtpport; // default smtp port
      _sport = smtpsocketfactoryport; // default socketfactory port
      _auth = true; // smtp authentication - default on
      _multipart = new MimeMultipart();
      MailcapCommandMap mc = (MailcapCommandMap) CommandMap
              .getDefaultCommandMap();
      mc
              .addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
      mc
              .addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
      mc
              .addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
      mc
              .addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
      mc
              .addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
      CommandMap.setDefaultCommandMap(mc);

  }

  public void setCredential(String username, String password) {
      _user = username;
      _pass = password;
  }

  public void send() throws AddressException,MessagingException
  {
      Properties props =_setProperties();
      Session session = Session.getInstance(props, this);
      MimeMessage msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress(_from));
      InternetAddress[] addressTo = new InternetAddress[_to.length];
      for (int i = 0; i < _to.length; i++) {
          addressTo[i] = new InternetAddress(_to[i]);
      }
      msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);
      msg.setSubject(_subject);
      msg.setSentDate(new Date());
      // setup message body
      BodyPart messageBodyPart = new MimeBodyPart();
      messageBodyPart.setText(_body);
      _multipart.addBodyPart(messageBodyPart);

      // Put parts in message
      msg.setContent(_multipart);

      // send email
      Transport.send(msg);
  }

  public void setEmail(String[] to, String from, String subject, String body) {
      _to = to;
      _body = body;
      _subject = subject;
      _from = from;
  }

  @Override
  public PasswordAuthentication getPasswordAuthentication() {
      return new PasswordAuthentication(_user, _pass);
  }

  private Properties _setProperties() {
      Properties props = new Properties();
      props.put("mail.smtp.starttls.enable", "true"); //for Hotmail...
      props.put("mail.smtp.host", _host);
      props.put("mail.smtp.ssl.enable", true);
      props.put("mail.debug", "true");
      if (_auth) {
          props.put("mail.smtp.auth", "true");
      }
      props.put("mail.smtp.port", _port);
      props.put("mail.smtp.socketFactory.port",_sport);
      props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
      props.put("mail.smtp.socketFactory.fallback","false");
      return props;
  }

}

Note: You will need to add these jar files in your app: