MainActivity / MapsActivity中的服务广播接收器

时间:2018-01-05 20:50:57

标签: java android service broadcastreceiver localbroadcastmanager

我有一个服务,它每秒获取当前位置,然后服务应该将带有广播的位置发送回主要活动。 根据我可以看到的日志,服务类发送广播,但MainActivity永远不会得到它。

我的服务:

public class MainActivity extends AppCompatActivity
    implements OnMapReadyCallback, 
    NavigationView.OnNavigationItemSelectedListener {

private static final String TAG = "Location";
private GoogleMap mMap;
private final static int MY_PERMISSIONS_FINE_LOCATION = 123;
track track = new track();


private BroadcastReceiver locationReceiver = new BroadcastReceiver() {

    @Override

    public void onReceive(Context context, Intent intent) {
        Log.e(TAG, "onReceive");

        String action = intent.getAction();
        LatLng pos = new LatLng(intent.getDoubleExtra("Lat", 0), 
intent.getDoubleExtra("Lon", 0));

        Log.e(TAG, "Position: " + pos + "empfangen");
        track.posAdd(pos);
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

LocalBroadcastManager.getInstance(this).registerReceiver(locationReceiver, 
new IntentFilter("GPSLocationUpdates"));
    Log.i(TAG, "BroadcastManager erstellt");
    setContentView(R.layout.activity_main);
    // Obtain the SupportMapFragment and get notified when the map is ready 
to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) 
getSupportFragmentManager()
            .findFragmentById(R.id.map);
    [...]

}

public void onMapReady(GoogleMap googleMap) {
    [...]
    startService(new Intent(this, MyService.class));
}


@Override
public void onRequestPermissionsResult(int requestCode, String 
permissions[], int[] grantResults) {....}

public void onBackPressed() {...}

@Override
public boolean onCreateOptionsMenu(Menu menu) {...}

@Override
public boolean onOptionsItemSelected(MenuItem item) {...}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {...}
}

MainActicity(包括地图):

inline-block

希望你能提供帮助

0 个答案:

没有答案