javaandroidandroid-broadcastreceiver

Trying to count number of times the phone is unlocked


i tired this a few months ago but failed.
what i'm trying to do is count the number of times the user unlocks his phone and show it on the screen but i'm getting vague numbers each time i unlock the phone.
my code is a follows.
My main activity oncreate

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    startService(new Intent(getApplicationContext(), LockService.class));
    TextView ticker;
    ticker = (TextView) findViewById(R.id.textView);
    ticker.setText(String.valueOf(Tick.tick));
    Log.e("but this is awesome ", String.valueOf(Tick.tick));
}

The Service class

public class LockService extends Service {
@Override
public IBinder onBind(Intent intent) {
    return null;
}

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_USER_PRESENT);
    final BroadcastReceiver mReceiver = new ScreenReceiver();
    registerReceiver(mReceiver, filter);
    return super.onStartCommand(intent, flags, startId);
}
public class LocalBinder extends Binder {
    LockService getService() {
        return LockService.this;
    }
}

} The BroadcastReceiver Class

public class ScreenReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;


    @Override
    public void onReceive(final Context context, final Intent intent) {
        Log.e("test", "onReceive");
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            wasScreenOn = false;
            Log.e("test", "wasScreenOn" + wasScreenOn);
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            wasScreenOn = true;
            Log.e("test", "wasScreenOn and user present" + wasScreenOn);
        } else if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
            Tick.tick ++;
            Log.e("test", "userpresent" + Tick.tick);
        }
    }

}

please help me understand what i'm doing wrong


Solution

  • I believe what's happening is this: each time you open your activity, you call start service. So even if your service is already running, onStartCommand is being called. This way, you register your broadcast multiple times, and then when you unlock your device your counters are being incremented for each time you reciver has been registered. You should do one of these options: 1. Define your recievers in your manifest so you won't have to deal with registration and unregisteration each time. 2. Register you recievers in your service onCreate instead onStartCommand. Also, make sure you unregister them in your service onDestroy.