How to create Google Maps in Widget in android - android

I am thinking of making widget for Android that can display Google Maps.
Though i have made two classes one inheriting with MapActivity and the other with AppWidgetProvider but i am not sure how to use them. Could any one help it out?
package com.leaning.widget;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.widget.RemoteViews;
public class MapWidgo extends AppWidgetProvider {
MapGoogle obj = new MapGoogle();
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// TODO Auto-generated method stub
super.onUpdate(context, appWidgetManager, appWidgetIds);
for(int i=0;i<appWidgetIds.length;i++)
{
int appWidgetId = appWidgetIds[i];
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://maps.google.com"));
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
RemoteViews remote = new RemoteViews(context.getPackageName(), R.layout.main);
remote.setOnClickPendingIntent(R.id.webView1, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, remote);
}
}
}
now below is my MapGoogle Class
package com.leaning.widget;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
public class MapGoogle extends MapActivity {
#Override
protected void onCreate(Bundle icicle) {
// TODO Auto-generated method stub
super.onCreate(icicle);
MapView mapview = (MapView) findViewById(R.id.mySecretMap);
mapview.setBuiltInZoomControls(true);
final MapController controller = mapview.getController();
LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener listener = new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
controller.setCenter(new GeoPoint((int)location.getLongitude(),(int)location.getLatitude()));
}
};
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0, listener);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
and the last one is my manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.leaning.widget"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<uses-library android:name="com.google.android.maps" />
<receiver android:name=".MapWidgo">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="android.appwidget.provider" android:resource="#xml/widgetresource"/>
</receiver>
<activity android:name=".MapGoogle">
</activity>
</application>
I want a quick solution!

maybe you can have a web service which reads a google map url and convert it to an image.
The,n what you need is simply a widget able to show an image from a web URL (there are many on Play)

Related

How to send notifications when app was closed

I am creating an android app that consists of android push notifications.Here i need the push notifications that will run even when the app was closed. I had achieved it by calling the notification in a service. But here when i was running the code in the android >5.x devices my code was running perfectly even when app was closed notification was coming for every 5 sec but when i was running app on devices <5.x notifications was displaying only when the app was opened or when it was minimised not receiving any notifications when app was closed can any one help me what my mistake is and this is my code
SERVICE:
package com.example.servicesandroid;
import java.util.Timer;
import java.util.TimerTask;
import com.example.servicesandroid.MainActivity.MyTimerTask;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;
public class Androidservice extends Service {
final static String ACTION = "NotifyServiceAction";
final static String STOP_SERVICE = "";
final static int RQS_STOP_SERVICE = 1;
NotifyServiceReceiver notifyServiceReceiver;
private static final int MY_NOTIFICATION_ID = 1;
private NotificationManager notificationManager;
private Notification myNotification;
Timer timer;
TimerTask timer_task;
Handler handler;
#Override
public void onCreate() {
// TODO Auto-generated method stub
notifyServiceReceiver = new NotifyServiceReceiver();
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
MyTimerTask myTask = new MyTimerTask();
Timer myTimer = new Timer();
myTimer.schedule(myTask, 5000, 1500);
// TODO Auto-generated method stub
return Service.START_STICKY;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
this.unregisterReceiver(notifyServiceReceiver);
super.onDestroy();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public class NotifyServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
int rqs = arg1.getIntExtra("RQS", 0);
if (rqs == RQS_STOP_SERVICE) {
stopSelf();
}
}
}
class MyTimerTask extends TimerTask {
public void run() {
generateNotification(getApplicationContext(), "Hello");
}
}
private void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
String appname = context.getResources().getString(R.string.app_name);
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
Notification notification;
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MainActivity.class), 0);
// To support 2.3 os, we use "Notification" class and 3.0+ os will use
// "NotificationCompat.Builder" class.
if (currentapiVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
notification = new Notification(icon, message, 0);
notification.setLatestEventInfo(context, appname, message,
contentIntent);
notification.flags = Notification.FLAG_AUTO_CANCEL;
notificationManager.notify((int) when, notification);
} else {
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context);
notification = builder.setContentIntent(contentIntent)
.setSmallIcon(icon).setTicker(appname).setWhen(0)
.setAutoCancel(true).setContentTitle(appname)
.setContentText(message).build();
notificationManager.notify((int) when, notification);
}
}
}
This is my activity:
package com.example.servicesandroid;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent serviceIntent = new Intent(MainActivity.this,Androidservice.class);
startService(serviceIntent);
}
This is my Broadcast receiver when device reboots:
package com.example.servicesandroid;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class Boot_Completed extends BroadcastReceiver {
private final String BOOT_COMPLETED_ACTION = "android.intent.action.BOOT_COMPLETED";
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if(intent.getAction().equals(BOOT_COMPLETED_ACTION)){
Intent myIntent = new Intent(context, Androidservice.class);
context.startService(myIntent);
}
}
}
This is my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.servicesandroid"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".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=".Androidservice"/>
<receiver android:name=".Boot_Completed" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
Please any one help me with this

