Thursday 19 December 2013


How to start and stop service in android.


Here we see how to start and stop a service dynamically.


What is Service ?


A service is a component which runs in the background without direct interaction with the user. As the service has no user interface, it is not bound to the lifecycle of an activity. 

As there are two methods by which we start and stop service  :
  1. startService (Intent service)
  2. stopService (Intent service)

In order to start a service we need to call a method name onStartCommand(Intent intent, int flags, int startId) and to stop a service call a method name onDestroy() . All this work we do in class which extends Service class.

Create a project with the following details :

·         ProjectName: StartStopServicee
·         PackageNamesat.tuts4mobile.startstop
·         ActivityNameMainActivity

In the MainActivity.java file, copy the following code :

package sat.tuts4mobile.startstop;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.activity_main);

                        Button start = (Button) findViewById(R.id.button1);
                        start.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                                // TODO Auto-generated method stub
                                                startService(new Intent(MainActivity.this, MyService.class));
                                    }
                        });

                        Button stop = (Button) findViewById(R.id.button2);
                        stop.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                                // TODO Auto-generated method stub
                                                stopService(new Intent(MainActivity.this, MyService.class));
                                    }
                        });

            }
            @Override
            public boolean onCreateOptionsMenu(Menu menu) {
                        // Inflate the menu; this adds items to the action bar if it is present.
                        getMenuInflater().inflate(R.menu.main, menu);
                        return true;
            }

}

Create a new class name MyService.java file, copy the following code :

package sat.tuts4mobile.startstop;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service{

            @Override
            public IBinder onBind(Intent intent) {
                        // TODO Auto-generated method stub
                        return null;
            }
           
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
            // TODO Auto-generated method stub
           
                        Toast.makeText(MyService.this, "Service Started!!!", Toast.LENGTH_SHORT).show();

            return super.onStartCommand(intent, flags, startId);
    }
   
    @Override
    public void onDestroy() {
            // TODO Auto-generated method stub
           
                        Toast.makeText(MyService.this, "Service Stoped!!!", Toast.LENGTH_SHORT).show();

            super.onDestroy();
    }

}

In the activity_main.xml file, copy the following code:

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="Start Service" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="20dp"
        android:text="Stop Service" />

</RelativeLayout>

In the 
AndroidMainfest.xml file, copy the following code:

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="false"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="sat.tuts4mobile.startstop.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
       
        <service android:name="sat.tuts4mobile.startstop.MyService"></service>
       
    </application>

</manifest>

Click this to download source code

When you run the application , you see the following screens :





Thursday 12 December 2013

How to get user location in android.

Here we learn how to get user location , how to get latitude and longitude and also the address.


As there are two ways by which we can get user location :
  1. Using GPS
  2. Using Network

Pros and Cons:

  • GPS is most accurate, it quickly consumes battery power, and doesn't return the location as quickly as users want.
  • Network Location Provider determines user location using cell tower and Wi-Fi signals, providing location information in a way that works indoors and outdoors, responds faster, and uses less battery power.
Here we get location using network provider. Later on we will discuss about how to get location using GPS.


In order to get location we use the "LocationManager" class by calling "requestLocationUpdates()".
We also need to implement the "LocationListener" interface. This provide us the latitude and longitude.
If you want to get the location by name , use Geocoder class . In this class we pass the latitude and longitude and the address of that position.
To get the location in application , we need to add following permissions to the AndroidMainfest.xml file.
ACCESS_COARSE_LOCATION:
Allows an app to access approximate location derived from network location sources such as cell towers and Wi-Fi.
ACCESS_FINE_LOCATION:
Allows an app to access precise location from location sources such as GPS, cell towers, and Wi-Fi.
INTERNET:
Allows applications to open network sockets


Create a project with the following details:
  • ProjectName: LocationDemo
  • PackageNamesat.tuts4mobile.locationdemo
  • ActivityNameMainActivity
In the MainActivity.java file, copy the following code

package sat.tuts4mobile.locationdemo;

import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity implements LocationListener{

    protected LocationManager locationManager;
    TextView text;
    String data = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        text = (TextView) findViewById(R.id.textview1);
            
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
        
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        String addressline = "";
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        Geocoder geocoder = new Geocoder(MainActivity.this,Locale.getDefault());
        try {
            
            List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            if(addresses.size() ==  1)
            {
                Address address = addresses.get(0);
                String aline = "";
                for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
                {
                    aline = aline + address.getAddressLine(i) + "\n";
                }
                addressline = "Address Line : " + aline ;
                            
            }
            
        } catch (Exception e) {
            // TODO: handle exception
        }
        String temp = "Latitude:" + location.getLatitude() + "\nLongitude:" + location.getLongitude() + "\n" + addressline + "\n";
        data = data + temp;
        text.setText(data);
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
        
    }

}

In the activity_main.xml file, copy the following code:

 <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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ScrollView
        android:id="@+id/sl"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/textview1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/hello_world" />
    </ScrollView>

</RelativeLayout>

In the AndroidMainfest.xml file, copy the following code:

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="14" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="sat.tuts4mobile.locationdemo.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    
    <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"/>

</manifest>

Note:
Please test this application in real device(mobile phone) , not in emulator.
If you are running this Android app with emulator, you need to send the latitude and longitude explicitly for the emulator. How to send latitude and longitude to android emulator -
  1. Open DDMS perspective in Eclipse (Window -> Open Perspective)
  2. Select your emulator device
  3. Select the tab named emulator control
  4. In ‘Location Controls’ panel, ‘Manual’ tab, give the Longitude and Latitude as input and ‘Send’.
When you run the application you see the following screens:

After some time when location changes , its gives you new location details.