Android 截圖最新方案

使用方式

import android.content.Context;
import android.content.Intent;
import android.media.projection.MediaProjectionManager;
import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;

public class ShotActivity extends AppCompatActivity {
    private static final String TAG = ShotActivity.class.getSimpleName();

    public static final int REQUEST_MEDIA_PROJECTION = 0x2304;
    private Intent mMediaServiceIntent;
    private String savedPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shot);
        if (mMediaServiceIntent == null) {
            mMediaServiceIntent = new Intent(this, MediaService.class);
        }
        startService(mMediaServiceIntent);
        savedPath = this.getExternalFilesDir("screenshot").getAbsoluteFile() + "/" + System.currentTimeMillis() + ".png";
        findViewById(R.id.shot).setOnClickListener(v -> {
            requestScreenShotPermission();
        });
    }

    public void requestScreenShotPermission() {
        MediaProjectionManager mediaMgr = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        startActivityForResult(mediaMgr.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION);
    }

    @Override
    protected void onActivityResult(int requestCode, final int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_MEDIA_PROJECTION && resultCode == RESULT_OK && data != null) {
            getWindow().getDecorView().postDelayed(() -> {
                ShootUtil shootUtil = new ShootUtil(ShotActivity.this, resultCode, data);
                shootUtil.startScreenShot(savedPath, new ShootUtil.OnShotListener() {
                    @Override
                    public void onFinish(String path) {
                        Log.i(TAG, "onFinish, path = " + path);
                    }

                    @Override
                    public void onError() {
                        Log.e(TAG, "onError, ");
                    }
                });
            }, 100L);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMediaServiceIntent != null) {
            stopService(mMediaServiceIntent);
            mMediaServiceIntent = null;
        }
    }
}

ShootUtil.java 截圖工具類

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.AsyncTask;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.nio.ByteBuffer;

public class ShootUtil {
    private static final String TAG = ShootUtil.class.getSimpleName();
    public static boolean hasPermission;
    private final SoftReference<Context> mRefContext;
    private final ImageReader mImageReader;
    private final MediaProjection mMediaProjection;
    private VirtualDisplay mVirtualDisplay;
    private OnShotListener mOnShotListener;
    private final int mHeight;
    private final int mWidth;
    private String mLocalUrl = "";

    private String getSavedPath() {
        if (TextUtils.isEmpty(mLocalUrl)) {
            mLocalUrl = getContext().getExternalFilesDir("screenshot").getAbsoluteFile() + "/" + System.currentTimeMillis() + ".png";
        }
        return mLocalUrl;
    }


    public ShootUtil(Context context, int reqCode, Intent data) {
        mRefContext = new SoftReference<>(context);
        mMediaProjection = getMediaProjectionManager().getMediaProjection(reqCode, data);
        WindowManager window = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display mDisplay = window.getDefaultDisplay();
        DisplayMetrics metrics = new DisplayMetrics();
        mDisplay.getRealMetrics(metrics);
        mWidth = metrics.widthPixels;//size.x;
        mHeight = metrics.heightPixels;//size.y;
        mImageReader = ImageReader.newInstance(mWidth, mHeight, PixelFormat.RGBA_8888, 1);
    }


    private void virtualDisplay() {
        mVirtualDisplay = mMediaProjection.createVirtualDisplay("screen-mirror", mWidth, mHeight, Resources.getSystem().getDisplayMetrics().densityDpi, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mImageReader.getSurface(), null, null);
    }

    public void startScreenShot(String savedPath, OnShotListener onShotListener) {
        mLocalUrl = savedPath;
        startScreenShot(onShotListener);
    }

    public void startScreenShot(OnShotListener onShotListener) {
        hasPermission = true;
        mOnShotListener = onShotListener;
        virtualDisplay();
        Handler handler = new Handler();
        handler.postDelayed(() -> {
            Image image = mImageReader.acquireLatestImage();
            new SaveTask().doInBackground(image);
        }, 300);
    }

    public class SaveTask extends AsyncTask<Image, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(Image... params) {
            if (params == null || params.length < 1 || params[0] == null) {
                return null;
            }
            Image image = params[0];
            int width = image.getWidth();
            int height = image.getHeight();
            final Image.Plane[] planes = image.getPlanes();
            final ByteBuffer buffer = planes[0].getBuffer();
            int pixelStride = planes[0].getPixelStride();
            int rowStride = planes[0].getRowStride();
            int rowPadding = rowStride - pixelStride * width;
            Bitmap bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
            bitmap.copyPixelsFromBuffer(buffer);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
            image.close();
            File fileImage;
            if (bitmap != null) {
                try {
                    fileImage = new File(getSavedPath());
                    if (!fileImage.exists()) {
                        fileImage.createNewFile();
                    }
                    FileOutputStream out = new FileOutputStream(fileImage);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    if (mOnShotListener != null) mOnShotListener.onError();
                    release();
                    return null;
                }
            }
            if (bitmap != null && !bitmap.isRecycled()) {
                bitmap.recycle();
            }
            if (mVirtualDisplay != null) {
                mVirtualDisplay.release();
            }
            if (mMediaProjection != null) {
                mMediaProjection.stop();
            }

            if (mOnShotListener != null) {
                mOnShotListener.onFinish(getSavedPath());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
        }
    }

    public void release() {
        if (mVirtualDisplay != null) {
            mVirtualDisplay.release();
        }
        if (mMediaProjection != null) {
            mMediaProjection.stop();
        }
    }


    private MediaProjectionManager getMediaProjectionManager() {
        return (MediaProjectionManager) getContext().getSystemService(Context.MEDIA_PROJECTION_SERVICE);
    }

