Monday, November 16, 2015

Get Current Location using Android Studio With Android M Support


You can get Current location in Android M using Below code...
You can Download full source code here.

GPSTracker.java



package com.example.shivang.currentlocation;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.util.Log;

/** * Created by shivang on 09-11-2015. */

public class GPSTracker extends Service implements LocationListener{

    private final Context mContext;

    // flag for GPS status  
  boolean isGPSEnabled = false;

    // flag for network status  
  boolean isNetworkEnabled = false;

    boolean canGetLocation = false;

      Location location; // location     
 double latitude; // latitude   
 double longitude; // longitude

    // The minimum distance to change Updates in meters  
  private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
    // The minimum time between updates in milliseconds  
  private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
    // Declaring a Location Manager   
 protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }


    @TargetApi(Build.VERSION_CODES.M)
    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext.getSystemService(mContext.LOCATION_SERVICE);

            // getting GPS status     
       isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status   
         isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled     
       } else {
                this.canGetLocation = true;
                // First get location from Network Provider   
             if (isNetworkEnabled) {
//                    if(isPermission())      
              if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (mContext.checkSelfPermission(Manifest.permission.
ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || mContext.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                            //DO OP WITH LOCATION SERVICE   
                         locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                        }
                    }else {
                        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);


                    }
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }
    /**     * Function to get latitude     * */    
public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude        return latitude;
    }

    /**     * Function to get longitude     * */    
public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude       
 return longitude;
    }

    /**     * Function to check if best network provider     * @return boolean     * */    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**     * Function to show settings alert dialog     * */ 
   public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title       
 alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message       
 alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // Setting Icon to Dialog      
  //alertDialog.setIcon(R.drawable.delete);
        // On pressing Settings button       
 alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button      
  alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Showing Alert Message      
  alertDialog.show();
    }

    @Override  
  public void onLocationChanged(Location location) {
    }

    @Override   
 public void onProviderDisabled(String provider) {
    }

    @Override   
 public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }


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

    public Location getLocationUsingCriteria()  {

        locationManager = (LocationManager) mContext.getSystemService(mContext.LOCATION_SERVICE);
        android.location.Criteria criteria = new android.location.Criteria();
        String best = locationManager.getBestProvider(criteria, true);
        System.out.println("Best..................."+ best);

        //since you are using true as the second parameter, you will only get the best of providers which are enabled.      
  canGetLocation = true;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (mContext.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || mContext.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                //DO OP WITH LOCATION SERVICE             
   location = locationManager.getLastKnownLocation(best);
            }
        }else {
            location = locationManager.getLastKnownLocation(best);
        }

        return location;
    }
}


 

MainActivity.java


package com.example.shivang.currentlocation;

import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        GPSTracker gpsTracker = new GPSTracker(this);

        if(gpsTracker.canGetLocation()){
//            Location location = gpsTracker.getLocation(); 
           Location location = gpsTracker.getLocationUsingCriteria();
            Toast.makeText(this, gpsTracker.getLatitude() +  " : " + gpsTracker.getLongitude(), Toast.LENGTH_LONG).show();

        }else{
            Toast.makeText(this, "Unable to get location!", Toast.LENGTH_LONG).show();
    gpsTracker.showSettingsAlert();
        }


//        location.getLatitude();//     
   location.getLongitude();



    }

}
permission:
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

Reference:
Googling

Tuesday, September 22, 2015

RoboGuice: (Android findViewById() vs @Inject View)


Roboguice is a dependency injection framework for Android applications, that brings the simplicity and ease of Dependency Injection to Android, using Google’s own Guice library. It smoothes out some of the wrinkles in your Android app development experience make things simple and fun. Do you always forget to check for null when you getIntent().getExtras()? RoboGuice 2 will help you. Think casting findViewById() to a TextView shouldn’t be necessary? RoboGuice is on it.
Using RoboGuice, you can inject your View, Resource, System Service, or any other object. RoboGuice can help you to slim down application code. Less code means less chances of issues/bugs and can help you to save efforts required to write or modify particular code in a project. It helps you to generate readable code which could be easier to follow.
Let’s look at different usage of RoboGuice library.

Usage of RoboGuice library:

  • Views Injection:: To initialize views, use @InjectViews, for example: @InjectView(R.id.textView1) TextView textView1;
  • Resources Injection: To initialize and get resources, use @InjectResources, for example: @InjectResource(R.string.app_name) String name;
  • System services Injection: To initialize and access system services, use @Inject, for example: @Inject LayoutInflater inflater;
  • POJO object Injection: To inject and initialize POJO object, use @Inject, for example: @Inject Foo foo;
