测试代码
这段代码的主要功能是使用Timer 定时更新计数。
public class TestTimerActivity extends Activity{
private final static String TAG=TestTimerActivity.class.getSimpleName();
private Timer mWaitTimer;
private Handler mHandler;
private TextView mTextView;
private int mTimes;
@Override
protected void onCreate(Bundle savedInstanceState ) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_timer_activity);
mTextView = (TextView) findViewById(R.id.textView);
mTextView.setText("TestTimer!");
mTimes =0;
mHandler = new Handler() {
public void handleMessage(Message msg){
switch (msg.what){
case 1:
mTextView.setText(""+mTimes);
}
super.handleMessage(msg);
}
};
TimerTask mTimerTask = new TimerTask(){
@Override
public void run()
{
mTimes++;
Message msg = new Message();
msg.what = 1;
mHandler.sendMessage(msg);
}
};
mWaitTimer = new Timer(true);
mWaitTimer.schedule(mTimerTask,1000,1000);
}
}
获取栈顶信息
android 5.0 之后官方屏蔽了获取栈顶信息的api,如下的方法在大多数机器上可用:
public String getTaskPackname() {
ActivityManager.RunningAppProcessInfo currentInfo = null;
Field field = null;
int START_TASK_TO_FRONT = 2;
String currentApp = "CurrentNULL";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
try {
field = ActivityManager.RunningAppProcessInfo.class.getDeclaredField("processState");
} catch (Exception e) {
e.printStackTrace();
}
ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appList = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo app : appList) {
if (app.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
Integer state = null;
try {
state = field.getInt(app);
} catch (Exception e) {
e.printStackTrace();
}
if (state != null && state == START_TASK_TO_FRONT) {
currentInfo = app;
break;
}
}
}
if (currentInfo != null) {
currentApp = currentInfo.processName;
}
} else {
ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses();
currentApp = tasks.get(0).processName;
}
// Log.e("TAG", "Current App in foreground is: " + currentApp);
return currentApp;
}