我需要从服务启动一个弹出窗口,在我的应用程序中执行特定的操作。我似乎没有找到一个好办法。在onCreate()里面我创建了弹出窗口但是当我用showAtLocation启动它时出现了这个错误:
10-06 13:39:49.573: ERROR/AndroidRuntime(5966): Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
有人可以帮忙吗?谢谢,
-em
答案 0 :(得分:8)
我遇到了同样的问题,如果我解决了这个问题。
我第一次尝试使用Android的原生PopupWindow
课程,但后来我决定像这样使用WindowManager
:
public class MyService extends Service {
private View mView;
private WindowManager.LayoutParams mParams;
private WindowManager mWindowManager;
@Override
public void onCreate() {
super.onCreate();
mView = new MyLoadView(this);
mParams = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT, 150, 10, 10,
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
PixelFormat.TRANSLUCENT);
mParams.gravity = Gravity.CENTER;
mParams.setTitle("Window test");
mWindowManager = (WindowManager)getSystemService(WINDOW_SERVICE);
mWindowManager.addView(mView, mParams);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
((WindowManager)getSystemService(WINDOW_SERVICE)).removeView(mView);
mView = null;
}
public class MyLoadView extends View {
private Paint mPaint;
public MyLoadView(Context context) {
super(context);
mPaint = new Paint();
mPaint.setTextSize(50);
mPaint.setARGB(200, 200, 200, 200);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawText("test test test", 0, 100, mPaint);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
您可以通过意图调用此服务类:
intent = new Intent(mContext, MyService.class);
if (intent != null) {
getContext().startService(intent);
}
另外,在清单文件中设置权限:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
我引用了Android的LoadAverageService.java
类,最后我从服务中创建了一个弹出窗口!这是一个非常简单的示例,因此如果要开发复杂的函数,可能需要添加更多内容。希望这会对你和其他人有所帮助。
答案 1 :(得分:0)
服务在没有UI的后台运行,因此您必须使用适当的Intent调用startActivity来启动相同的活动。