搜索了一段时间后,我发现了如何生成程序包名称,但是无论何时有人打开或关闭应用程序,我都无法生成程序包名称,有人知道如何处理吗? 下面的代码是我用来生成程序包名称的代码。
public String getTopActivity() {
String topPackageName = "";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
// We get usage stats for the last 10 seconds
List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 10, time);
// Sort the stats by the last time used
if (stats != null) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : stats) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
topPackageName = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
Log.e("TopPackage Name", topPackageName);
}
}
}
return topPackageName;
}
答案 0 :(得分:0)
您需要为此了解活动生命周期。这是一个示例:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show("onCreate");
}
@Override
public void onStart() {
super.onStart();
show("onStart");
}
@Override
public void onRestart() {
super.onRestart();
show("onRestart");
}
@Override
public void onResume() {
super.onResume();
show("onResume");
}
@Override
public void onPause() {
super.onPause();
show("onPause: bye bye!");
}
@Override
public void onStop() {
super.onStop();
show("onStop.");
}
@Override
public void onDestroy() {
super.onDestroy();
show("onDestroy.");
}
private void show(String s) {
Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
}
现在您可以了解生命周期,请使用这些方法。从诸如getTopActivity()
,onCreate
,onStart()
之类的方法中调用onPause()
,
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getTopActivity();
}
@Override
protected void onStart() {
super.onStart();
getTopActivity();
}
@Override
protected void onPause() {
super.onPause();
getTopActivity();
}
有关更多信息和所有此类方法,请参见Activity Lifecycle。