2016-11-24 103 views
0

我有下面的代碼來獲取屏幕的狀態。我正在嘗試做的是製作一種計時器來衡量手機在我的Android應用程序中打開或使用時的流逝時間。當屏幕開啓時,手機正在使用,我想這樣。如果還有其他方法,我想知道。 答案here不好,我試過了,它沒有工作,我不知道爲什麼...我也認爲這不是一個好方法,不專業。我需要您的幫助來計算手機正在使用時的流逝時間。由於如何測量手機正在使用時的流逝時間

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

你可以做,沒有使用任何UI interraction。只需在清單中聲明您的廣播接收器。當你得到Intent.ACTION_SCREEN_ON時,用System.currentTimeMillis()創建一個保存系統時間的變量。保存另一個保存的變量當您收到Intent.ACTION_SCREEN_OFF事件時。計算您將以毫秒爲單位獲得電話使用時間的值之間的差異。總結它與上次sharepreferences