<uses-permission android:name="android.permission.GET_TASKS" /> <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> <!-- 使用SYSTEM_ALERT_WINDOW时必须要加 -->
import android.app.Activity; import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.graphics.PixelFormat; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.ViewGroup.LayoutParams; import android.view.WindowManager; import android.widget.TextView;
public class MainActivity extends Activity { private ActivityManager mActivityManager; private Handler popupHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: String packageName = mActivityManager.getRunningTasks(1).get(0).topActivity.getPackageName(); Log.e("log", packageName + System.currentTimeMillis()); if (packageName.equals("com.some.app.name")) { popupHandler.sendEmptyMessage(1); } if (isRunning) { popupHandler.sendEmptyMessageDelayed(0, 3500); } break; case 1: Log.e("log", "mWindowManager"); if (!isAdd) { startActivity(new Intent(MainActivity.this, MainActivity.class)); mWindowManager.addView(mTrackingText, lp); isAdd = true; } break; } } }; WindowManager mWindowManager; private boolean isRunning = true; WindowManager.LayoutParams lp; TextView mTrackingText; boolean isAdd; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); mTrackingText = new TextView(MainActivity.this); mTrackingText.setTextColor(Color.BLUE); mTrackingText.setTextSize(55); mTrackingText.setText("00:00"); lp = new WindowManager.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_APPLICATION, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT); isRunning = true; popupHandler.sendEmptyMessageDelayed(0, 3500); } }
Android ActivityManager与WindowManager
原文:http://www.cnblogs.com/niray/p/4737290.html