    private Context getContext() {
        return mRefContext.get();
    }

    public interface OnShotListener {
        void onFinish(String path);

        void onError();
    }
}

MediaService.java 前臺(tái)服務(wù)

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.IBinder;

import androidx.core.app.NotificationCompat;

public class MediaService extends Service {
    private final String NOTIFICATION_CHANNEL_ID = "com.tencent.trtc.apiexample.MediaService";
    private final String NOTIFICATION_CHANNEL_NAME = "com.tencent.trtc.apiexample.channel_name";
    private final String NOTIFICATION_CHANNEL_DESC = "com.tencent.trtc.apiexample.channel_desc";

    public MediaService() {
    }

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

    public void startNotification() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Intent notificationIntent = new Intent(this, MediaService.class);
            PendingIntent pendingIntent;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
                pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
            } else {
                pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_ONE_SHOT);
            }
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground))
                    .setSmallIcon(R.drawable.ic_launcher_foreground)
                    .setContentTitle("Starting Service")
                    .setContentText("Starting monitoring service")
                    .setContentIntent(pendingIntent);
            Notification notification = notificationBuilder.build();
            NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            channel.setDescription(NOTIFICATION_CHANNEL_DESC);
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.createNotificationChannel(channel);
            startForeground(1, notification); //必須使用此方法顯示通知灰伟,不能使用notificationManager.notify余赢,否則還是會(huì)報(bào)上面的錯(cuò)誤
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

AndroidManifest.xml 文件添加 service

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

     <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:requestLegacyExternalStorage="true"
        android:supportsRtl="true">
        
        ...
        
        <service
            android:name=".MediaService"
            android:enabled="true"
            android:exported="true"
            android:foregroundServiceType="mediaProjection" />
    </application>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末晨继,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子湿蛔,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,406評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件呼股,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡画恰,警方通過(guò)查閱死者的電腦和手機(jī)彭谁,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,395評(píng)論 3 398
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)允扇,“玉大人缠局,你說(shuō)我怎么就攤上這事则奥。” “怎么了狭园?”我有些...
    開封第一講書人閱讀 167,815評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵读处,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我唱矛,道長(zhǎng)罚舱,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,537評(píng)論 1 296
  • 正文 為了忘掉前任绎谦,我火速辦了婚禮管闷,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘窃肠。我一直安慰自己包个,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,536評(píng)論 6 397
  • 文/花漫 我一把揭開白布冤留。 她就那樣靜靜地躺著碧囊,像睡著了一般。 火紅的嫁衣襯著肌膚如雪搀菩。 梳的紋絲不亂的頭發(fā)上呕臂,一...
    開封第一講書人閱讀 52,184評(píng)論 1 308
  • 那天,我揣著相機(jī)與錄音肪跋,去河邊找鬼歧蒋。 笑死,一個(gè)胖子當(dāng)著我的面吹牛州既,可吹牛的內(nèi)容都是我干的谜洽。 我是一名探鬼主播,決...
    沈念sama閱讀 40,776評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼吴叶,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼阐虚!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起蚌卤,我...
    開封第一講書人閱讀 39,668評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤实束,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后逊彭,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體咸灿,經(jīng)...
    沈念sama閱讀 46,212評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,299評(píng)論 3 340
  • 正文 我和宋清朗相戀三年侮叮,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了避矢。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,438評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖审胸,靈堂內(nèi)的尸體忽然破棺而出亥宿,到底是詐尸還是另有隱情,我是刑警寧澤砂沛,帶...
    沈念sama閱讀 36,128評(píng)論 5 349
  • 正文 年R本政府宣布烫扼,位于F島的核電站,受9級(jí)特大地震影響尺上,放射性物質(zhì)發(fā)生泄漏材蛛。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,807評(píng)論 3 333
  • 文/蒙蒙 一怎抛、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧芽淡,春花似錦马绝、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,279評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至白胀,卻和暖如春椭赋,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背或杠。 一陣腳步聲響...
    開封第一講書人閱讀 33,395評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工哪怔, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人向抢。 一個(gè)月前我還...
    沈念sama閱讀 48,827評(píng)論 3 376
  • 正文 我出身青樓认境,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親挟鸠。 傳聞我的和親對(duì)象是個(gè)殘疾皇子叉信,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,446評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容

  • 現(xiàn)在 hotfix 框架有很多,原理大同小異艘希,基本上是基于qq空間這篇文章 或者微信的方案硼身。可惜的是微信的 Tin...
    yecanaan閱讀 1,599評(píng)論 0 20
  • 【Android Service】 Service 簡(jiǎn)介(★★★) 很多情況下覆享,一些與用戶很少需要產(chǎn)生交互的應(yīng)用程...
    Rtia閱讀 3,159評(píng)論 1 21
  • 標(biāo)簽(空格分隔): Android 熱更新 Tinker概述 開源地址https://github.com/Ten...
    dongzi711閱讀 981評(píng)論 0 6
  • Android版本差異適配方案(5.0-9.0) 一個(gè)好的APP最好支持90%設(shè)備佳遂,由于不同版本系統(tǒng)提供的API可...
    yinhaide閱讀 3,345評(píng)論 4 32
  • 眾所周知讶迁,日活率是一款A(yù)pp的核心績(jī)效指標(biāo),日活量不僅反應(yīng)了應(yīng)用的受歡迎程度,同時(shí)反應(yīng)了產(chǎn)品的變現(xiàn)能力巍糯,進(jìn)而直接影...
    龍旋之谷閱讀 1,551評(píng)論 2 5