4

我正在为盲人开发一个 Android 导航应用程序。所以自然不用在屏幕上显示地图。我的代码现在通过构建一个 url 然后解析 html 文档来获取路径。我想让这个活,即我想在他/她偏离道路或走错方向时处理这个案子,我希望我的应用程序提醒他。

使用谷歌地图功能可以做到这一点吗?如果可能,请提供有关该功能的详细信息,或者如果不存在此类功能,那么是否可以使用现有功能并以某种方式使用它来帮助解决问题。

这是我现在的代码:

public class GPSTracking extends Activity implements
        TextToSpeech.OnInitListener
{

    protected static final int RESULT_SPEECH_start = 1;
    protected static final int RESULT_SPEECH_end = 2;
    protected static final int RESTART_ALL = 3;
    //total distance travelled till last turn
    Float totalDistance;
    //distance to be travelled from present point to the next point
    Float obtainedDistance;
    //upper button
    Button btnShowLocation;
    //bottom button
    Button btnShowLocationNo;
    //to narate what user should do. 
    TextToSpeech tts;
    //used to get name of current location
    Geocoder geocoder;
    //used to find positioning feature
    GPS gps;
    //start and position of the journey
    String startPosition=null, endPosition=null;
    //strings containing the path.
    String[] string = null;
    //vibrate the mobile
    Vibrator viberator;
    //indexing the present value of string which contains the path
    int i = 0;
    //to maintain proper order of events
    int steps=0;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //button on top
        btnShowLocation = (Button) findViewById(R.id.trueButton);
        //button on the lower side
        btnShowLocationNo = (Button) findViewById(R.id.falseButton);
        //initialising the text to speech
        tts = new TextToSpeech(this, this);
        //initialising the vibrator.
        viberator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        //to know what the current location
        btnShowLocation.setOnClickListener(new View.OnClickListener() {
            //to avoid start of multiple threads
            boolean mytaskStarted=false;
            String str=null;
            @Override
            public void onClick(View v) {
                if(steps==0){
                    //to make sure values are reset
                    totalDistance=(float)0;
                    obtainedDistance=(float)0;
                    mytaskStarted=false;
                    string=null;
                    str=null;
                    i=0;                    
                    //only ask for initial position if not set
                    if(startPosition == null){
                        speakOut("Please enter the start position");
                        //takes the input using speech to text
                        intentGenerator(RESULT_SPEECH_start);
                    }
                    else{
                        //to enter the destination
                        speakOut("press the button again");
                        steps=1;
                    }
                }
                else if(steps==1){
                    //to enter the destination
                    speakOut("Please enter the destination");
                    intentGenerator(RESULT_SPEECH_end);
                }
                else if(steps==2){
                    //for a impatient user
                    speakOut("please wait");
                    //to avoid start of many asynchronous task
                    if(!mytaskStarted){
                        mytaskStarted=true;
                        //asynchronous task to find the path to be followed
                        new GetPath().execute();
                    }
                }
                else if(steps==3){
                    if (string != null && i < string.length) {
                        if(gps!=null && gps.isGpsEnabled()){
                            speakOut(i + 1 + " " + string[i]);
                            if(i>0 && i<string.length-1 && (string[i]+" ").lastIndexOf(" m ")>-1){
                                str=(string[i]+" ").substring(0,(string[i]+" ").lastIndexOf(" m ")+3);
                                obtainedDistance=Float.parseFloat(str.substring(1+str.substring(0,str.substring(0,str.lastIndexOf(" ")).lastIndexOf(" ")).lastIndexOf(" "),str.substring(0,str.lastIndexOf(" ")).lastIndexOf(" ")));
                                //increment only when present distance greater than distance in present string so that one will know when to turn.
                                if(((totalDistance+obtainedDistance)-gps.getApprximateDistance())<10)
                                {
                                    i++;
                                    totalDistance=totalDistance+obtainedDistance;
                                }
                            }
                            else if(i>0 && i<string.length-1 && (string[i]+" ").lastIndexOf(" km ")>-1){
                                str=(string[i]+" ").substring(0,(string[i]+" ").lastIndexOf(" km ")+4);
                                obtainedDistance=Float.parseFloat(str.substring(1+str.substring(0,str.substring(0,str.lastIndexOf(" ")).lastIndexOf(" ")).lastIndexOf(" "),str.substring(0,str.lastIndexOf(" ")).lastIndexOf(" ")));    
                                obtainedDistance*=1000;
                                //increment only when present distance greater than distance in present string so that one will know when to turn.
                                if(((totalDistance+obtainedDistance)-gps.getApprximateDistance())<10)
                                {
                                    i++;
                                    totalDistance=totalDistance+obtainedDistance;
                                }
                            }
                            else if(i==0 ){
                                i++;
                            }
                        }
                        else if(gps!=null){
                            gps.resetDistance();
                            gps.stopUsingGPS();
                            //if gps not working.
                            speakOut(i + 1 + " " + string[i]);
                            i++;
                        }
                        else{
                            speakOut(i + 1 + " " + string[i]);
                            i++;
                        }
                    } else if (string != null &&  i >= string.length) {
                        i = 0;
                    }
                }
            }

        });
        //to get present location
        btnShowLocation.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            if(gps==null){
                gps = new GPS(AndroidGPSTrackingActivity.this);
            }
            if (gps.canGetLocation()) {
                double longitude = gps.getLongitude();
                double latitude = gps.getLatitude();
                Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());                 
                try {
                    //obtain the address of present location 
                    List<Address> listAddresses = geocoder.getFromLocation(latitude, longitude, 1);
                    if(null!=listAddresses&&listAddresses.size()>0){
                        if (listAddresses.size() > 0) {
                            StringBuilder result = new StringBuilder();
                            for(int i = 0; i < listAddresses.size(); i++){
                                Address address =  listAddresses.get(i);
                                int maxIndex = address.getMaxAddressLineIndex();
                                for (int x = 0; x <= maxIndex; x++ ){
                                    if(address.getAddressLine(x)!=null){
                                        result.append(address.getAddressLine(x));
                                        result.append(",");
                                    }
                                }
                                if(address.getLocality()!=null){
                                    result.append(address.getLocality());
                                    result.append("\n\n");
                                }
                            }
                            //if position accurate
                           if(gps.isGpsEnabled()){
                               speakOut(result.toString()+" is Your current location");
                               startPosition=result.toString();
                               Toast.makeText(
                                        getApplicationContext(),startPosition,
                                        Toast.LENGTH_LONG).show();
                           } else if(gps.isNetworkEnabled()){
                               speakOut(result.toString()+" is Your current approximate location. You have to give input of your present location on your own.");
                               Toast.makeText(
                                        getApplicationContext(),result.toString(),
                                        Toast.LENGTH_LONG).show();
                           }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                gps.showSettingsAlert();
                startPosition=null;
                speakOut(" please turn on gps");
            }
            return false;
        }
    });
        //to know what the previous direction string
        btnShowLocationNo.setOnClickListener(new View.OnClickListener() {
            int j=0;
            @Override
            public void onClick(View arg0) {
                if(string!=null && j<string.length){
                    speakOut(j + 1 + " " + string[j]);
                    j++;
                }
                else if(string!=null && j>=string.length){
                    j=0;
                }
            }
        });
        //to reset all values for fresh start
        btnShowLocationNo.setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                // TODO Auto-generated method stub
                speakOut("Values reset");
                steps=0;
                string=null;
                i=0;
                startPosition=null;
                gps.stopUsingGPS();
                gps=null;
                endPosition=null;
                return false;
            }
        });
    }
    //function to handle he text obtained from speech to text.
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
        //set the start 
        case RESULT_SPEECH_start:
            if (resultCode == RESULT_OK && null != data) {
                ArrayList<String> text = data
                        .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                Toast.makeText(getApplicationContext(), text.get(0),
                        Toast.LENGTH_SHORT).show();
                startPosition = text.get(0);
                steps=1;
                //speakOut("please press button again");

            }
            else{
                steps=0;
            }
            break;
            //to set the end
        case RESULT_SPEECH_end:
            if (resultCode == RESULT_OK && null != data) {
                ArrayList<String> text = data
                        .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                Toast.makeText(getApplicationContext(), text.get(0),
                        Toast.LENGTH_SHORT).show();
                endPosition = text.get(0);              
                steps=2;
            }
            else{
                steps=1;
            }
            break;
        }
    }

    //function to generate intent to take speech input
    public void intentGenerator(int code) {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
        try {
            startActivityForResult(intent, code);
        } catch (ActivityNotFoundException a) {
            Toast.makeText(getApplicationContext(),
                    "Opps! Your device doesn't support Speech to Text",
                    Toast.LENGTH_SHORT).show();
            speakOut("Opps! Your device doesn't support Speech to Text");
        }
    }
    //mobile gives instruction.
    private void speakOut(String text) {
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
        while (tts.isSpeaking()) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    //asynchronous task to get the path. THIS IS USED TO AVOID OVERLOAD THE MAIN THRED AND AVOID FORCE CLOSE OF THE APPLICATION
    private class GetPath extends AsyncTask<Void, Void, Void> {
        @Override 
        protected Void doInBackground(Void... params) {
            try {
                string=null;
                String html="";
                //forming url
                URL net = new URL(("http://maps.google.com/maps?saddr="+startPosition+" &daddr= "+endPosition).replaceAll(" ","%20"));
                URLConnection netConnection = null;
                netConnection = net.openConnection();
                //to take the input from google maps
                BufferedReader in = null;
                in = new BufferedReader(new InputStreamReader(netConnection.getInputStream()));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    html+=inputLine;
                }
                //jsoup parser to parse the document obtained from google maps
                Document doc = Jsoup.parse(html);
                //obtain necessary part of the document
                Elements el = doc.getElementsByClass("dir-mrgnr");
                //to remove html tags
                String str = el.text();
                str = str.replaceAll("[0-9]+[.] ", "\n");
                string = str.split("\n");
            } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            // TODO Auto-generated method stub
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            //so that on press of button again mobile can read the directions to users  
            steps=3;
        }
    }

    @Override
    public void onDestroy() {
        //shutdown
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        super.onDestroy();
    }

    @Override
    protected void onStart() {
        gps = new GPS(AndroidGPSTrackingActivity.this);
        super.onStart();
    }

    @Override
    protected void onStop() {
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        if(gps!=null){
            gps.stopUsingGPS();
        }
        super.onStop();
    }

    @Override
    public void onInit(int status) {
        //initialising the text to speech  
        if (status == TextToSpeech.SUCCESS) {
            int result = tts.setLanguage(Locale.US);
            if (result == TextToSpeech.LANG_MISSING_DATA
                    || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Log.e("TTS", "Language is not supported");
            } else {
                btnShowLocation.setEnabled(true);
            }
        } else {
            Log.e("TTS", "Initilization Failed");
        }
    }
}
4

0 回答 0