Let’s look at an example of general activity code:
public class TestActivity extends Activity{
    TextView textView1;
    TextView textView2;
    ImageView imageView1;
    String name;
    Drawable icLauncher;
    LocationManager locManager;
    LayoutInflater inflater;
    NotificationManager notifyManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_test);
        textView1 = (TextView) findViewById(R.id.textView1);
        textView2 = (TextView) findViewById(R.id.textView2);
        imageView1 = (ImageView) findViewById(R.id.imageView1);
        name = getString(R.string.app_name);
        icLauncher = getResources().getDrawable(R.id.ic_launcher);
        locManager = (LocationManager) getSystemService(Activity.LOCATION_SERVICE);
        inflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        notifyManager = (NotificationManager)        getSystemService(Activity.NOTIFICATION_SERVICE);
        textView1.setText("Hello World! RoboGuice demo");
    }
}

Let’s check the magic of RoboGuice and let’s slim down the code.

Using RoboGuice

To use RoboGuice for the dependency injection, you are required to extends eitherRoboActivity or RoboFragment.
public class TestActivity extends RoboActivity{


    @InjectView(R.id.textView1) TextView textView1;

    @InjectView(R.id.textView2) TextView textView2;
    @InjectView(R.id.imageView1) ImageView imageView1;
    @InjectResource(R.string.app_name) String name;
    @InjectResource(R.drawable.ic_launcher) Drawable icLauncher;
    @Inject LocationManager locManager;
    @Inject LayoutInflater inflater;
    @Inject NotificationManager notifyManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_test);
        textView1.setText(name);
    }
}
Benefits of using RoboGuice
  • No need to initialize views, if you want then Inject it using @InjectViews
  • No need to initialize System service. If you need then Inject it using @Inject
  • No need to initialize Drawable, string and other resources. If you require then Inject it using @InjectResource
  • All of these above practices helps you to slim down the code.
  • Less code => Less chances of bugs/issues
  • Less code => Android developer can save coding efforts and can focus fully on actual business logic of android app

RoboGuice and ActionBarSherlock

As I have mentioned earlier in alert box that you are required to extend either RoboActivity or RoboFragment to use RoboGuice in either Activity or Fragment particularly. But what if you have included ActionBarSherlock in your project to manage compatibility? The problem is you have extended either SherlockActivity or SherlockFragmentActivity for your activity or fragment particularly and now the situation is we could not use RoboGuice with ActionBarSherlock.
But There is one solution for it too, you have to define custom base classes for Activities and Fragments to use RoboGuice and ActionBarSherlock both.
You can download base classes from here: https://github.com/rtyley/roboguice-sherlock or download a JAR file for the same: RoboGuice+Sherlock.jar, include either of them in your project.
You can download a sample code here.

Reference:

Wednesday, September 16, 2015

Sending email with attachment using JavaMail API


For sending email with attachment, JavaMail API provides some useful classes like BodyPart, MimeBodyPart etc.

For better understanding of this example, learn the steps of sending email using JavaMail API first.
For sending the email using JavaMail API, you need to load the two jar files:
  • mail.jar
  • activation.jar
download these jar files (or) go to the Oracle site to download the latest version.

Sending email with attachment using JavaMail API


There are total 7 steps for sending attachment with email. They are:
  1. Get the session object
  2. compose message
  3. create MimeBodyPart object and set your message text
  4. create new MimeBodyPart object and set DataHandler object to this object
  5. create Multipart object and add MimeBodyPart objects to this object
  6. set the multiplart object to the message object
  7. send message

Example of sending email with attachment using JavaMail API

import java.util.*;  
import javax.mail.*;  
import javax.mail.internet.*;  
import javax.activation.*;  
  
class SendAttachment{  
 public static void main(String [] args){  
  
  String to="example@gmail.com";//change accordingly  
  final String user="example@gmail.com";//change accordingly  
  final String password="xxxxx";//change accordingly  
   
  //1) get the session object    

//GMail via TLS
 Properties properties = System.getProperties();  
 properties.put("mail.smtp.host", "smtp.gmail.com");  
 properties.put("mail.smtp.auth", "true");  
 properties.put("mail.transport.protocol", "smtps");
 properties.put("mail.smtp.port", "587");
 properties.put("mail.smtp.starttls.enable", "true");
 // GMail via SSL

/*properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.socketFactory.port", "465");
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.port", "465");*/
   Session session = Session.getDefaultInstance(properties,  
   new javax.mail.Authenticator() {  
   protected PasswordAuthentication getPasswordAuthentication() {  
   return new PasswordAuthentication(user,password);  
   }  
  });  
     
  //2) compose message     
  
try{  
    MimeMessage message = new MimeMessage(session);  
    message.setFrom(new InternetAddress(user));  
    message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));  
    message.setSubject("Message Aleart");  
      
    //3) create MimeBodyPart object and set your message text     

    BodyPart messageBodyPart1 = new MimeBodyPart();  
    messageBodyPart1.setText("This is message body");  
      
