Home > OS >  How to implement taking a screenshot when an action button is pressed in pip mode state
How to implement taking a screenshot when an action button is pressed in pip mode state

Time:10-12

I'm trying to implement taking a screenshot when an action button is pressed in pip-mode state. When the action button is pressed, I can confirm with the broadcast receiver, but I'm having trouble implementing a screenshot.

I would like to know how to add the ability to take a screenshot when broadcast onReceive reacts.

The problem with this project is that the screenshot button's event reception is being done outside of onCreate, not inside. I wonder how I can do that.

I'd really appreciate it if you help me. Thanks

class MainActivity : AppCompatActivity() {

    private val youtubeName = "com.google.android.youtube"
    private val gmailName = "com.google.android.gm"

    class ScreenShotReceiver: BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            println("Clicked on screenShot button!")
            screenShot()
        }
        private fun screenShot(){
            // need - code
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val youtubeBtn = findViewById<ImageButton>(R.id.btn_youtube)
        val gmailBtn = findViewById<ImageButton>(R.id.btn_gmail)

        val intentYoutube = packageManager.getLaunchIntentForPackage(youtubeName)
        val intentGmail = packageManager.getLaunchIntentForPackage(gmailName)

        ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1)
        ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)

        youtubeBtn.setOnClickListener {
            enterPipMode(intentYoutube)
        }

        gmailBtn.setOnClickListener {
            enterPipMode(intentGmail)
        }
    }
    private fun enterPipMode(target: Intent?) {
        try {
            startActivity(target)
        } catch (e: Exception) {  // if no app
            val intentPlayStore = Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="   target)) // 설치 링크를 인텐트에 담아
            startActivity(intentPlayStore) // go to play-store
        }
        Handler(Looper.getMainLooper()).postDelayed({
            updatedPipParams()?.let{
                    params -> enterPictureInPictureMode(params)
            }
        },1)
    }

    private fun updatedPipParams(): PictureInPictureParams? {
        return PictureInPictureParams.Builder()
            .setAspectRatio(Rational(3, 2))
            .setActions(
                listOf(
                    RemoteAction(
                        Icon.createWithResource(
                            applicationContext,
                            R.drawable.ic_screeshot_foreground
                        ),
                        "screen shot",
                        "screen shot",
                        PendingIntent.getBroadcast(
                            applicationContext,
                            0,
                            Intent(applicationContext, ScreenShotReceiver::class.java),
                            PendingIntent.FLAG_IMMUTABLE
                        )
                    )
                )
            )
            .build()
    }

    override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) {
        if (isInPictureInPictureMode) {
            //hide all unimportant views
            println("pip mode")
        } else {
            //show all unimportant views
            println("total screen mode")
        }
    }
}

CodePudding user response:

First add this to manifest:

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

And this is the code (running in an Activity):

 private void takeScreenshot() {
        Date now = new Date();
        android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
    
        try {
            // image naming and path  to include sd card  appending name you choose for file
            String mPath = Environment.getExternalStorageDirectory().toString()   "/"   now   ".jpg";
    
            // create bitmap screen capture
            View v1 = getWindow().getDecorView().getRootView();
            v1.setDrawingCacheEnabled(true);
            Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
            v1.setDrawingCacheEnabled(false);
    
            File imageFile = new File(mPath);
    
            FileOutputStream outputStream = new FileOutputStream(imageFile);
            int quality = 100;
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
            outputStream.flush();
            outputStream.close();
    
            openScreenshot(imageFile);
        } catch (Throwable e) {
            // Several error may come out with file handling or DOM
            e.printStackTrace();
        }
    }
  • Related