开发者

Android: location; activity and service

I'm working on some application that should fetch current location and after device is located in some radius should be shown application with some message. I have a few questions. I'm trying to fetch location using

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000*60*5, 50, locationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000*60*5, 50, locationListener);
addProximityAlert(LAT,LONG);

private void addProximityAlert(double latitude, double longitude) 
        {
            Intent intent = new Intent开发者_如何学Go(this.getApplicationContext(), SOME_CLASS_HERE); 
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //Does this needed even if apllication/activity is alive?
            PendingIntent proximityIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK); //and does this needed again?
            locationManager.addProximityAlert(latitude, longitude, Radius, 0, proximityIntent);
        }
  1. If I use requestLocationUpdates then GPS is always working. And this is a waste of battery. Maybe there is some way, for example, to pause this for a several minutes? I mean use GPS every 5 minutes for example from one location fetching to next. How to realize this?

  2. If SOME_CLASS_HERE - some activity class, then how I could know if exactly this event called it? Because when ProximityAlert is triggered I need to call some activity's function as well. How could I do this?


UPD: Now I'm using only Activity (I haven't Service at all) I'm trying next:

Intent intent = new Intent(getString(R.string.intent_message_location_fetched));
PendingIntent proximityIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
locationManager.addProximityAlert(LAT, LONG, RADIUS, 0, proximityIntent);

As I understand intent with action R.string.intent_message_location_fetched should be fired after location will be around LAT LONG.

Then I'm trying to create BroadcastReciver class:

public class MyBroadcastReciver extends BroadcastReceiver {
    MyActivity mainActivity;
    public MyBroadcastReciver(MyActivity activity)
    {
        mainActivity = activity;
    }
    @Override
    public void onReceive(Context context, Intent intent) {
        mainActivity.ShowToast("Recived : " + intent.getAction());
    }
}

And register reciver in MyActivity class:

public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        myReciver = new MyBroadcastReciver(this);
        IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(getString(R.string.intent_message_location_fetched));
        registerReceiver(myReciver, intentFilter);
...

But nothing happens when I'm in LAT LONG location. What's wrong? Maybe I should register reciver in AndroidManifest.xml? But how exactly?


1.You should check the answer here for using a timer to turn on / off the location lookups via GPS : android locationManager requestLocationUpdates

It will start a timer every X seconds. During the processing of the timer, locations updates will be requested, and after a location is retrieved, it will stop the GPS listener.

2.You should send an intent after your proximity alert logic is over. You can then register a broadcast receiver that listens for that intent, and do your processing. The Intent mechanism provides a loosely coupled way of communicating between activities/services.

You can find an example of how an intent is broadcast (in your case from your proximity alert) to a broadcastreceiver (a new component in your application that will receive the intent, and process it accordingly). It also shows how to setup the receiver in the manifest to listen for your custom Intent.


If I use requestLocationUpdates then GPS is always working. And this is a waste of battery. Maybe there is some way, for example, to pause this for a several minutes? I mean use GPS every 5 minutes for example from one location fetching to next. How to realize this?

addProximityAlert() uses GPS every 4 minutes. If you want to use GPS every x minutes, run a Service and get single shot fixes every x minutes, and manually check if it is present around that area.

If SOME_CLASS_HERE - some activity class, then how I could know if exactly this event called it? Because when ProximityAlert is triggered I need to call some activity's function as well. How could I do this?

Not entirely sure what you are asking here

Here is how to use a pending intent

    PendingIntent pendingIntent;
    Intent intent = new Intent();
    intent.setClass(mContext, yourActivity.class);
    pendingIntent =  PendingIntent.getActivity(mContext, 0, intent, 0);

FLAG_ACTIVITY_NEW_TASK : This makes the launched activity the root activity for a task. If a task is already running for the activity you are now starting, then a new activity will not be started; instead, the current task will simply be brought to the front of the screen with the state it was last in.


