将数据从服务发送到BroadCastReceiver Activity

时间:2016-09-12 13:14:13

标签: android broadcastreceiver android-service

我有一个问题,即通过BroadcastReceiver将数据从Service发送到Android中的新Activity ....

服务:

    package gavrilyuk.com.example.bleservice2;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by gavriluks on 12.09.2016.
 */
public class LocationService extends Service {

    public static final String BROADCAST_ACTION = "COORDS_RECEIVED";
    private static final int TWO_MINUTES = 1000 * 60 * 2;
    public LocationManager locationManager;
    public MyLocationListener listener;
    public Location previousBestLocation = null;

    Intent intent;
    int counter = 0;

    @Override
    public void onCreate()
    {
        super.onCreate();
        intent = new Intent(BROADCAST_ACTION);

        Log.d("SERVICE_CREATE", String.valueOf(intent));
    }

/*
    @Override
    public void onStart(Intent intent, int startId)
    {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        listener = new MyLocationListener();
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 4000, 0, listener);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 4000, 0, listener);
    }
*/

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        listener = new MyLocationListener();
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 4000, 0, listener);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 4000, 0, listener);

        return START_STICKY;
//        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }

    protected boolean isBetterLocation(Location location, Location currentBestLocation) {
        if (currentBestLocation == null) {
            // A new location is always better than no location
            return true;
        }

        // Check whether the new location fix is newer or older
        long timeDelta = location.getTime() - currentBestLocation.getTime();
        boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
        boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
        boolean isNewer = timeDelta > 0;

        // If it's been more than two minutes since the current location, use the new location
        // because the user has likely moved
        if (isSignificantlyNewer) {
            return true;
            // If the new location is more than two minutes older, it must be worse
        } else if (isSignificantlyOlder) {
            return false;
        }

        // Check whether the new location fix is more or less accurate
        int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
        boolean isLessAccurate = accuracyDelta > 0;
        boolean isMoreAccurate = accuracyDelta < 0;
        boolean isSignificantlyLessAccurate = accuracyDelta > 200;

        // Check if the old and new location are from the same provider
        boolean isFromSameProvider = isSameProvider(location.getProvider(),
                currentBestLocation.getProvider());

        // Determine location quality using a combination of timeliness and accuracy
        if (isMoreAccurate) {
            return true;
        } else if (isNewer && !isLessAccurate) {
            return true;
        } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
            return true;
        }
        return false;
    }



    /** Checks whether two providers are the same */
    private boolean isSameProvider(String provider1, String provider2) {
        if (provider1 == null) {
            return provider2 == null;
        }
        return provider1.equals(provider2);
    }



    @Override
    public void onDestroy() {
        // handler.removeCallbacks(sendUpdatesToUI);
        super.onDestroy();
        Log.v("STOP_SERVICE", "DONE");
        locationManager.removeUpdates(listener);
    }

    public static Thread performOnBackgroundThread(final Runnable runnable) {
        final Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    runnable.run();
                } finally {

                }
            }
        };
        t.start();
        return t;
    }




    public class MyLocationListener implements LocationListener
    {

        public void onLocationChanged(final Location loc)
        {
            Log.i("**************************************", "Location changed");
            if(isBetterLocation(loc, previousBestLocation)) {

                Log.d("LOCATION_SERVICE", String.valueOf(loc));

                loc.getLatitude();
                loc.getLongitude();

                intent.putExtra("Latitude", loc.getLatitude());
                intent.putExtra("Longitude", loc.getLongitude());
                intent.putExtra("Provider", loc.getProvider());
                sendBroadcast(intent);
//                intent.addFlags(intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(intent);
            }
        }

        public void onProviderDisabled(String provider)
        {
            Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
        }


        public void onProviderEnabled(String provider)
        {
            Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
        }


        public void onStatusChanged(String provider, int status, Bundle extras)
        {

        }

    }

}

我希望从服务中接收信息的ACtivity:

package gavrilyuk.com.example.bleservice2;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class eceiverActivity extends AppCompatActivity {

    BroadcastReceiver receiver;
    IntentFilter filter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_eceiver);

        Log.d("RECEIVER_ACTIVITY", "CREATE");
    }

    @Override
    protected void onStart() {
        filter = new IntentFilter();
        filter.addAction(LocationService.BROADCAST_ACTION);

        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d("RECEIVER_ACTIVITY", "TEST");
            }
        };

        registerReceiver(receiver, filter);
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}

修改 startService:

private static final int SPLASH_DISPLAY_LENGTH = 1000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new Handler().postDelayed(new Runnable(){
            @Override
            public void run() {
                /* Create an Intent that will start the Menu-Activity. */
//                startService(new Intent(MainActivity.this, MyService.class));
                startService(new Intent(MainActivity.this, LocationService.class));
                finish();
            }
        }, SPLASH_DISPLAY_LENGTH);
    }

在清单中我注册了服务和活动...... 任何人都可以帮助我,因为我无法弄清楚为什么我无法在Activity中收到信息...似乎onReceive没有启动......我无法让它工作......

已解决的问题 所以我以第二种方式解决了这个沟通问题:

private static ReceiverActivity ins = null;
protected void onCreate(Bundle savedInstanceState) {.. ins = this; ..}
    public static ReceiverActivity getInstance()
    {
        Log.d("RECEIVER_ACTIVITY", "Instance => " + ins);

        return ins;
    }
    public void updateTextView(final double lat, final double lng)
    {
        ReceiverActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                txt_coords = (TextView)findViewById(R.id.txtCoords);
                txt_coords.setText("Latitude: " + lat + "\r\n" + "Longitude: " + lng);
            }
        });
    }

1 个答案:

答案 0 :(得分:0)

从我能看到的情况来看,您注册了广播接收器,但根本没有启动该服务,因此 onStartCommand 从未被解雇过。如果您希望从此服务的eceiverActivity接收服务数据,则需要在此活动中启动该服务,而在其他活动(MainActivity)中

@Override
    protected void onStart() {

      Intent serviceIntent = new Intent(eceiverActivity .this, LocationService.class);
      startService(serviceIntent);

        filter = new IntentFilter();
        filter.addAction(LocationService.BROADCAST_ACTION);

        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d("RECEIVER_ACTIVITY", "TEST");
            }
        };

        registerReceiver(receiver, filter);
        super.onStart();
    }