首先,WebView
开始在服务上加载不可见(setVisibility(View.INVISIBLE)
)的网址。并等到网址加载完成。
最后,设置可见性显示(setVisibility(View.VISIBLE)
),WebView
显示空屏幕(白屏)约0.5秒。然后显示渲染的网页。
我想立即在没有空屏幕的WebView上显示呈现的网页。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(this, ServiceViewManager.class));
setUI();
}
private void setUI()
{
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(createLoadUrlInvisible());
layout.addView(createShowWebView());
this.setContentView(layout);
}
private Button createLoadUrlInvisible()
{
Button button = new Button(this);
button.setText("LoadUrlInvisible (Click first)");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
WebPageServiceView.instance().loadUrlInvisible();
}
});
return button;
}
private Button createShowWebView()
{
Button button = new Button(this);
button.setText("ShowWebView (Click second)");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
WebPageServiceView.instance().setVisibility(View.VISIBLE);
}
});
return button;
}
}
public class ServiceViewManager extends Service {
private static ServiceViewManager inst = null;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
public static ServiceViewManager Instance()
{
return inst;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
inst = this;
return START_NOT_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
inst = null;
super.onDestroy();
}
public void add(final View view, final WindowManager.LayoutParams params)
{
((WindowManager)getSystemService(Service.WINDOW_SERVICE)).addView(view, params);
}
}
public class WebPageServiceView extends FrameLayout {
private static WebPageServiceView inst = null;
public WebPageServiceView() {
super(ServiceViewManager.Instance());
}
public static WebPageServiceView instance() {
if(inst == null)
inst = new WebPageServiceView();
return inst;
}
private void addViewToService()
{
WindowManager.LayoutParams serviceParams = new WindowManager.LayoutParams();
serviceParams.x = 0;
serviceParams.y = 0;
serviceParams.type = WindowManager.LayoutParams.TYPE_PHONE;
serviceParams.flags = WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
serviceParams.format = PixelFormat.TRANSPARENT;
ServiceViewManager.Instance().add(this, serviceParams);
}
private void addWebViewAndLoadUrl()
{
WebView webView = new WebView(getContext());
webView.loadUrl("http://naver.com");
webView.setWebViewClient(new WebViewClient());
this.addView(webView);
}
public void loadUrlInvisible() {
addViewToService();
addWebViewAndLoadUrl();
setVisibility(INVISIBLE);
}
}