LocationManager requestLocationUpdates not working

I Have This Creepy problem. i am trying to get the location of my emulator. it working fine when i get the location of my emulator. but when i change my location coordinates nothing happens. gps is working fine.
Here is my code
Main.java
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class Main extends Activity {
TextView tvStatus;
LocationManager lm;
boolean gpsEnabled;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvStatus = (TextView) findViewById(R.id.textView1);
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Log.d("", "GPS is Active");
Location l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
tvStatus.setText(l.getLatitude()+" , "+l.getLongitude());
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1,
Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location arg0) {
tvStatus.setText("GPS ENABLED: " + gpsEnabled
+ "\nLatitude: " + arg0.getLatitude()
+ "\nLongitude: " + arg0.getLongitude());
}
});
}
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.enabelinglocationprovider"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="5"
android:targetSdkVersion="10" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.enabelinglocationprovider.Main"
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>
</manifest>
Samsung phones have this problem. There is hack to this. You need to kick the locationmanager on the butt to get the latest location from the maps cache.
God.locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
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(final Location location) {
}
});
currentLocation = God.locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Call getLastKnownLocation after kicking the requestLocationUpdates with 0's.
It happens with emulators, try rebooting the emulator.
Or, close both eclipse and emulator and start both again

A basic Android Service that uses GPS is causing Google Nexus One to reboot

I have created a very basic program to track GPS coordinates. The program has a button that turns a service on and off. The service simple installs a LocationListener. On each onLocationChanged the location coordinates are dumped on sd card.
The application works fine. But when I push the sleep button, the application logs data for sometime and then causes Google Nexus One to reboot.
Below I am posting the MINIMUM code that is required to reproduce this bug. I have striped extra code to avoid confusion.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.phonetracker"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".PhoneTrackerActivity"
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=".MyGPSService" android:process=":my_gps_service" />
</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.WRITE_EXTERNAL_STORAGE" />
</manifest>
layout/main.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"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<Button
android:id="#+id/on_button_click"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/on_button_click"
android:onClick="onButtonClick" />
</LinearLayout>
values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, PhoneTrackerActivity!</string>
<string name="app_name">PhoneTracker</string>
<string name="on_button_click">Start Service</string>
</resources>
PhoneTrackerActivity.java
package com.phonetracker;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class PhoneTrackerActivity extends Activity
{
private static final String TAG = "MyGPSServiceDemoActivity";
private Intent intent = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.on_button_click);
if (isMyServiceRunning())
{
button.setText("Stop Service");
}
else
{
button.setText("Start Service");
}
if (intent == null)
intent = new Intent(this, MyGPSService.class);
}
public void onButtonClick(View view)
{
Log.e(TAG, "onButtonClick");
Button button = (Button)view;
if (isMyServiceRunning())
{
stopService(intent);
button.setText("Start Service");
}
else
{
startService(intent);
button.setText("Stop Service");
}
}
private boolean isMyServiceRunning()
{
Log.e(TAG, "isMyServiceRunning");
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))
{
if ("com.gpsservicedemo.MyGPSService".equals(service.service.getClassName()))
{
return true;
}
}
return false;
}
}
MyGPSService.java
package com.phonetracker;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.os.IBinder;
import android.util.Log;
public class MyGPSService extends Service
{
private static final String TAG = "Hx2MyGPSService";
private LocationManager locationManager = null;
private GPSLocationListener gpsLocationListener = null;
#Override
public IBinder onBind(Intent arg0)
{
Log.e(TAG, "onBind");
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate()
{
Log.e(TAG, "onCreate");
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
gpsLocationListener = new GPSLocationListener();
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpsLocationListener);
}
}
#Override
public void onDestroy()
{
Log.e(TAG, "onDestroy");
super.onDestroy();
if (locationManager != null)
{
try
{
locationManager.removeUpdates(gpsLocationListener);
}
catch (Exception ex)
{
Log.e(TAG, "fail to remove location listners, ignore", ex);
}
}
gpsLocationListener.closeOperations();
}
}
GPSLocationListener.java
package com.phonetracker;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;
public class GPSLocationListener implements LocationListener
{
private static final String TAG = "Hx2GPSLocationListener";
public GPSLocationListener ()
{
Log.e(TAG, "GPSLocationListener");
}
#Override
public void onLocationChanged(Location location)
{
Log.e(TAG, "onLocationChanged");
}
#Override
public void onProviderDisabled(String provider)
{
Log.e(TAG, "onProviderDisabled");
}
#Override
public void onProviderEnabled(String provider)
{
Log.e(TAG, "onProviderEnabled");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.e(TAG, "onStatusChanged");
}
public void closeOperations()
{
Log.e(TAG, "closeOperations");
}
}
Please see if I am missing out something.

Android-Alert Dialog on location change through service

