Android 如何使用窗口管理器将线性布局添加为系统警报

Android 如何使用窗口管理器将线性布局添加为系统警报,android,Android,我遵循了下面的教程,了解了如何使用窗口管理器在教程中将简单视图添加到所有其他窗口之上的图像 当我尝试在ImageView中使用它时,它就像一个符咒。当我尝试使用ViewGroup子类(如线性布局)执行此操作时,不会显示任何内容,我也不知道为什么 这是我的密码 package com.example.servicedialogexample; import android.app.ActionBar; import android.app.AlertDialog; import android.

我遵循了下面的教程,了解了如何使用窗口管理器在教程中将简单视图添加到所有其他窗口之上的图像

当我尝试在ImageView中使用它时,它就像一个符咒。当我尝试使用ViewGroup子类(如线性布局)执行此操作时,不会显示任何内容,我也不知道为什么

这是我的密码

package com.example.servicedialogexample;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class HelloService extends IntentService {

    private WindowManager windowManager;
    private LinearLayout m_viwAlert;
    private ImageView im;

    public HelloService()
    {
        super("HelloService");

        m_viwAlert = null;
        windowManager = null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

        m_viwAlert = new LinearLayout(this);
        im = new ImageView(this);
        im.setImageResource(R.drawable.ic_launcher);


        WindowManager.LayoutParams params1 = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);

        params1.gravity = Gravity.TOP | Gravity.LEFT;

        ((LinearLayout)m_viwAlert).addView(im, params1);

        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);
        params.gravity = Gravity.TOP | Gravity.LEFT;
        params.x = 0;
        params.y = 100;

        windowManager.addView(m_viwAlert, params);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (m_viwAlert != null)
        {
            windowManager.removeView(m_viwAlert);
        }

    }
}
我不确定我在这里做错了什么


提前感谢您的帮助:

这里是您的建议;对不起

我把你的代码复制了一遍,自己试着看能不能帮上忙。我在onCreate和onDestroy中放了一些日志,结果发现onDestroy被立即调用了

现在我自己对IntentService不太了解,但我开始使用它

startService(context, HelloService.class);
也许你应该检查你的代码没有这样做,因为事情是这样的;我把它从IntentService改为just Service;你的代码很好地发挥了作用

愉快的调查;我希望我能帮上更多的忙