I am using this code for getting current location of the User .

 public class HomeActivity extends Activity implements LocationListener{
public static Context mContext;
private double latitude, longitude;
 public LocationManager mLocManager;
// *******This is the new Code start on 11/4/2011 at 3 o'clock


/**
 * This is the Home Button if user Login then it is move to TennisAppActivity otherwise move to Login  
 *
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    mContext=this;
    super.onCreate(savedInstanceState);
    setContentView(R.layout.homelayout);
    

    mLocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
     
    mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
            this);
    mLocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
            0, this);
    locationUpdate();
    ((Button) this.findViewById(R.id.ButtonHome))
            .setOnClickListener(new OnClickListener() {
                public void onClick(View arg0) {
                    
                        startActivity(new Intent(HomeActivity.this,
                                DefaultDisplay.class));
                    
                }
            });

    ((Button) this.findViewById(R.id.ButtonProfile))
            .setOnClickListener(new OnClickListener() {

                public void onClick(View arg0) {
                    if (GUIStatics.boolLoginStatus) {
                        startActivity(new Intent(HomeActivity.this,
                                MyProfile.class));
                    } else {
                        Intent intent=new Intent(HomeActivity.this,
                                Login.class);
                        intent.putExtra("moveTo","MyProfile");
                        startActivity(intent);
                    }
                }
            });

    ((Button) this.findViewById(R.id.ButtonNotifications))
            .setOnClickListener(new OnClickListener() {

                public void onClick(View arg0) {
                    if (GUIStatics.boolLoginStatus) {
                        startActivity(new Intent(HomeActivity.this,
                                ShowAllNotificationActiviry.class));
                    } else {
                        Intent intent=new Intent(HomeActivity.this,
                                Login.class);
                        intent.putExtra("moveTo","ShowAllNotificationActiviry");
                        startActivity(intent);
                    }
                }
            });

    ((Button) this.findViewById(R.id.ButtonFavorites))
            .setOnClickListener(new OnClickListener() {

                public void onClick(View arg0) {
                    if (GUIStatics.boolLoginStatus) {
                        startActivity(new Intent(HomeActivity.this,
                                FavoritesActivity.class));
                    } else {
                        Intent intent=new Intent(HomeActivity.this,
                                Login.class);
                        intent.putExtra("moveTo","FavoritesActivity");
                        startActivity(intent);
                    }
                }
            });

            ((Button) this.findViewById(R.id.ButtonMore))
            .setOnClickListener(new OnClickListener() {
                public void onClick(View arg0) {
                        startActivity(new Intent(HomeActivity.this,
                                MoreListActivity.class));
                }
            });

}

public void locationUpdate()
{
    CellLocation.requestLocationUpdate();
}


public void getAddress(double lat, double lng) {
    Geocoder geocoder = new Geocoder(HomeActivity.mContext, Locale.getDefault());
    try {
        List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
        Address obj = addresses.get(0);
        String add = obj.getAddressLine(0);
        GUIStatics.currentAddress = obj.getSubAdminArea() + ","
                + obj.getAdminArea();
        GUIStatics.latitude = obj.getLatitude();
        GUIStatics.longitude = obj.getLongitude();
        GUIStatics.currentCity= obj.getSubAdminArea();
        GUIStatics.currentState= obj.getAdminArea();
        add = add + "\n" + obj.getCountryName();
        add = add + "\n" + obj.getCountryCode();
        add = add + "\n" + obj.getAdminArea();
        add = add + "\n" + obj.getPostalCode();
        add = add + "\n" + obj.getSubAdminArea();
        add = add + "\n" + obj.getLocality();
        add = add + "\n" + obj.getSubThoroughfare();

        Log.v("IGA", "Address" + add);
        // Toast.makeText(this, "Address=>" + add,
        // Toast.LENGTH_SHORT).show();

        // TennisAppActivity.showDialog(add);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
    }
}



public void onLocationChanged(Location location) {
    latitude = location.getLatitude();
    longitude = location.getLongitude();
    GUIStatics.latitude=location.getLatitude();
    GUIStatics.longitude= location.getLongitude();
    Log.v("Test", "IGA" + "Lat" + latitude + "   Lng" + longitude);
    //mLocManager.r
     
    getAddress(latitude, longitude);
    if(location!=null)
    {
        
    mLocManager.removeUpdates(this);
    }
    // Toast.makeText(this, "Lat" + latitude + "   Lng" + longitude,
    // Toast.LENGTH_SHORT).show();
}


public void onProviderDisabled(String arg0) {
    // TODO Auto-generated method stub
    Toast.makeText(HomeActivity.this, "Gps Disabled", Toast.LENGTH_SHORT).show();
    Intent intent = new Intent(
            android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    startActivity(intent);
}


public void onProviderEnabled(String arg0) {
    // TODO Auto-generated method stub
    
}


public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
     if(arg1 == 
            LocationProvider.TEMPORARILY_UNAVAILABLE) { 
                                    Toast.makeText(HomeActivity.this, 
            "LocationProvider.TEMPORARILY_UNAVAILABLE", 
            Toast.LENGTH_SHORT).show(); 
                        } 
                        else if(arg1== LocationProvider.OUT_OF_SERVICE) { 
                                    Toast.makeText(HomeActivity.this, 
            "LocationProvider.OUT_OF_SERVICE", Toast.LENGTH_SHORT).show(); 
                        } 
    
}

}

In this code you find

mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

in this method the first parameter is provide ,II- timeforupdate location, III mindistance for update request,

 mLocManager.removeUpdates(this);

the above call method remove updating of location when it get so you save battery.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