我工作的应用程序可返回用户的位置,并从GPS获取信息。 并将位置发送给电子邮件以下代码已存在,它在Android 2.3上运行正常,但在Android 4.2.2上却无法运行。 在Android 4.2.2设备和模拟器上无法正常工作。 GPS追踪器的代码如下:

package com.example.safetymobile;

//package com.example.gpstracking;

import android.app.AlertDialog;
import android.app.Service;
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.IBinder;
import android.provider.Settings;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager .NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }       
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

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

}

全球定位系统 :

package com.example.safetymobile;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;


public class GPS extends Activity {
    String NotifyWay="";
    CheckBox chk,chk1;
    EditText edt,edt1;
    Button btn;
    GPSTracker gps;
    public int time = 0;
    public Timer t = new Timer();
    int interval = 1;
    int counter = 0;
    int counterend = 2;
    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+1:00"));
    Date currentLocalTime = cal.getTime();
    Date stopt = cal.getTime();
    int StopTime = 0;





    @SuppressLint("SimpleDateFormat")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gps);


        @SuppressWarnings("unused")
        DateFormat date = new SimpleDateFormat("HH:mm a"); 

        //chk=(CheckBox)findViewById(R.id.notiEmail);
        //chk1=(CheckBox)findViewById(R.id.notisms);

        edt=(EditText)findViewById(R.id.interval);
        edt1=(EditText)findViewById(R.id.timeStop);
        //email 
        /*chk.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                if(NotifyWay.equals(""))
                {
                    NotifyWay="Email";
                }
                else
                {
                    NotifyWay="Email";
                    chk1.setChecked(false);
                    //Toast.makeText(getApplicationContext(), "You can choose one way only", Toast.LENGTH_LONG).show();
                }
            }
        });*/

        /*chk1.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                if(NotifyWay.equals(""))
                {
                    NotifyWay="SMS";
                }
                else
                {
                    NotifyWay="SMS";
                    chk.setChecked(false);
                    //Toast.makeText(getApplicationContext(), "You can choose one way only", Toast.LENGTH_LONG).show();
                }
            }

        });*/
        btn=(Button)findViewById(R.id.DoneAdd);

        btn.setOnClickListener(new OnClickListener(){

            @SuppressWarnings("deprecation")
            @Override
            public void onClick(View v) {
                int val=Integer.parseInt(edt.getText().toString());
                StopTime=Integer.parseInt(edt1.getText().toString());
                interval=val*60000;

                SQLiteDatabase db;                      
                db = openOrCreateDatabase("Saftey.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
                db.setVersion(1);
                db.setLocale(Locale.getDefault());
                db.setLockingEnabled(true);
                final String CREATE_TABLE_setting = 
                        "CREATE TABLE GPS ("
                        + "id INTEGER PRIMARY KEY AUTOINCREMENT,"
                        + "valTime INTEGER,"
                        + "stopTime INTEGER);";
                db.execSQL(CREATE_TABLE_setting);
                ContentValues values1 = new ContentValues();
                values1.put("valTime", interval);
                values1.put("stopTime", StopTime);
                db.insert("Setting", null, values1);
                //Convert Minute To Milliseconds
                stopt.setHours(currentLocalTime.getHours() + StopTime);

                tt();


                Intent intent = new Intent(GPS.this, Change_setting.class);
                startActivity(intent);




            }

        });
    }

    @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_gps, menu);
        return true;
    }



    public void tt()
    {
        t.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                runOnUiThread(new Runnable() {

                    @SuppressWarnings("deprecation")
                    @Override
                    public void run() {

                        currentLocalTime = cal.getTime();
                        //// .....
                        if(currentLocalTime.compareTo(stopt) > 0)

                        {
                            t.cancel();
                        }
                        else
                             Toast.makeText(getApplication(), "d < d1", Toast.LENGTH_LONG).show();

                        gps = new GPSTracker(GPS.this);

                        // check if GPS enabled     
                        if(gps.canGetLocation())
                        {

                            double latitude = gps.getLatitude();
                            double longitude = gps.getLongitude();

                            String text ="https://Maps.google.com/maps?q=" + Double.toString(latitude) + "," + Double.toString(longitude)  ;// latitude
                          //............................

                             String em="";
                             //String pn="";
                             //SharedPreferences pref = getSharedPreferences("pref",0);
                             //SharedPreferences.Editor edit = pref.edit();
                             //String pn= pref.getString("PhNum", null);
                             //edit.commit();
                             SQLiteDatabase db;

                             db = openOrCreateDatabase(
                                    "Saftey.db"
                                    , SQLiteDatabase.CREATE_IF_NECESSARY
                                    , null
                                    );
                             db.setVersion(1);
                             db.setLocale(Locale.getDefault());
                             db.setLockingEnabled(true);
                             Cursor cur = db.query("info", null, null, null, null, null, null);
                             cur.moveToFirst();
                             while (cur.isAfterLast() == false) 
                             {
                                 //pn = cur.getString(0);
                                 em=cur.getString(3);
                                 cur.moveToNext();
                             }
                             cur.close();
                            // if(NotifyWay.equals("Email"))
                           //  {
                                 SendingEmail(em, text);
                           //  }
                            /* else
                             {
                                 if(NotifyWay.equals("SMS"))
                                 {
                                     SendingSMS(pn, text);
                                 }

                             }*/




                              //......................
                        }
                       else{
                            // can't get location
                            // GPS or Network is not enabled
                            // Ask user to enable GPS/network in settings
                            gps.showSettingsAlert();
                        }

                        //// .....
                        time += 1;
                    }

                });
            }

        }, 0, interval);
    }



    public void SendingEmail(String em, String text)
    {
         Mail m = new Mail("mbrm.yu@gmail.com", "mbrm_yu123"); 
          String[] toArr = {em}; 
          m.setTo(toArr); 
          m.setFrom("mbrm.yu@gmail.com"); 
          m.setSubject("This is an email sent using my Mail JavaMail wrapper from an Android device."); 
          //m.setBody("I'm in Danger Dad, please Help ...");
          m.setBody(text);
          try 
          { 
            //m.addAttachment("/sdcard/filelocation"); 

            if(m.send()) { 
              Toast.makeText(getApplication(), "Email was sent successfully.", Toast.LENGTH_LONG).show(); 
            } else { 
              Toast.makeText(getApplication(), "Email was not sent.", Toast.LENGTH_LONG).show(); 
            } 
          } 
          catch(Exception e) 
          { 
            Toast.makeText(getApplication(), "There was a problem sending the email to : " + em, Toast.LENGTH_LONG).show(); 
            Log.e("MailApp", "Could not send email", e); 
          } 
    }


    /*public void SendingSMS(String pn, String text)
    {
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
            new Intent(SENT), 0);

        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
            new Intent(DELIVERED), 0);

        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS sent", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off", 
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));

        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS delivered", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS not delivered", 
                                Toast.LENGTH_SHORT).show();
                        break;                        
                }
            }
        }, new IntentFilter(DELIVERED));        

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(pn, null, text, sentPI, deliveredPI);
        }*/

}