I want to pop up the alert dialog on location change through service. Here i have attached my manifest , Service and broadcastReciever codes.
In the console it is giving that .apk has been installed.
But i'm not getting any toast or alertdialog.
PLease correct me if i'm wrong.
Thanks.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ser"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="3" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<receiver android:name="com.ser.Myreceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
<service android:enabled="true"
android:name="com.ser.RunService">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</service>
</application>
</manifest>`
package com.ser;
import android.app.AlertDialog;
import android.app.Service;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
public class RunService extends Service implements LocationListener{
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
System.out.println("**inside onCreate");
super.onCreate();
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
//Intent call = new Intent(Intent.ACTION_CALL,Uri.parse("tel:+5555"));
//startActivity(call);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("ALERT")
.setTitle("Location")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
}
#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
}
}
//Reciver
package com.ser;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
//import android.widget.Toast;
//import android.util.Log;
public class Myreceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
System.out.println("MYRECEIVER");
//Toast.makeText(Myreceiver.this, "MyReciver", Toast.LENGTH_SHORT).show();
Intent serviceLauncher = new Intent(context, RunService.class);
context.startService(serviceLauncher);
//Log.v("TEST", "Service loaded at start");
}
}
create an Activity and and register receiver in this activity and start service from this activity and use alert dialog in activity class
i have modified your code and its working fine with my testing mobile device (sony xperia)
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ser"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<application android:icon="#drawable/icon" android:label="#string/app_name" android:debuggable="true">
<service android:enabled="true" android:name=".MyService">
<intent-filter>
<action android:name="com.ser.MyService">
</action>
</intent-filter>
</service>
<receiver android:enabled="true" android:name=".MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED">
</action></intent-filter>
</receiver>
</application>
MyReceiver.java
package com.ser;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "MyReceiver Started..",Toast.LENGTH_SHORT).show();
Log.v("Debug", "MyReceiver Started..");
Intent myIntent=new Intent(context,MyService.class);
context.startService(myIntent);
}
}
MyService.java
package com.ser;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
private LocationManager locManager;
private LocationListener locListener = new myLocationListener();
private boolean gps_enabled = false;
private boolean network_enabled = false;
#Override
public IBinder onBind(Intent intent) {return null;}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
Toast.makeText(getBaseContext(), "Service Started..", Toast.LENGTH_SHORT).show();
Log.v("Debug", "Service Started..");
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
try{
gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
catch(Exception ex){}
try{
network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
catch(Exception ex){}
if (gps_enabled) {
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
Log.v("Debug", "gps_enabled..");
}
if (network_enabled) {
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
Log.v("Debug", "network_enabled..");
}
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
private class myLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location location) {
if(location!=null){
Toast.makeText(getBaseContext(),"on location changed called..",Toast.LENGTH_SHORT).show();
Log.v("Debug", "on location changed method called..");
}
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
}//service closed
still have any doubts for Receiver,Service and GPS classes let me know!!
or even your can check Start Service from Broadcast Receiver and Get Current Location links for details. hope it helps!!

gps monitoring service in android

I'm trying to create a program for android that constantly (every minute) gets the gps location and then sends it to my server at home (so that i always know where my phone is).
I created a gui with a start-button which starts the service:
start.setOnClickListener(new View.OnClickListener() {
synchronized public void onClick(View v) {
startService(new Intent(GpsTest2.this, GTService.class));
}
});
Then my service is declared like this:
public class GTService extends Service implements LocationListener {
}
This GTService has a method for retrieving the data:
public void onLocationChanged(Location location) {
}
#Override
public void onCreate() {
super.onCreate();
LocationManager locMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, interval * 1000, minDist, this);
}
In AndroidManifest.xml I have:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<service android:name=".GTService">
</service>
This doesn't seem to work: no data is logged.
What am I doing wrong here?
Your code seems to be working fine except this,
You are using LocationManager.NETWORK_PROVIDER
locMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, interval * 1000, minDist, this);
Where as it should be LocationManager.GPS_PROVIDER
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2 * 1000, 10, locationListener);
Hope this will surely do for you. Thanks.
The location from Network provider is not accurate. PLease use GPS instead. If you really want to user Network only then I would recomond to set minDistance param as 0
The following should work fine,
Manifest :
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.smartconcept.locationmonitor.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=".GTService" />
</application>
GTService :
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
public class GTService extends Service implements LocationListener {
LocationManager locMgr;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate(){
super.onCreate();
locMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1 * 1000, 0, this);
}
#Override
public void onDestroy(){
super.onDestroy();
locMgr.removeUpdates(this);
}
#Override
public void onLocationChanged(Location loc) {
Toast.makeText(getBaseContext(), String.valueOf(loc.getLatitude()) + "\n" + String.valueOf(loc.getLongitude()), Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
MainActivity:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnStart = (Button)findViewById(R.id.btnStart);
btnStart.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
startService(new Intent(MainActivity.this,GTService.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.activity_main, menu);
return true;
}
}
Hope this helps.

Categories

Resources