开始我以为悬浮窗口,可以用Android中得PopupWindow 来实现,虽然也实现了,但局限性非常大。比如PopupWindow必须要有载体View,也就是说,必须要指定在那个View的上面来实现。以该View为相对位置,来显示PopupWindow。这就局限了其智能在用户交互的窗口上,相对的显示。而无法自由的拖动位置和在桌面显示。
于是查阅了一些资料,有两种实现方法。一种是自定义Toast,Toast是运行于所有界面之上的,也就是说没有界面可以覆盖它。另一种是Android中得CompatModeWrapper类,ConmpatModeWrapper是基类,实现大部分功能的是它的内部类WindowManagerImpl。该对象可以通过getApplication().getSystemService(Context.WINDOW_SERVICE)得到。(注:如果是通过activity.getSystemService(Context.WINDOW_SERVICE)得到的只是属于Activity的LocalWindowManager)。
简单的介绍之后,我们直接来看代码实现,注释已经写在代码中。
MainActivity.java
package com.example.floatviewdemo;
import com.example.floatviewdemo.service.FloatViewService;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onStart() {
Intent intent = new Intent(MainActivity.this, FloatViewService.class);
//启动FloatViewService
startService(intent);
super.onStart();
}
@Override
protected void onStop() {
// 销毁悬浮窗
Intent intent = new Intent(MainActivity.this, FloatViewService.class);
//终止FloatViewService
stopService(intent);
super.onStop();
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://www.easck.com/apk/res/android"
xmlns:tools="http://www.easck.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.floatviewdemo.MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>