表现:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.safetymobile"
    android:versionCode="2"
    android:versionName="1.2" >

    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CALL_PHONE" >
    </uses-permission>
    <uses-permission android:name="android.permission.CAMERA" />

    <uses-feature android:name="android.hardware.camera" />

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >
    </uses-permission>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >
    </uses-permission>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.VIBRATE" >
    </uses-permission>
    <uses-permission android:name="android.permission.WAKE_LOCK" >
    </uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>

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

    <uses-permission android:name="android.permission.SEND_SMS" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.safetymobile.MainActivity"
            android:label="@string/app_name" 
            android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen"
            android:clearTaskOnLaunch="true"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.safetymobile.ContactList"
            android:label="@string/title_activity_contact_list" >
        </activity>
        <activity
            android:name="com.example.safetymobile.Change_setting"
            android:label="@string/title_activity_change_setting"
            android:clearTaskOnLaunch="true" >
        </activity>
        <activity
            android:name="com.example.safetymobile.CallContent"
            android:label="@string/title_activity_call_content"
            android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen" >
        </activity>
        <activity
            android:name="com.example.safetymobile.SMS"
            android:label="@string/title_activity_sms"
            android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen" >
        </activity>
        <activity
            android:name="com.example.safetymobile.Alication_list"
            android:label="@string/title_activity_alication_list"  >
        </activity>
        <activity
            android:name="com.example.safetymobile.Apps"
            android:label="@string/title_activity_apps" 
            android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen">
        </activity>
        <activity
            android:name="com.example.safetymobile.Pass"
            android:label="@string/title_activity_pass" >
        </activity>
        <activity
            android:name="com.example.safetymobile.ChangePass"
            android:label="@string/title_activity_change_pass" >
        </activity>
        <activity
            android:name="com.example.safetymobile.GPS"
            android:label="@string/title_activity_gps" >
        </activity>
        <activity
            android:name="com.example.safetymobile.LightActivity"
            android:label="@string/title_activity_light"
            android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen" >
        </activity>
        <receiver android:name=".StartupActivity">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"></action>
                <category android:name="android.intent.category.DEFAULT"></category>
            </intent-filter>
        </receiver>
    </application>

</manifest>

请任何帮助?

===============>>#1 票数:0

使用网络服务在android中获取地址

看到我发布的答案。 我的代码工作正常,但是在android 4.0及更高版本中,您必须手动打开GPS。 您无法以编程方式打开它

===============>>#2 票数:0

麻烦自己,只需使用Google Play服务位置API 如果您在设备上安装了Play服务,则它们可以提供良好的实施方式和精确的位置(大多数设备现在都可以使用)

  ask by michael translate from so

未解决问题?本站智能推荐: