私は数ヶ月前にこれを疲れましたが失敗しました。
私がしようとしているのは、ユーザーが自分の電話のロックを解除して画面に表示する回数を数えることですが、電話のロックを解除するたびにあいまいな数字が表示されます。
私のコードは以下の通りです。
私の主な活動の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));
}
Serviceクラス
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);
}
}
}
私が間違ってやっている
ありがとうございました!最初のやり方はわからないので、私は2番目のアプローチを取ってそれがうまくいったのです。 – pavitran
アプリのカウントは電話のロックが解除された回数ですが、電話機をいったん使用しないで放置しておくと、ゼロに戻ってしまう理由を教えてください。 – pavitran
はい、しばらくするとアンドロイドはメモリからあなたのアプリを削除し、Tickクラスは削除されています。 ティックをSharedPreferencesに保存し、毎回編集する必要があります。 この方法では削除されません。 –