    //4) create new MimeBodyPart object and set DataHandler object to this object      

    MimeBodyPart messageBodyPart2 = new MimeBodyPart();  
  
    String filename = "SendAttachment.java";//change accordingly  
    DataSource source = new FileDataSource(filename);  
    messageBodyPart2.setDataHandler(new DataHandler(source));  
    messageBodyPart2.setFileName(filename);  
     
     
    //5) create Multipart object and add MimeBodyPart objects to this object      

    Multipart multipart = new MimeMultipart();  
    multipart.addBodyPart(messageBodyPart1);  
    multipart.addBodyPart(messageBodyPart2);  
  
    //6) set the multiplart object to the message object  

    message.setContent(multipart );  
     
    //7) send message  

    Transport.send(message);  
   
   System.out.println("message sent....");  
   }catch (MessagingException ex) {ex.printStackTrace();}  
 }  
}

You can download full source code Here.

Wednesday, August 19, 2015

Get Registered Email From Android Device


We just need to get account fron Account Manager. Here is the code...

MainActivity.java

import java.util.regex.Pattern;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.os.Bundle;
import android.util.Patterns;


public class MainActivity extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
Account[] accounts = AccountManager.get(this).getAccounts();
for (Account account : accounts) {
   if (emailPattern.matcher(account.name).matches()) {
       String possibleEmail = account.name;
       System.out.println("Here is email address in matches........[" + possibleEmail + "]");
   }
 
   System.out.println("Here is email address........[" + account.name + "]" + "{" + account.type +"}");
}
}

We also require user permintion:
<uses-permission android:name="android.permission.GET_ACCOUNTS" />

You can download source code from here.

Reference: Googling

Thursday, July 9, 2015

Apache's James enterprise e-mail server

The Java Apache Mail Enterprise Server (a.k.a. James) is a 100% pure Java SMTP and POP3 Mail server and NNTP News server designed to be a complete and portable enterprise mail engine solution. James is based on currently available open protocols.


How e-mail works

E-mail is simple, in principle. You construct a message with one or more recipient addresses using a mail user agent (MUA). MUAs come in many forms and include text-based, Web-based, and GUI applications; Microsoft Outlook and Netscape Messenger fall into the last category. Each e-mail client is configured to send mail to a mail transfer agent (MTA) and can be used to poll an MTA to fetch e-mail messages sent to the user's address. To do this, you need an e-mail account on a mail server (technically the MTA) and you can, using standard Internet protocols, either work with the e-mail offline (using POP3) or leave the e-mail on the server (using IMAP). The protocol used to send mail both from the client to the MTA and between MTAs is SMTP (Simple Mail Transfer Protocol).
What really happens between MTAs is only slightly more interesting. E-mail servers rely heavily on DNS and e-mail-specific records called mail transfer (or MX) records. MX records are slightly different from the DNS records used to resolve URLs, containing some additional priority information used to route mail more effectively. I won't delve into those details here, but it's important to understand that DNS is key to routing e-mail successfully and efficiently. James is an MTA, while the JavaMail API provides a framework for an MUA. In this article, we'll use JavaMail to set up a test for our James installation. In the second article in this series, we'll use the James Mailet API to show how you can develop your own James applications.


James design objectives

James was designed to accommodate certain objectives. For example, it is written entirely in the Java language to maximize portability. It was written to be secure and provides a number of features that both protect the server environment itself and provide secure services. James functions as a multithreaded application that takes advantage of many of the benefits available in the Avalon framework. (Avalon is an Apache Jakarta project that features the Phoenix high-performance server infrastructure. Understanding Avalon is useful but not necessary to developing James applications. See the Resources section for more on Avalon.)
James provides a comprehensive set of services, including many that are usually available only in high-end or well-established e-mail servers. These services are primarily implemented using the Matcher and Mailet APIs, which work together to provide e-mail detection and processing capabilities. James supports the standard e-mail protocols (SMTP, POP3, IMAP), along with a few others, using a loosely coupled plug-in design that keeps the messaging framework abstracted from the protocols. This is a powerful idea that may enable James to act as more of a general messaging server in the future or to support alternative messaging protocols such as instant messaging.
The final and most interesting objective delivered by the James design group is the notion of mailets, which provide a component life cycle and container solution for developing e-mail applications. To be sure, it's always been possible to use other MTAs, such as Sendmail, to do this, given that any program can be called and data piped through executables to do the job, but James provides a common, simple API for accomplishing these goals and makes the work easy, thanks to the objects available for manipulation. We'll take a closer look at both the Matcher and Mailet APIs in this article.


Quick Start With James 2.3.1


Make sure your firewall allows the email ports.
Extract the tar file.
Go to the $JAMES_HOME/bin directory.
You may have to change permissions on a few of the shell scripts to get James to run.

