gpt4 book ai didi

android - 整个应用程序的 float View

转载 作者:太空宇宙 更新时间:2023-11-03 11:13:08 24 4
gpt4 key购买 nike

我需要在我的所有应用程序中有一个 float View 。
我可以使用 Window_service,但我不需要将 View 置于应用程序之外。
仅在我的应用程序内。

我也不希望用户看到“在其他应用程序上绘制”权限。
我还能怎么做?

最佳答案

我不得不做类似的事情。在我的例子中,我希望我的所有日​​志记录语句都显示在整个应用程序上方(类似于 Android 设备中的 Developer Options -> Show CPU Usage 设置)。

在我的例子中,我只是想在应用程序顶部显示一个 TextView,但您几乎可以用自己的布局替换它。

这是我使用的代码示例:

import android.app.Service;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Binder;
import android.os.IBinder;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.BackgroundColorSpan;
import android.view.WindowManager;
import android.widget.TextView;

public class OverlayService extends Service {

private final IBinder mBinder = new LocalBinder();
private TextView mTextView;
private Spannable mSpannable;

public class LocalBinder extends Binder {
public OverlayService getService() {
return OverlayService.this;
}
}

@Override
public IBinder onBind(Intent intent) {
return mBinder;
}

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

mTextView = new TextView(this);
mTextView.setTextSize(10);
mTextView.setTextColor(Color.WHITE);

WindowManager.LayoutParams params = new WindowManager.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY, 0 | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.addView(mTextView, params);
}

public void setText(String text) {

mSpannable = new SpannableString(text);
mSpannable.setSpan(new BackgroundColorSpan(0xD993d2b9),0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

// simple logic to only display 10 lines
if(mTextView.getLineCount() > 10) {
mTextView.setText(mSpannable);
} else {
mTextView.append(mSpannable);
}
mTextView.append("\n");

}

@Override
public void onDestroy() {
super.onDestroy();
if (mTextView != null) {
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.removeView(mTextView);
}
}
}

然后您可以从您的 Activity 连接到此服务并设置它的文本,如下所示:

ServiceConnection mConnection = new ServiceConnection() {

@Override
public void onServiceConnected(ComponentName className, IBinder service) {
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
}

@Override
public void onServiceDisconnected(ComponentName arg0) {
}
};

Intent intent = new Intent(context, OverlayService.class);
context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
mService.setText("Sending a test message");

如果您不希望该服务位于其他应用之上,您当然需要在用户离开该应用后立即销毁该服务。

关于android - 整个应用程序的 float View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21465614/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com