全局窗口一

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> 
<uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW" />

通过activity.getWindow().addContectView()可以在activityz中添加控件


import java.util.Random;

import android.app.Activity;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;

import com.archermind.http.view.LrcTextView;

public class TopWindow extends Activity {
	
	private LrcTextView tv = null;
	private boolean isAlwaysShow = true;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (tv == null){
			tv = new LrcTextView(TopWindow.this);
			tv.setOnClickListener(new View.OnClickListener() {
				
				public void onClick(View v) {
					Random r  =new Random(System.currentTimeMillis());
					tv.updatePosition(r.nextInt(600),r.nextInt(300));
					
				}
			});
		}
		show();
		finish();
	}
	
	@Override
	protected void onDestroy() {
		if(!isAlwaysShow){
			close();
		}
		super.onDestroy();
	}

	private void close(){
		if (tv != null && tv.isShown()) {
			WindowManager wm = (WindowManager)getSystemService(WINDOW_SERVICE);
			wm.removeView(tv);
		}
	}
	
	private void show(){
		if (tv == null)
			tv = new LrcTextView(TopWindow.this);
		if(tv.isShown())
			return;
		Rect frame = new Rect();  
		getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  
		LrcTextView.TOOL_BAR_HIGH = frame.top;  
		
		//此处如果直接getSystemService(WINDOW_SERVICE); 
		//在点击home的时候会文本框会被隐藏
		WindowManager wm = (WindowManager)getApplicationContext().getSystemService(WINDOW_SERVICE);
		WindowManager.LayoutParams params = LrcTextView.params;
		
		params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT | WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;
		params.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL | LayoutParams.FLAG_NOT_FOCUSABLE;
		
		params.width = 200;
		params.height = 60;
		params.alpha = 100;//透明度
		
		params.gravity=Gravity.LEFT|Gravity.CENTER;
		params.x = 0;
		params.y = 0;
		
		wm.addView(tv, params);
	}
}

你可能感兴趣的:(窗口)