2016-07-25 5 views
0

Я пытаюсь показать GPS-координаты на карте Google. Я получаю GPS-координаты через SMS. Создание и создание приложений выполняется правильно, но после запуска приложения на реальном устройстве (Android-kitkat) карта google ничего не отображает, и как только я получаю координаты GPS через SMS, аварийные сообщения приложения отображают «к сожалению карта остановлена». мой код:Получение GPS-координат по SMS и показать на карте google

import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.os.Build; 
import android.support.v4.app.FragmentActivity; 
import android.os.Bundle; 
import android.telephony.SmsManager; 
import android.widget.Toast; 

import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.OnMapReadyCallback; 
import com.google.android.gms.maps.SupportMapFragment; 
import com.google.android.gms.maps.model.LatLng; 
import com.google.android.gms.maps.model.MarkerOptions; 

public class MapsActivity extends FragmentActivity implements  
OnMapReadyCallback { 

static private GoogleMap mMap; 
int index=0;//index of SMS recieved 
int index2=0; 
char[] Lat=new char[15]; 
char[] Lon=new char[15]; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_maps); 
    // Obtain the SupportMapFragment and get notified when the map is ready to be used. 
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
      .findFragmentById(R.id.map); 
    mapFragment.getMapAsync(this); 
} 
private BroadcastReceiver mReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 

    // Get the data (SMS data) bound to intent 
     Bundle bundle = intent.getExtras(); 
    SmsMessage[] msgs = null; 

     String str = ""; 
     String format = bundle.getString("format"); 

     if (bundle != null) 
     { 
      Object [] pdus = (Object[]) bundle.get("pdus"); 

      msgs= new SmsMessage[pdus.length]; 

      for (int i = 0; i < messages.length; i++) 
      { 
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
        String format = myBundle.getString("format"); 
        messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i], format); 
       } 
       // else { 
       // messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); 
       //} 
       strMessage += messages[i].getOriginatingAddress(); 
       strMessage += " : "; 
       strMessage += messages[i].getMessageBody(); 
       index=strMessage.indexOf(":"); 
       index2=strMessage.indexOf(","); 
       strMessage.getChars(index,index2,Lat,0);//extracting latitude from Latitude: to , 
       index=strMessage.lastIndexOf(":");//getting last index of : which will be Longitude: 
       index2=strMessage.length();//getting the length of string 
       strMessage.getChars(index,index2,Lon,0);//extracting longitude from : to last char of string 
       strMessage += "\n"; 
      } 

      Toast.makeText(context, strMessage, Toast.LENGTH_SHORT).show(); 
      update_location(); 
     } 
      } // bundle is null 
     } 
@Override 
public void onMapReady(GoogleMap googleMap) { 
    mMap = googleMap; 

    // Add a marker in Sydney and move the camera 
    LatLng venkateshnagar = new LatLng(20.8781753,15.3481637); 
    mMap.addMarker(new MarkerOptions().position(venkateshnagar).title("random location for startup")); 
    mMap.moveCamera(CameraUpdateFactory.newLatLng(venkateshnagar)); 
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(venkateshnagar,18)); 
} 




void update_location(){ 
double Lat1=Double.parseDouble(Lat.toString()); 
double Lon2=Double.parseDouble(Lon.toString()); 
    LatLng found=new LatLng(Lat1,Lon2); 
    mMap.addMarker(new MarkerOptions().position(found).title("this is current location")); 
    mMap.moveCamera(CameraUpdateFactory.newLatLng(found)); 
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(found,18)); 
    } 
    } 

Что я сделал не так.

+0

Добавить аварийный журнал на ваш вопрос. – TDG

+0

Ваш приемник 'getSMS' должен быть' public', что, скорее всего, вызывает сбои при получении СМС. Не знаете о вашей карте. –

+0

@ Mike M: если я сделал это публично, то Manifest покажет, что этот класс не найден. Как получить доступ к этому классу? –

ответ

0

Теперь его работы. Я использовал MarkerOptions options в методе update_location() моей программы. А потом byusing options.position(found) Вот обновленный метод:

public void update_Loc() 
    {            // Instantiating MarkerOptions class 
    MarkerOptions options = new MarkerOptions(); 
    // Toast.makeText(getApplicationContext(), Lat.toString()+Lon.toString(), Toast.LENGTH_LONG).show(); 
    double Lat1=Double.parseDouble(Lat); 
    double Lon2=Double.parseDouble(Lon); 
    LatLng found=new LatLng(Lat1,Lon2); 
    options.position(found); 
    Marker mapMarker=mMap.addMarker(options); 
    options.title("This is the current location"); 
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(found,26)); 
} 

Я надеюсь, что он будет другим, которые пытаются сделать приложение, как я.

Смежные вопросы