Android BroadcastReceiver gets multipe events while listening for screen on/off events

83 views Asked by At

I have a litle problem while programing on my application. I'm programing a service which shows me how many times my phone was active in the last 24 hours. I’m doing this by listening for screen on/off action, and I’m getting more and more receives by pusshing the button.

Actually I gat a pattern in it, so:

logs getherd = logs getterd in the previus button puss * 2 - 8

My Reciver class:

package com.example.balinator.androidprojekt.services.screenonservice;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.display.DisplayManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Display;

import com.example.balinator.androidprojekt.database.Database;

import java.util.Set;

/**
 * Created by Balinator on 2016. 12. 15..
 */
public class MyScreenOnOffReciver extends BroadcastReceiver {
    private static final String tag = "MyScreenOnOffReciver";

    private Database db;

    @Override
    public void onReceive(Context context, Intent intent) {
        String state = intent.getAction();

        if (state.equals(Intent.ACTION_SCREEN_ON)) {
            if(db == null){
                db = new Database(context);
            }
            db.open();
            long id = db.getService(MyScreenOnService.sName).getId();
            db.createServiceLog(id,System.currentTimeMillis() + ":on");
            db.close();
            Log.d(tag,"screen on log");
        }else if(state.equals(Intent.ACTION_SCREEN_OFF)) {
            if (db == null) {
                db = new Database(context);
            }
            db.open();
            long id = db.getService(MyScreenOnService.sName).getId();
            db.createServiceLog(id, System.currentTimeMillis() + ":off");
            db.close();
            Log.d(tag, "screen off log");
        }
    }
}
1

There are 1 answers

0
Mr.Popular On

I think you registered your receiver 2 times

  1. At activity
  2. manifest

Register your receiver one time by using any one of the above.. then it ll b fyn