Android中浮动窗口案例

简单的例子写给自己参考。

1.BarTestMainfest.xml文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bartest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name="com.example.bartest.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!--    FloatingService-->
        <service android:name="com.example.bartest.MyService"
            android:enabled="true"></service>

    </application>
</manifest>


2. MainActivity.java
package com.example.bartest;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.Button;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
   
        Intent i = new Intent();
        i.setClassName("com.example.bartest", "com.example.bartest.MyService");
        startService(i);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

3. MyService.java
package com.example.bartest;

import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;

public class MyService extends Service{

  private View view;// 透明窗体
     private boolean viewAdded = false;// 透明窗体是否已经显示
     private WindowManager windowManager;
     private WindowManager.LayoutParams layoutParams;
        private AutoScroll auto;
     @Override
     public IBinder onBind(Intent intent)
     {
         return null;
     }
     @Override
     public void onCreate() {
         super.onCreate();
         view = LayoutInflater.from(this).inflate(R.layout.autoscroll, null);

         windowManager = (WindowManager) this.getSystemService(WINDOW_SERVICE);
       
         layoutParams = new LayoutParams(LayoutParams.FILL_PARENT,
                 LayoutParams.WRAP_CONTENT, LayoutParams.TYPE_SYSTEM_ERROR,
                 LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSPARENT);
         //layoutParams.gravity = Gravity.RIGHT|Gravity.BOTTOM; //悬浮窗开始在右下角显示
         layoutParams.gravity = Gravity.RIGHT | Gravity.TOP;
         auto=(AutoScroll)view.findViewById(R.id.TextViewNotice);
         auto.setText("测试测试测试测试");
     }

   
     private void refresh() {
         if (viewAdded) {
             windowManager.updateViewLayout(view, layoutParams);
         } else {
          //layoutParams.y = 300;
             windowManager.addView(view, layoutParams);         
             viewAdded = true;
             AutoScroll autoScrollTextView = (AutoScroll)view.findViewById(R.id.TextViewNotice);
             autoScrollTextView.init(windowManager);
             autoScrollTextView.startScroll();
         }
     }
     @Override
     public void onStart(Intent intent, int startId) {
         super.onStart(intent, startId);
         refresh();
     }

   
     public void removeView() {
         if (viewAdded)
         {
             windowManager.removeView(view);
             viewAdded = false;
         }
     }

     @Override
     public void onDestroy()
     {
         super.onDestroy();
         removeView();
         Log.d("CCtext", "ONDESTORY");
     }
}

4. autoscroll.xml文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    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=".MainActivity" >
<com.example.bartest.AutoScroll
    android:id="@+id/TextViewNotice"
    android:layout_height="30px"
    android:layout_width="fill_parent"
    android:text="我是OSD,我要开始滚动啦,哦也"
    android:textColor="#ffffffff"
    android:inputType="text"
    android:background="#eee"
    android:textSize="20px"
    android:layout_marginTop="50px"/>
</RelativeLayout>

5. AutoScroll.java
package com.example.bartest;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class AutoScroll extends TextView {
  private float textLength = 0f;//文本长度
  private float viewWidth = 0f;
  private float step = 0f;//文字的横坐标
  private float y = 0f;//文字的纵坐标
  private float temp_view_plus_text_length = 0.0f;//用于计算的临时变量
  private float temp_view_plus_two_text_length = 0.0f;//用于计算的临时变量
  public boolean isStarting = false;//是否开始滚动
  private Paint paint = null;//绘图样式
  private String text = "";//文本内容
  Canvas acanvas;
 
 
  private Handler handler = new Handler()
     {
      @Override
   public void handleMessage(Message msg)
      {
       onDraw(acanvas);
   }
     
     };
 public AutoScroll(Context context)
 {
  super(context);
//  initView();
 }
 public AutoScroll(Context context, AttributeSet attrs)
 {
  super(context, attrs);
//  initView();
 }
 public AutoScroll(Context context, AttributeSet attrs, int defStyle)
 {
  super(context, attrs, defStyle);
//  initView();
 }
 
// public void onClick(View v) {
//   if(isStarting)
//             stopScroll();
//         else
//             startScroll();
// }
//  private void initView()
//     {
//         setOnClickListener(this);
//     }
  public void init(WindowManager windowManager)
     {
         paint = getPaint();
         text = getText().toString();
         textLength = paint.measureText(text);//textview中字数的长度
         viewWidth = getWidth();
         if(viewWidth == 0)
         {
             if(windowManager != null)
             {
                 Display display = windowManager.getDefaultDisplay();
                 viewWidth = display.getWidth();
             }
         }
         step = textLength;
         temp_view_plus_text_length = viewWidth + textLength;
         temp_view_plus_two_text_length = viewWidth + textLength * 2;
         y = getTextSize() + getPaddingTop();
     }
     public void startScroll()
     {
         isStarting = true;
         invalidate();
     }
  
  
     public void stopScroll()
     {
         isStarting = false;
         invalidate();
     }
     public void onDraw(Canvas canvas) {
      acanvas = canvas;
         canvas.drawText(text, temp_view_plus_text_length - step, y, paint);
         if(!isStarting)
         {
             return;
         }
         step += 2;//0.5为文字滚动速度。
         if(step > temp_view_plus_two_text_length)
             step = textLength;
   invalidate();
     }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
浮动窗口Android应用程序可以浮动在其他应用程序上方的可视化界面元素。在Android Studio创建浮动窗口需要以下几个步骤: 1. 创建一个新的类,命名为FloatingWindowGFG,可以在项目包路径通过 "New -> Java 类" 来创建。 2. 在FloatingWindowGFG类,实现一个名为isMyServiceRunning()的方法,该方法用于检查浮动窗口服务是否正在运行。下面是一个示例代码: ```java private boolean isMyServiceRunning() { ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (FloatingWindowGFG.class.getName().equals(service.service.getClassName())) { return true; } } return false; } ``` 3. 另外,需要实现一个名为requestOverlayDisplayPermission()的方法,该方法用于请求悬浮窗口的显示权限。以下是一个示例代码: ```java private void requestOverlayDisplayPermission() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(true); builder.setTitle("Screen Overlay Permission Needed"); builder.setMessage("Enable 'Display over other apps' from System Settings."); builder.setPositiveButton("Open Settings", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())); startActivityForResult(intent, RESULT_OK); } }); AlertDialog dialog = builder.create(); dialog.show(); } ``` 以上就是在Android Studio创建浮动窗口的基本步骤和示例代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值