试图计算手机解锁的次数

时间:2016-05-22 05:01:39

标签: java android android-broadcastreceiver

几个月前我厌倦了但是失败了 我试图做的是计算用户解锁手机并在屏幕上显示的次数,但每次解锁手机时我都会收到模糊的数字。
我的代码如下 我的主要活动是创建

@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));
}

服务类

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;
    }
}

} BroadcastReceiver类

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);
        }
    }

}

请帮助我了解我做错了什么

1 个答案:

答案 0 :(得分:1)

我相信发生的事情是这样的: 每次打开活动时,都会调用启动服务。因此,即使您的服务已在运行,也会调用onStartCommand。这样,您多次注册广播,然后当您解锁设备时,每次重新注册时计数器都会递增。 您应该执行以下选项之一: 1.在清单中定义接收方,这样您每次都不必处理注册和取消注册。 2.在服务中注册接收者onCreate而不是onStartCommand。另外,请确保在服务onDestroy中取消注册它们。