chmod 755 $JAMES_HOME/bin/run.sh
chmod 755 $JAMES_HOME/bin/phoenix.sh

At this point, you can run $JAMES_HOME/bin/run.sh, or $JAMES_HOME/bin/phoenix.sh
Running $JAMES_HOME/bin/phoenix.sh gives this:

Usage: $JAMES_HOME/bin/phoenix.sh {start|stop|run|restart|check}

So run

$JAMES_HOME/bin/phoenix.sh start

Let it go for a few minutes.
Then run

$JAMES_HOME/bin/phoenix.sh stop

Configuring James


In order to get James to do something useful, you need to edit the configuration file. This file is $JAMES_HOME/apps/james/SAR-INF/config.xml. You can view the default James configuration file here. To edit this file I used NetBeans, since it has good XML editing features. It has drop-down menus which make it easy to find sub-tags in XML. In this post I use notation for XML tags like this: root/tag/sub-tag/sub-sub-tag.
First, you need to put in the IP address of your DNS servers. On a Unix or Linux machine, you can get this information by looking at /etc/resolf.conf. Put the IP addresses in the config/dnsserver/servers tag, with a “server” tag for each IP address. This will be at lines 758-765 in the default config.xml file.
Next, type the domain names you want James to handle. As far as I know, even if you type in two different domains, like “daydomain.com” and “nightdomain.com”, then any user accounts you put into James will be for both domains. So joe.schmoe@daydomain.com will be the same user as joe.schmoe@nightdomain.com. Put the domains in the config/James/servernames section, with a servername for each domain. This will be lines 54-57 in the default config file.
It is also a good idea to change the password (and maybe the username as well) for the Remote Manager. This is a utility that James uses to manage users. User information can be stored in the database, but so far the documentation for that is not very good. To use Remote Manager, you must log into the server upon which James is running, and telnet to the port specified at config/remotemanager/port, which is line 778 in the default config file. The username and password information is at config/remotemanager/handler/administrator_accounts section, which is at lines 795-799 in the default config file. You may also want to change the server name in the config/remotemanager/handler/helloName section to match what you entered in the config/James/servernames/servername section, but I do not think this is necessary.
It is also good to change the postmaster address, which is line 35 in the default config file, at config/James/postmaster.



Adding Users In James


The default James configuration file has a section for the Remote Manager beginning on line 778, and ending on line 806. To use the Remote Manager, you must telnet to the machine running James on the port specified in the configuration file. By default it is port 4555. The James web site has a page about configuring the Remote Manager, but I was not able to find any information about using it. It is pretty easy to use, but it would be nice if there was a list of the commands. You can get a list of the commands by typing help:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Welcome root. HELP for a list of commands
 help
 Currently implemented commands:
 help                                    display this help
 listusers                               display existing accounts
 countusers                              display the number of existing accounts
 adduser [username] [password]           add a new user
 verify [username]                       verify if specified user exist
 deluser [username]                      delete existing user
 setpassword [username] [password]       sets a user’s password
 setalias [user] [alias]                 locally forwards all email for ‘user’ to ‘alias’
 showalias [username]                    shows a user’s current email alias
 unsetalias [user]                       unsets an alias for ‘user’
 setforwarding [username] [emailaddress] forwards a user’s email to another email address
 showforwarding [username]               shows a user’s current email forwarding
 unsetforwarding [username]              removes a forward
 user [repositoryname]                   change to another user repository
 shutdown                                kills the current JVM (convenient when James is run as a daemon)
 quit                                    close connection
Here is a quick sample session:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
user@machine:/path/to/james$ telnet localhost 4555
 Trying 127.0.0.1…
 Connected to localhost.
 Escape character is ‘^]’.
 JAMES Remote Administration Tool 2.3.1
 Please enter your login and password
 Login id:
 rmusername
 Password:
 rmpassword
 Welcome rmusername. HELP for a list of commands
verify Grumpy
 User Grumpy exists
 adduser genericuser badpassword
 User genericuser added
 verify genericuser
 User genericuser exists
 ^[[A^[[B
 Unknown command
 listusers
 Existing accounts 4
 user: Happy
 user: Grumpy
 user: Sleepy
 user: genericuser
 deluser genericuser
 User genericuser deleted
 listusers
 Existing accounts 3
 user: Happy
 user: Grumpy
 user: Sleepy
 quit
 Bye
 Connection closed by foreign host.

Apache james 3.0 beta4
Add domain :
./james-cli.sh -h localhost -p 9999 adddomain tssdemo.com

Add User :
 ./james-cli.sh -h localhost -p 9999 adduser shivang@tssdemo.com shivang

List Existing User :
./james-cli.sh -h localhost listusers

List Existing Domain :
./james-cli.sh -h localhost listdomains


Reference: