GPS App Widget Example In Android Programming

This example explains the use of app widgets in android. This app widget that displays the GPS coordinates the device.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it GPSAppWidgetExample.

2.) Write following into res/values/strings.xml:

 

<resources>

<string name="app_name">GPSAppWidgetExample</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_gpsapp_widget_example">GPSAppWidgetExample</string>
<string name="app_info">This widget shows the GPS coordinates of the device's position. The widget refreshes the position in 15 minutes interval</string>
</resources>

 

 

3.) Create and write following into res/xml/gpswidgetinfo.xml:

 

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="294dp"
android:minHeight="72dp"
android:updatePeriodMillis="900000"
android:initialLayout="@layout/gpswidget">
</appwidget-provider>

 

 

4.) Write following into gpswidget.xml:

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/back"
android:padding="10dip">

<ImageView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:src="@drawable/widgeticon"/>

<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/txtInfo"
android:text="Waiting for GPS coordinates..."
android:textColor="#FFFFFFFF"
android:gravity="center_horizontal|center_vertical"/>

</LinearLayout>
</LinearLayout>

 

 

5.) Write following into AndroidManifest.xml:

 

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gpsappwidgetexample"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="5"
android:targetSdkVersion="15" />

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".GPSAppWidgetExample"
android:label="@string/title_activity_gpsapp_widget_example" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".GPSWidgetProvider">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/gpswidgetinfo" />
</receiver>

<service android:name=".GPSWidgetProvider$GPSWidgetService"></service>
</application>

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

Write following into main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip">

<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/widgeticon"
android:scaleType="fitCenter"/>

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="@string/app_name"
android:textSize="20dip"
android:textStyle="bold"
android:padding="10dip"/>

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="@string/app_info"/>

</LinearLayout>

 

 

6.) Add two icons back.png and widgeticon.png into your drawable folder.
7.) Run for output.

Steps:

1.) Create a project named GPSAppWidgetExample and set the information as stated in the image.

Build Target: Android 4.0
Application Name: GPSAppWidgetExample
Package Name: com. example. GPSAppWidgetExample
Activity Name: GPSAppWidgetExample
Min SDK Version: 2.0

2.) Open GPSAppWidgetExample.java file and write following code there:

 

package com.example.gpsappwidgetexample;

import android.app.Activity;
import android.os.Bundle;

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

 

 

3.) Create and Write following into GPSWidgetProvider.java:

 

package com.example.gpsappwidgetexample;

import java.util.List;

import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.RemoteViews;

public class GPSWidgetProvider extends AppWidgetProvider {
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
super.onDeleted(context, appWidgetIds);
}

@Override
public void onDisabled(Context context) {
super.onDisabled(context);
}

@Override
public void onEnabled(Context context) {
super.onEnabled(context);
}

@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
}

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);

final int N = appWidgetIds.length;

for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];

Intent intent = new Intent(context, GPSAppWidgetExample.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.gpswidget);
views.setOnClickPendingIntent(R.id.txtInfo, pendingIntent);

appWidgetManager.updateAppWidget(appWidgetId, views);
}

context.startService(new Intent(context,GPSWidgetService.class));
}

public static class GPSWidgetService extends Service{
private LocationManager manager = null;

private LocationListener listener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onProviderDisabled(String provider) {}

@Override
public void onLocationChanged(Location location) {
AppLog.logString("Service.onLocationChanged()");

updateCoordinates(location.getLatitude(),location.getLongitude());

stopSelf();
}
};

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

@Override
public void onCreate() {
super.onCreate();

AppLog.logString("Service.onCreate()");

manager = (LocationManager)getSystemService(LOCATION_SERVICE);
}

@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);

waitForGPSCoordinates();
}

@Override
public void onDestroy() {
stopListening();

AppLog.logString("Service.onDestroy()");

super.onDestroy();
}

public int onStartCommand(Intent intent, int flags, int startId) {
waitForGPSCoordinates();

AppLog.logString("Service.onStartCommand()");

return super.onStartCommand(intent, flags, startId);
}

private void waitForGPSCoordinates() {
startListening();
}

private void startListening(){
AppLog.logString("Service.startListening()");

final Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);

final String bestProvider = manager.getBestProvider(criteria, true);

if (bestProvider != null && bestProvider.length() > 0) {
manager.requestLocationUpdates(bestProvider, 500, 10, listener);
}
else {
final List<String> providers = manager.getProviders(true);

for (final String provider : providers) {
manager.requestLocationUpdates(provider, 500, 10, listener);
}
}
}

private void stopListening(){
try {
if (manager != null && listener != null) {
manager.removeUpdates(listener);
}

manager = null;
}
catch (final Exception ex) {

}
}

private void updateCoordinates(double latitude, double longitude){
Geocoder coder = new Geocoder(this);
List<Address> addresses = null;
String info = "";

AppLog.logString("Service.updateCoordinates()");
AppLog.logString(info);

try
{
addresses = coder.getFromLocation(latitude, longitude, 2);

if(null != addresses && addresses.size() > 0){
int addressCount = addresses.get(0).getMaxAddressLineIndex();

if(-1 != addressCount){
for(int index=0; index<=addressCount; ++index){
info += addresses.get(0).getAddressLine(index);

if(index < addressCount)
info += ", ";
}
}
else
{
info += addresses.get(0).getFeatureName() + ", " + addresses.get(0).getSubAdminArea() + ", " + addresses.get(0).getAdminArea();
}
}

AppLog.logString(addresses.get(0).toString());
}
catch (Exception e)
{
e.printStackTrace();
}

coder = null;
addresses = null;

if(info.length() <= 0){
info = "lat " + latitude + ", lon " + longitude;
}
else{
info += ("n" + "(lat " + latitude + ", lon " + longitude + ")");
}

RemoteViews views = new RemoteViews(getPackageName(), R.layout.gpswidget);

views.setTextViewText(R.id.txtInfo, info);

ComponentName thisWidget = new ComponentName(this, GPSWidgetProvider.class);
AppWidgetManager manager = AppWidgetManager.getInstance(this);
manager.updateAppWidget(thisWidget, views);
}
}
}

 

 

4.) Create and Write following into AppLog.java:

 

package com.example.gpsappwidgetexample;

import android.util.Log;

public class AppLog {
private static final String APP_TAG = "GPSWidget";

public static int logString(String message){
return Log.i(APP_TAG, message);
}
}

 

 

5.) Compile and build the project.

Note:- Application’s actual outcome can be tested on original device only.

Output

Leave a Comment:

3 comments
Aadam Gibson says November 8, 2012

Extremely, it’s important code of android who can learn this blog and get the good acknowledge. You have provided good example coding of android.

Reply
kaushtuv says December 18, 2012

In manifest file,where how u had taken the @xml/getwidgetinfo .I counldn’t find it ?can u plz explain it!

Reply
paypal hacker says June 4, 2013

It’s hard to come by educated people on this subject, but you sound like you know what you’re talking about! Thanks

Reply
Add Your Reply