2010-11-04 3 views
3

Я тестировал отправку и прием широковещательных сообщений в своем приложении, но у меня есть проблема. Служба запускается, и я получаю Toast, чтобы сказать, что передача была отправлена, но onReceive никогда не вызывается в классе myMapView. Я включил только код, который, по моему мнению, ниже, ... любая помощь была бы высоко оценена. Я не думаю, что правильно регистрирую приемник.Широковещательный приемник onReceive() никогда не вызывал - Android

Заранее спасибо.

public class myLocationService extends Service implements LocationListener { 
    private static final String GEO_LNG = "GEO_LNG"; 
    private static final String GEO_LAT = "GEO_LAT"; 

    private void updateWithNewLocation(Location location){ 


    if (location != null){ 

      Double geoLat = location.getLatitude() * 1E6; 
      Double geoLng = location.getLongitude() * 1E6; 

      Intent intent = new Intent(this, myMapView.class); 
      intent.putExtra(GEO_LNG,geoLng); 
      intent.putExtra(GEO_LAT, geoLat); 
      sendBroadcast(intent); 
      Toast.makeText(myLocationService.this, "Broadcast sent", Toast.LENGTH_SHORT).show(); 
     } 
    else{ 
     Toast.makeText(myLocationService.this, "Location = null", Toast.LENGTH_SHORT).show(); 
    } 

} 
} 


public class myMapView extends MapActivity{ 
    private static final String GEO_LNG = "GEO_LNG"; 
    private static final String GEO_LAT = "GEO_LAT"; 


@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.map_layout);  

    IntentFilter filter = new IntentFilter(); 
    filter.addAction(GEO_LONG); 
    filter.addAction(GEO_LAT); 
    registerReceiver(locationRec, filter); 

    Intent i = new Intent(this, myLocationService.class); 

      startService(i); 
} 

    private BroadcastReceiver locationRec = new BroadcastReceiver(){ 
     @Override 
     public void onReceive(Context context, Intent intent) { 
         double geoLng = intent.getExtras().getDouble(GEO_LONG); 
         double geoLat = intent.getExtras().getDouble(GEO_LAT); 
      Toast.makeText(GeoTrailsMap.this, "Got broadcast", Toast.LENGTH_LONG).show(); 


     } 
    }; 

Редактировать Я изменил мой код, чтобы посмотреть, как это, но я все еще не имея каких-либо удачи с приема передач.

public class myLocationService extends Service implements LocationListener { 
private static final String GEO_LNG = "GEO_LNG"; 
private static final String GEO_LAT = "GEO_LAT"; 
public static final String LOCATION_UPDATE = "LOCATION_UPDATE"; 

private void updateWithNewLocation(Location location){ 


if (location != null){ 

     Double geoLat = location.getLatitude() * 1E6; 
     Double geoLng = location.getLongitude() * 1E6; 

     Intent intent = new Intent(this, myMapView.class); 
     intent.putExtra(GEO_LNG,geoLng); 
     intent.putExtra(GEO_LAT, geoLat); 
     intent.setAction(LOCATION_UPDATE); 
     sendBroadcast(intent); 
     Toast.makeText(myLocationService.this, "Broadcast sent", Toast.LENGTH_SHORT).show(); 
    } 
    else{ 
    Toast.makeText(myLocationService.this, "Location = null", Toast.LENGTH_SHORT).show(); 
    } 

} 
} 


public class myMapView extends MapActivity{ 
private static final String GEO_LNG = "GEO_LNG"; 
private static final String GEO_LAT = "GEO_LAT"; 
private static final String LOCATION_UPDATE = myLocationService.LOCATION_UPDATE; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.map_layout);  

    IntentFilter filter = new IntentFilter(); 
    filter.addAction(LOCATION_UPDATE); 
    registerReceiver(locationRec, filter); 

    Intent i = new Intent(this, myLocationService.class); 

    startService(i); 
} 

private BroadcastReceiver locationRec = new BroadcastReceiver(){ 
    @Override 
    public void onReceive(Context context, Intent intent) { 
        double geoLng = intent.getExtras().getDouble(GEO_LNG); 
        double geoLat = intent.getExtras().getDouble(GEO_LAT); 
     Toast.makeText(GeoTrailsMap.this, "Got broadcast", Toast.LENGTH_LONG).show(); 


    } 
}; 

ответ

2

Намерение, что стреляет не имеет набор действий. При вызове «AddAction» в IntentFilter здесь:.

IntentFilter filter = new IntentFilter(); 
    filter.addAction(GEO_LNG); 
    filter.addAction(GEO_LAT); 
    registerReceiver(locationRec, filter); 

Вы добавлять действия, приемник будет слушать (в данном случае приемник будет слушать GEO_LNG и GEO_LAT

В службе где вы стреляете намерение, намерение должно содержать это действие для того, чтобы приемника запятнать его Решит, какой вы хотите отправить, а затем изменить код Intent-огневого выглядеть следующим образом:.

 Intent intent = new Intent(this, myMapView.class); 
     // Here you're using GEO_LNG as both the Intent action, and a label 
     // for data being passed over. Might want to change that for clarity? 
     intent.putExtra(GEO_LNG, geoLng); 
     intent.putExtra(GEO_LAT, geoLat); 
     intent.setAction(GEO_LNG); 
     ... 
+0

Hi спасибо за это! Я думаю, что я почти там, пожалуйста, вы можете взглянуть на мое редактирование и посмотреть, что вы думаете? Все еще не получаю трансляции .. – siu07

+0

Привет, я получил его работу. Я изменил эту строку Intent intent = new Intent (this, myMapView.class); to .. Intent intent = new Intent(); и это сработало – siu07

0

AndroidManifest.xml должна включать в себя:

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

Вместо того, чтобы использовать радиовещательный приемник попробовать:

private LocationManager locationManager; 
    private GeoUpdateHandler geoUpdateHandler; 

    public void onCreate(Bundle bundle) { 
      super.onCreate(bundle); 
      geoUpdateHandler = new GeoUpdateHandler(); 
      locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 
        0, geoUpdateHandler); 
} 

public void onStop() 
    { 
     locationManager.removeUpdates(geoUpdateHandler); 
     super.onStop(); 

    } 

public class GeoUpdateHandler implements LocationListener { 

     private boolean _bLocationChangeReceived = false; 

     public void onLocationChanged(Location location) { 
      int lat = (int) (location.getLatitude() * 1E6); 
      int lng = (int) (location.getLongitude() * 1E6); 
      GeoPoint point = new GeoPoint(lat, lng); 
      if(!_bLocationChangeReceived) 
      { 
      mapController.animateTo(point); // mapController.setCenter(point); 
      _bLocationChangeReceived = true; 
      } 
      OverlayItem overlayitem = new OverlayItem(point, "Testing", "My location!"); 
      itemizedoverlay.resetOverlay(overlayitem, 0); 
     } 

     public void onProviderDisabled(String provider) { 
     } 

     public void onProviderEnabled(String provider) { 
     } 

     public void onStatusChanged(String provider, int status, Bundle extras) { 
     } 
    } 
Смежные вопросы