我正在尝试获取应用程序在前台的时间,并且我想在执行此操作时使用Service,因为它需要始终在后台运行。
这是我的主要活动
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startService(View view) {
Intent intent = new Intent(this, appTracker.class);
startService(intent);
}
public void stopService(View view) {
Intent intent = new Intent(this, appTracker.class);
stopService(intent);
}
}
这是我将用于此工作的服务活动。
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class appTracker extends Service {
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "App Track Starting...", Toast.LENGTH_LONG);
//should I implement this here?
UsageStats usageStats;
String PackageName = "Nothing";
long TimeInforground = 500;
int minutes = 500, seconds = 500, hours = 500;
UsageStatsManager mUsageStatsManager = (UsageStatsManager)getSystemService("usagestats");
long time = System.currentTimeMillis();
List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,
time - 1000 * 10, time);
if (stats != null) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : stats) {
TimeInforground = usageStats.getTotalTimeInForeground();
PackageName = usageStats.getPackageName();
minutes = (int)((TimeInforground / (1000 * 60)) % 60);
seconds = (int)(TimeInforground / 1000) % 60 ;
hours = (int)((TimeInforground / (1000 * 60 * 60)) % 24);
Log.i("BAC", "PackageName is" + PackageName + "Time is: "
+ hours + "h" + ":" + minutes + "m" + seconds + "s");
}
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
我的问题是我应该实现能够在onStartCommand
方法或其他地方为每个应用程序腾出时间的代码吗?提前谢谢。
答案 0 :(得分:0)
应用程序处于前台状态意味着您的某个活动当前对用户可见
我将创建一个像这样的新基础活动
public class BaseActivity extends AppCompatActivity {
....
@Override
public void onResume(){
//app is showing, start the timer
}
@Override
public void onPause(){
//app is going to background or an activity switch is occuring, pause the timer
}
}
然后,您在应用中拥有的每个活动都可以扩展此BaseActivity
public class MainActivity extends BaseActivity {
...
}
现在,您需要根据所需的计算将timer
属性保存在SharedPref或其他位置。