应用FC获取位置后

时间:2012-08-04 13:06:51

标签: android gps location android-location

应用程序部队从GPS获取位置后关闭!请帮忙!我用过 获取位置的this代码。但我仍然遇到问题!
MainActivity.java

package com.locationremind.app;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.locationremind.app.MyLocation.LocationResult;

public class LocationReminderActivity extends Activity {
    //Location loc;
    Context context;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        context=this;
        Button btn_ok=(Button) findViewById(R.id.btn_set);
        EditText txt_msg=(EditText) findViewById(R.id.txt_alarm);
        String msg= txt_msg.getText().toString();
        btn_ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                LocationResult locationResult = new LocationResult(){
                    @Override
                    public void gotLocation(Location location){
                        //Got the location
                        try {
                            Toast.makeText(context, "Location set to\n Latitude:"+location.getLatitude()+",Longitude:"+location.getLongitude(), Toast.LENGTH_LONG).show();
                            doWithLocation(location);
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            Toast.makeText(context, "Error Finding Location"+e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }};


                MyLocation myLocation = new MyLocation();
                myLocation.getLocation(context, locationResult);          
                };
        });
            }       
    public boolean doWithLocation(Location location) throws NullPointerException
    {
        if(location==null)
            return false;
        TextView tv_lat= (TextView) findViewById(R.id.tv_lat);
        tv_lat.setVisibility(View.VISIBLE);
        TextView tv_lat_value=(TextView) findViewById(R.id.tv_lat_value);
        tv_lat_value.setText(Double.toString(location.getLatitude()));
        tv_lat_value.setVisibility(View.VISIBLE);
        TextView tv_long=(TextView) findViewById(R.id.tv_long);
        tv_long.setVisibility(View.VISIBLE);
        TextView tv_long_value=(TextView) findViewById(R.id.tv_long_value);
        tv_long_value.setText(Double.toString(location.getLongitude()));
        tv_long_value.setVisibility(View.VISIBLE);
        //loc.set(location);
        return true;
    }
}

MyLocation.java

package com.locationremind.app;

import java.util.Timer;
import java.util.TimerTask;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

public class MyLocation {
    Timer timer1;
    LocationManager lm;
    LocationResult locationResult;
    boolean gps_enabled=false;
    boolean network_enabled=false;
    Context con;
    public boolean getLocation(Context context, LocationResult result)
    {   con=context;
        //I use LocationResult callback class to pass location value from MyLocation to user code.
        locationResult=result;
        if(lm==null)
            lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        //exceptions will be thrown if provider is not permitted.
        try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){ex.printStackTrace();}
        try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){ex.printStackTrace();}

        //don't start listeners if no provider is enabled
        if(!gps_enabled && !network_enabled)
            return false;

        if(gps_enabled)
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
        //if(network_enabled)
            //lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
        timer1=new Timer();
        timer1.schedule(new GetLastLocation(), 60*2*1000);
        return true;
    }

    LocationListener locationListenerGps = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            //lm.removeUpdates(locationListenerNetwork);
        }
        @Override
        public void onProviderDisabled(String provider) {
            Toast.makeText(con.getApplicationContext(), "Please enable GPS in Settings!", Toast.LENGTH_LONG).show();
            Message msg = handler.obtainMessage();
             msg.arg1 = 1;
             handler.sendMessage(msg);
        }
        @Override
        public void onProviderEnabled(String provider) {}
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };
    private final Handler handler = new Handler() {
         @Override
        public void handleMessage(Message msg) {
              if(msg.arg1 == 1){
                    // Without this in certain cases application will show ANR
                        AlertDialog.Builder builder = new AlertDialog.Builder(con.getApplicationContext());
                        builder.setMessage("Your GPS is disabled! Would you like to enable it?").setCancelable(false).setPositiveButton("Enable GPS", new DialogInterface.OnClickListener() {
                             @Override
                            public void onClick(DialogInterface dialog, int id) {
                                  Intent gpsOptionsIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                  con.startActivity(gpsOptionsIntent);
                              }
                         });
                         builder.setNegativeButton("Do nothing", new DialogInterface.OnClickListener() {
                              @Override
                            public void onClick(DialogInterface dialog, int id) {
                                   dialog.cancel();
                              }
                         });
                         AlertDialog alert = builder.create();
                         alert.show();
                   }


           }
    };


    class GetLastLocation extends TimerTask {
        @Override
        public void run() {
             lm.removeUpdates(locationListenerGps);
             //lm.removeUpdates(locationListenerNetwork);

             Location  gps_loc=null;
             if(gps_enabled)
                 gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
             //if(network_enabled)
               //  net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

             //if there are both values use the latest one
             if(gps_loc!=null){
                 //if(gps_loc.getTime()>net_loc.getTime())
                     locationResult.gotLocation(gps_loc);
                 //else
                     //locationResult.gotLocation(net_loc);
                 return;
             }

             //if(gps_loc!=null){
               //  locationResult.gotLocation(gps_loc);
                 //return;
             //}
             /*if(net_loc!=null){
                 locationResult.gotLocation(net_loc);
                 return;
             }*/
             //locationResult.gotLocation(null);
        }

    }

    public static abstract class LocationResult{
        public abstract void gotLocation(Location location);
    }
}  

AndroidManifest.xml

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

    <uses-sdk android:minSdkVersion="10" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".LocationReminderActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".NotificationClass"
            android:label="YOU ARE IN PROXIMITY AREA!!!"
            android:exported="false">
            <intent-filter>
                <action android:name="com.locationsensor.notif"/>
                <category android:name="android.intent.category.DEFAULT"/> 
            </intent-filter>
        </activity>
    </application>

</manifest>  

请帮忙。我在真正的手机上尝试过,我在这里发帖。我不想使用网络位置。有什么建议吗?

0 个答案:

没有答案