2016-11-24 8 views
0

画面の状態を取得するには、以下のコードがあります。私がしようとしているのは、携帯電話が開かれている間、またはAndroidアプリケーションで使用中の経過時間を測定するための一種のクロノメーターを作成することです。画面がオンになっているときに、電話が使用されている、私はこの方法を考えた。それ以外の方法があれば、私は知りたい。 答えはhereは良くない、私は試してみたが、それはonresumeを働かなかった、私はなぜ知りません...また、それは良い方法ではなく、プロではないと思う。電話が使用されている間の経過時間を計算するためにあなたの助けが必要です。おかげであなたはどんなUI interractionを使用せずにそれを行うことができます携帯電話の使用中に経過時間を測定する方法

public class MainActivity extends Activity { 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    ///start calculating the elapsed time 

    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON); 
    filter.addAction(Intent.ACTION_SCREEN_OFF); 
    BroadcastReceiver mReceiver = new ScreenReceiver(); 
    registerReceiver(mReceiver, filter); 

} 

@Override 
protected void onPause() { 
    if (ScreenReceiver.screenMod) { 
     Toast.makeText(getApplicationContext(),"turn off",Toast.LENGTH_SHORT).show(); 

     /////stop calculating 
    } else { 
    } 
    super.onPause(); 
} 

@Override 
protected void onResume() { 
    if (!ScreenReceiver.screenMod) { 
     Toast.makeText(getApplicationContext(),"turn on",Toast.LENGTH_LONG).show(); 

     ////continue calculating 
    } else { 
    } 
    super.onResume(); 
} 
} 

ScreenReceiver.class

public class ScreenReceiver extends BroadcastReceiver { 

public static boolean screenMod = true; 

@Override 
public void onReceive(Context context, Intent intent) { 
    if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { 

     screenMod = false; 
    } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { 

     screenMod = true; 
    } 
} 
} 

答えて

0

。あなたの放送受信機をマニフェストで宣言するだけです。 Intent.ACTION_SCREEN_ONを取得すると、System.currentTimeMillis()でシステム時間を保持する変数を作成します。 Intent.ACTION_SCREEN_OFFイベントが発生したときに保持する別の変数を保存します。電話使用時間をミリ秒単位で取得する値との差を計算します。前回のsharedpreferencesとの合計

関連する問題