surfaceview实现的画画板以及安卓6.0以上部分动态权限以及WindowManger的使用

17 篇文章 0 订阅

surfaceview实现的画画板以及安卓6.0以上部分动态权限

Activity

package com.ahtelit.zbv.myapplication;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private final static int REQUEST_CODE = 0;

    WindowManager wm;
    SimpleView simpleView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("zbv", "SDK_INT=" + Build.VERSION.SDK_INT);

//        setContentView(new SimpleView(this));
//        wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
//        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
//        //宽高
//        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
//        layoutParams.height = 500;
//        //设置类型---以前的TYPE_SYSTEM_ALERT--需要弹框权限
//        layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
//        //设置flags
        layoutParams.flags=WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
//        //设置背景遮罩为透明
//        layoutParams.format = PixelFormat.TRANSLUCENT;
//        layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
//
//        simpleView=new SimpleView(this);
//
//        wm.addView(simpleView, layoutParams);

    }

    public void popupWM(View view) {
        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        //宽高
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //设置类型---以前的TYPE_SYSTEM_ALERT--需要弹框权限
        layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        //设置flags
//        layoutParams.flags=WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        //设置背景遮罩为透明
        layoutParams.format = PixelFormat.TRANSLUCENT;
        layoutParams.gravity = Gravity.TOP | Gravity.LEFT;

        TextView tv = new TextView(this);
        tv.setText("弹出窗口文本!!!");
        wm.addView(tv, layoutParams);
    }

    //返回键最后调用
    @Override
    public void onBackPressed() {
        Log.d("zbv","onBackPress");
//        wm.removeView(simpleView);
        super.onBackPressed();

        finish();

    }

    //返回键先调用
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if(event.getKeyCode()==KeyEvent.KEYCODE_BACK){
//            Log.d("zbv","按返回键");
            wm.removeView(simpleView);
//            finish();
//        }
//        return true;
//    }

 private void jumpPermissionForHUAWEI() {
    /*
    * com.huawei.systemmanager/com.huawei.permissionmanager.ui.SingleAppActivity
    * 需要权限---跳转到该app的所需权限页面
    * */
        try {
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ComponentName comp = new ComponentName("com.huawei.systemmanager", "com.huawei.permissionmanager.ui.MainActivity");
            //华为权限管理
            intent.setComponent(comp);
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            Log.d("zbv","error",e);
//                   appDetailInfo();
        }
    }

    //系统的应用详情页面
    private void appDetailInfo() {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        startActivity(localIntent);
    }

    /**
     * 安卓6.0以上部分需要权限动态申明
     */
    private void initNeededPermission(Context context, String[] permissions) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            ArrayList<String> needPermission = new ArrayList<>();

            for (String permission : permissions) {
                if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    Log.d("zbv", "没有准许的权限是=" + permission);
                    needPermission.add(permission);
                }
            }

            //链表转化成对应类型的数组
            String[] needPermissionStrs = new String[needPermission.size()];
            if (needPermission.size() != 0) {
                ActivityCompat.requestPermissions(this, needPermission.toArray(needPermissionStrs), 0x7);
            }

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 0x7) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            for (int i = 0; i < grantResults.length; i++) {
                boolean flag = ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i]);
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    if (flag) {
                        //用户拒绝了但是没有勾选“dont ask again”
                        ActivityCompat.requestPermissions(this,new String[]{permissions[i]},0x7);
                    } else {
                        //用户拒绝了并且勾选“dont ask again”
                        popupTips();
                    }
                }
            }
        }
    }

    private void popupTips(){
        AlertDialog dialog=new AlertDialog.Builder(this)
                .setTitle("Tips")
                .setMessage("您有未开启的权限,请开始!")
                .setNegativeButton("不设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        appDetailInfo();
                        dialog.dismiss();
                    }
                })
                .create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }
}

二、画画板的View

package com.ahtelit.zbv.myapplication;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.support.annotation.ColorRes;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;

/**
 * Created by Administrator on 2018/4/18.
 * qzx
 */

public class SimpleView extends SurfaceView implements SurfaceHolder.Callback,Runnable{

    private SurfaceHolder mHolder;
    private Canvas mCanvas;
    private Paint mPaint;
    private boolean isDestroy;
    private static final int INTERVER_TIME=30;//30毫秒
    private Context mContext;

    private WindowManager wm;
    private WindowManager.LayoutParams layoutParams;

    public SimpleView(Context context) {
        this(context,null);
    }

    public SimpleView(Context context, AttributeSet attrs) {
        this(context,attrs,0);
    }

    public SimpleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext=context;
        initAttrs();
    }

    private void initAttrs(){

        mHolder=getHolder();
        mHolder.addCallback(this);

        //可聚焦和聚焦触摸
        setFocusable(true);
        setFocusableInTouchMode(true);
        //保持常亮
        this.setKeepScreenOn(true);

        mPaint=new Paint();

        mPath=new Path();

//        //wm
//        wm=(WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
//        layoutParams=new WindowManager.LayoutParams();
//        //宽高
//        layoutParams.width=WindowManager.LayoutParams.MATCH_PARENT;
//        layoutParams.height=WindowManager.LayoutParams.WRAP_CONTENT;
//        //设置类型---以前的TYPE_SYSTEM_ALERT--需要弹框权限
//        layoutParams.type=WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
//        //设置flags
        layoutParams.flags=WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
//        //设置背景遮罩为透明
//        layoutParams.format= PixelFormat.TRANSLUCENT;
//        layoutParams.gravity= Gravity.TOP|Gravity.LEFT;
//
//
//        Log.d("zbv","width="+this.getWidth()+";height="+this.getHeight());//0 0
//        wm.addView(this,layoutParams);
    }

    //需要api=21
//    public SimpleView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
//        super(context, attrs, defStyleAttr, defStyleRes);
//    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        isDestroy=false;
        new Thread(this).start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isDestroy=true;
    }

    @Override
    public void run() {
        while(!isDestroy){
            //控制刷新的帧数
            long startTime=System.currentTimeMillis();

            draw();

            long endTime=System.currentTimeMillis();

            if((endTime-startTime)<INTERVER_TIME){
                try {
                    Thread.sleep((INTERVER_TIME-(endTime-startTime)));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    private void draw(){

        //如果没有try catch在返回的那一刻会空指针崩溃
        try{
            mCanvas=mHolder.lockCanvas();
            mCanvas.drawColor(Color.WHITE);

            mPaint.setColor(Color.GRAY);

            mCanvas.drawPath(mPath,mPaint);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //这个同理
            if(mCanvas!=null)
            mHolder.unlockCanvasAndPost(mCanvas);
        }



    }

    private Path mPath;
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                mPath.moveTo(event.getX(),event.getY());
                break;
            case MotionEvent.ACTION_MOVE:
                mPath.lineTo(event.getX(),event.getY());
//                mPath.moveTo(event.getX(),event.getY());
                break;

        }
//        return super.onTouchEvent(event);
        return true;
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if(event.getKeyCode()==KeyEvent.KEYCODE_BACK){
//            wm.removeView(this);
//        }
//        return super.onKeyDown(keyCode,event);
//    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值