Android Gps跟踪应用程序

时间:2014-04-09 05:13:42

标签: android gps locationmanager

我开发了一个名为AndroidGpsTracking的应用程序,它运行良好。但是什么时候 我关闭我的设备并重新启动它然后它将显示不幸停止工作,我不知道 为什么会这样。

这是我的logcat:

04-09 10:32:12.521: I/log(5166): maaaap{}
04-09 10:32:12.543: D/GPS Enabled(5166): GPS Enabled
04-09 10:32:12.543: I/System.out(5166): inside location manager
04-09 10:32:12.546: D/AndroidRuntime(5166): Shutting down VM
04-09 10:32:12.547: W/dalvikvm(5166): threadid=1: thread exiting with uncaught exception (group=0x416c8d40)
04-09 10:32:12.548: E/AndroidRuntime(5166): FATAL EXCEPTION: main
04-09 10:32:12.548: E/AndroidRuntime(5166): Process: com.example.gpstracking, PID: 5166
04-09 10:32:12.548: E/AndroidRuntime(5166): java.lang.NullPointerException
04-09 10:32:12.548: E/AndroidRuntime(5166):     at com.example.gpstracking.AndroidGPSTrackingActivity$1$1$1.run(AndroidGPSTrackingActivity.java:169)
04-09 10:32:12.548: E/AndroidRuntime(5166):     at android.os.Handler.handleCallback(Handler.java:733)
04-09 10:32:12.548: E/AndroidRuntime(5166):     at android.os.Handler.dispatchMessage(Handler.java:95)
04-09 10:32:12.548: E/AndroidRuntime(5166):     at android.os.Looper.loop(Looper.java:136)
04-09 10:32:12.548: E/AndroidRuntime(5166):     at android.app.ActivityThread.main(ActivityThread.java:5102)
04-09 10:32:12.548: E/AndroidRuntime(5166):     at java.lang.reflect.Method.invokeNative(Native Method)
04-09 10:32:12.548: E/AndroidRuntime(5166):     at java.lang.reflect.Method.invoke(Method.java:515)
04-09 10:32:12.548: E/AndroidRuntime(5166):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
04-09 10:32:12.548: E/AndroidRuntime(5166):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
04-09 10:32:12.548: E/AndroidRuntime(5166):     at dalvik.system.NativeStart.main(Native Method)

这里是com.example.gpstracking代码:

package com.example.gpstracking;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;



public class AndroidGPSTrackingActivity extends Activity implements View.OnClickListener 
{

    Button btnShowLocation;
    Button btnWriteSDFile;
    Button btnClose;
    EditText txtData;
    GPSTracker gps;
    private Spinner spinner1, spinner2;
      private Button btnSubmit;

        public void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            addItemsOnSpinner2();
            checkExternalMedia();
            writeToExternalTextFile();
            readfromFilesms();
            addListenerOnButton();
            addListenerOnSpinnerItemSelection();
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

