Service Broadcast Receiver Logs more than expected

旧街凉风 提交于 2019-12-25 02:29:00

问题


My problem is that I think my service runs multiple times. The service is controlled by a switch calling a method that starts and stops the service. I have a broadcast listener inside my service and the receiver logs whenever it receives a broadcast. at first switch on, it logs two times. After switch off and on, it logs four times.

public class Service1 extends Service implements DetectionListener {
    private static final String TAG = "ListenerService";
    private final broadcastReceiver1 receiver = new broadcastReceiver1();
    public HashMap<String, String> hashMapData;
    private ARSonicManager arSonicManager;

    public ListenerService() {
    }

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

    @Override
    public void onCreate() {
        super.onCreate();

        IntentFilter filter = new IntentFilter();
        filter.addAction("com.digify.almostrealsonic.broadcast_intent");

        registerReceiver(receiver, filter);
    }

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

    @Override
    public void onStart(Intent intent, int startId) {
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (null != intent) {
            try {
                hashMapData = (HashMap<String, String>) intent.getSerializableExtra("hashMapData");

                // Do something with hashMapData

            } catch (Exception e) {
                Log.i("onStartCommand", e.toString());
            }
        }
        return super.onStartCommand(intent, flags, startId);

    }

    @Override
    public void onMarkerDetected(String markerKey) {

        Intent intent = new Intent();
        intent.putExtra("hashMapData", hashMapData);
        intent.setAction("com.broadcastReceiver1_intent");
        sendBroadcast(intent);
    }

    public static class broadcastReceiver1 extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String hashMapData = intent.getStringExtra("hashMapData");
            Log.i("receiver", "Got message: " + hashMapData);
        }
    }
}

来源:https://stackoverflow.com/questions/25028707/service-broadcast-receiver-logs-more-than-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!