            if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
            {
                Toast.makeText(this, "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show();
            }
            else
            {
                showGPSDisabledAlertToUser();
            }
                btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
                btnShowLocation.setOnClickListener(new View.OnClickListener() 
                {

                    //@SuppressWarnings("unused")
                    public void onClick(View v)     
                    {
                        Context c = getApplicationContext();
                        SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(c);
                        SharedPreferences.Editor editor = app_preferences.edit();
                        TimerTask scanTask;
                        final Handler handler = new Handler();
                        Timer t = new Timer();
                        scanTask = new TimerTask(); 
                        {
                            GPSTracker gps;
                            List<Double> l = new ArrayList<Double>();
                            TreeMap<Double,List<Double>> list = new  TreeMap<Double,List<Double>>();
                             public void void run() 
                             {
                                    Handler handler;
                                    handler.post(new Runnable() 
                                    {


                                        public void run() 
                                        {
                                                    Context c = getApplicationContext();
                                                    SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(c);
                                                    SharedPreferences.Editor editor = app_preferences.edit();
                                                    int counter = app_preferences.getInt("counter", 0);
                                                    String list;
                                                    Log.i("log", "maaaap"+list);
                                                    Double latitude=new Double(0.0d);
                                                    Double longitude=new Double(0.0d);
                                                    ArrayList<Double> l = new ArrayList<Double>();
                                                    gps = new GPSTracker(AndroidGPSTrackingActivity.this);

                                                    if(gps.canGetLocation())
                                                    {

                                                         l.add(gps.getLatitude());
                                                         l.add(gps.getLongitude());
                                                         list.put(gps.getAccur(),l);
                                                         Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + gps.getLatitude() + "\nLong:" + gps.getLongitude()+ "\nAccracy:"+gps.getAccur(), Toast.LENGTH_SHORT).show();

                                                        Log.i("log", "latitude"+gps.getLatitude());
                                                        Log.i("log", "longitude"+gps.getLongitude());
                                                        Log.i("log", "gps.getAccur()"+gps.getAccur());
                                                        Log.d("tag", "Finding Latitude");
                                                        latitude = gps.getLatitude();
                                                        Log.d("tag", "Lat: "+String.valueOf(latitude));
                                                        Log.d("tag", "Finding Longitude");
                                                        longitude  = gps.getLongitude();
                                                        Log.d("tag", "Lon: "+String.valueOf(longitude));
                                                        String Text =
                                                        "\nLat: " + gps.getLatitude() +
                                                        "\nLan:" + gps.getLongitude()+
                                                        "\nAcrcy="+gps.getAccur();

                                                        sendSMS(readfromFilesms(), Text);

                                                    }
                                                    else
                                                    {

                                                    }

                                                if(counter<12)
                                                {
                                                    if(gps.getAccur()<=3)
                                                    {
                                                        Double  d =  (Double)list.firstKey();
                                                        Log.i("log", "gps.firstKey()"+d);

                                                        List<?> l1 = (List<?>)list.get(d);
                                                        Log.i("log", "gps.l1()"+(Double)l1.get(0));
                                                        Log.i("log", "gps.l2"+(Double)l1.get(1));
                                                        latitude = (Double)l1.get(0);
                                                        longitude = (Double)l1.get(1);
                                                        editor.putInt("counter", 0);
                                                        editor.commit(); // Very important
                                                        cancel();

                                                    }
                                                    else
                                                    {
                                                        counter = app_preferences.getInt("counter", 0);
                                                        Log.i("log", "counter"+counter);
                                                        editor.putInt("counter", ++counter);
                                                        editor.commit(); 
                                                    }

                                                }
                                                else
                                                {
                                                    Double  d =  (Double)list.firstKey();
                                                    Log.i("log", "gps.firstKey()"+d);

                                                    List<?> l1 = (List<?>)list.get(d);
                                                    Log.i("log", "gps.l1()"+(Double)l1.get(0));
                                                    Log.i("log", "gps.l2"+(Double)l1.get(1));
                                                    latitude = (Double)l1.get(0);
                                                    longitude = (Double)l1.get(1);

                                                    editor.putInt("counter", 0);
                                                    editor.commit(); // Very important
                                                    cancel();

                                                }
                                            }

                                        private void cancel() {
                                            // TODO Auto-generated method stub

                                        }
                                    });
                        Timer t;
                        TimerTask scanTask;
                        t.schedule(scanTask,1000,90000000);  
        }
                            @Override
                            public void onClick1(View v) {
                                // TODO Auto-generated method stub

                            }
        });
        btnClose = (Button) findViewById(R.id.btnClose);
        btnClose.setOnClickListener(new OnClickListener() 
        {

            public void onClick(View v) 
            {

                finish();
            }
        }); 
    }
        public void addListenerOnButton() 
        {

                spinner1 = (Spinner) findViewById(R.id.spinner1);

                spinner2 = (Spinner) findViewById(R.id.spinner2);
                btnSubmit = (Button) findViewById(R.id.btnSubmit);
                btnSubmit.setOnClickListener(new OnClickListener() 
                {

                        public void onClick(View v)
                        {
                            Toast.makeText(AndroidGPSTrackingActivity.this,
                            String.valueOf(spinner2.getSelectedItem()),
                            Toast.LENGTH_SHORT).show();
                            sendSMS(readfromFilesms(),"on leave");
                        }
                });
        }
        private void sendSMS(String phoneNumber, String message)
        {
            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);

            registerReceiver(new BroadcastReceiver()
            {   

                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",
                Toast.LENGTH_SHORT).show();
                break;
                case SmsManager.RESULT_ERROR_RADIO_OFF:
                Toast.makeText(getBaseContext(), "Radio off",
                Toast.LENGTH_SHORT).show();
                break;
                }
            }
        }, new IntentFilter(SENT));

        registerReceiver(new BroadcastReceiver()
        {

            public void onReceive(Context arg0, Intent arg1) 
            {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS Dlivered",
                    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(phoneNumber, null, message, sentPI, deliveredPI);
    }
    private void showGPSDisabledAlertToUser()
    {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
        .setCancelable(false)
        .setPositiveButton("GPS Setting",
        new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int id)
            {
                Intent callGPSSettingIntent = new Intent(
                android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(callGPSSettingIntent);
            }
        });

        AlertDialog alert = alertDialogBuilder.create();
        alert.show();
    }

    public void addItemsOnSpinner2() {

        spinner2 = (Spinner) findViewById(R.id.spinner2);
        List<String> list = new ArrayList<String>();
        list.add("Casual Leave");
        list.add("Medical Leave");

        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, list);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner2.setAdapter(dataAdapter);



 }


      public void addListenerOnSpinnerItemSelection() 
      {
        spinner1 = (Spinner) findViewById(R.id.spinner1);
        spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());

        }
      private void checkExternalMedia() 
        {

            @SuppressWarnings("unused")
            boolean mExternalStorageAvailable = false;
            @SuppressWarnings("unused")
            boolean mExternalStorageWriteable = false;
            String state = Environment.getExternalStorageState();

            if (Environment.MEDIA_MOUNTED.equals(state)) 
            {
                mExternalStorageAvailable = mExternalStorageWriteable = true;
            }   
            else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) 
            {
              mExternalStorageAvailable = true;
              mExternalStorageWriteable = false;
            } 
            else 
            {
              // Can't read or write
              mExternalStorageAvailable = mExternalStorageWriteable = false;
            }

        }
     private void writeToExternalTextFile() 
        {


            File root = android.os.Environment.getExternalStorageDirectory();
            File dir = new File(root.getAbsolutePath() + "/PhoneNumber");
            if(!dir.exists())
            dir.mkdirs();
            File file = new File(dir, "PhNumber.txt");
            if (!file.exists ())
            {
                try 
                {
                    FileOutputStream f = new FileOutputStream(file);
                    PrintWriter pw = new PrintWriter(f);
                    pw.flush();
                    pw.close();
                    f.close();
                } 
                catch (FileNotFoundException e) 
                {
                    e.printStackTrace();
                } 
                catch (IOException e) 
                {
                    e.printStackTrace();
                }
            }

        }
     private String  readfromFilesms() 
     {
            File root = android.os.Environment.getExternalStorageDirectory();
            Log.i("log", "ddddddddddddddddddddddddddddddd"+root.getAbsolutePath());
            File dir = new File(root.getAbsolutePath() + "/PhoneNumber");
            String aBuffer = "";
            File file = new File(dir, "PhNumber.txt");
            if (file.exists ())
            {
                try 
                {
                    FileInputStream fIn = new FileInputStream(file);
                    BufferedReader myReader = new BufferedReader(
                            new InputStreamReader(fIn));
                    String aDataRow = "";
                    while ((aDataRow = myReader.readLine()) != null) 
                    {
                        aBuffer += aDataRow  ;
                    }
                    myReader.close();

                } 
                catch (FileNotFoundException e) 
                {
                    e.printStackTrace();
                    Log.i("TAG",
                            "******* File not found. Did you"
                                    + " add a WRITE_EXTERNAL_STORAGE permission to the   manifest?");
                } 
                catch (IOException e) 
                {
                    e.printStackTrace();
                }
            }
            return aBuffer;
        }
    @Override
    public void onClick(View arg0) 
    {
        // TODO Auto-generated method stub

    }



}

0 个答案:

没有答案