Activity is not starting again

85 Views Asked by At

i have created an application which uses firebase push notification to get commands and perform that task. my app doesn't have any visible activity but a service which continuously working in background.

i have implemented a functionality of taking screenshot using Media Projection Api.

when i get command of Screenshot, app launches ScreenProjectionActivity, took screenshot and finish. but when it gets again command of Screenshot ScreenProjectionActivity doesn't launch again. i dont know what i am doing wrong and where i am doing wrong.

Here is how i am launching from service.

context.startActivity(
                        Intent(this, ScreenProjectionActivity::class.java)
                            .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
                            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    )

ScreenProjectionActivity.kt

class ScreenProjectionActivity : Activity()
{
    lateinit var context: Context
    private var mHandler: Handler? = null

    @RequiresApi(Build.VERSION_CODES.KITKAT_WATCH)
    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        val tv = TextView(this)
        tv.text = ""
        setContentView(tv)
        context = this

        log("onCreate")

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        {
            val mgr = getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
            startActivityForResult(mgr.createScreenCaptureIntent(), 7575)

            // start capture handling thread
            object : Thread() {
                override fun run() {
                    Looper.prepare()
                    mHandler = Handler()
                    Looper.loop()
                }
            }.start()
        }
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == 7575 && resultCode == RESULT_OK)
        {
            log("if taking screen")
            //TakeScreenShot(applicationContext, Handler(Looper.getMainLooper()), resultCode, data).start()
            takeScreenShot(resultCode, data)
        }

        super.onBackPressed()
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    private fun takeScreenShot(resultCode: Int, data: Intent?)
    {
        log("takeScreenshot")
        SystemClock.sleep(1000)
        var flagScreenShot = true

        val metrics = DisplayMetrics()
        val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val mgr = getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager

        windowManager.defaultDisplay.getMetrics(metrics)

        val mMediaProjection = mgr.getMediaProjection(resultCode, data!!)

        val imgReader: ImageReader = ImageReader.newInstance(
            metrics.widthPixels,
            metrics.heightPixels,
            PixelFormat.RGBA_8888,
            1
        )

        val onImageAvailableListener =
            OnImageAvailableListener {
                log("onImageAvailableListener")
                val image: Image? = it?.acquireLatestImage()

                if (image != null && flagScreenShot)
                {
                    flagScreenShot = false
                    mMediaProjection?.stop()
                    log("mMediaProjection Stopped!")
                    imgReader.setOnImageAvailableListener(null, null)

                    val mWidth = image.width
                    val mHeight = image.height

                    val planes = image.planes
                    val buffer = planes[0].buffer
                    val pixelStride = planes[0].pixelStride
                    val rowStride = planes[0].rowStride
                    val rowPadding = rowStride - pixelStride * mWidth

                    val bitmap = Bitmap.createBitmap(
                        mWidth + rowPadding / pixelStride,
                        mHeight,
                        Bitmap.Config.ARGB_8888
                    )
                    bitmap.copyPixelsFromBuffer(buffer)
                    saveImage(bitmap)
                }
                log("image close")
                image?.close()
            }

        mMediaProjection?.createVirtualDisplay(
            "ScreenCapture",
            metrics.widthPixels,
            metrics.heightPixels,
            metrics.densityDpi,
            DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
            imgReader.surface,
            null,
            mHandler
        )

        imgReader.setOnImageAvailableListener(onImageAvailableListener, mHandler)
    }

    private fun saveImage(finalBitmap: Bitmap) {
        val root: String = Environment.getExternalStorageDirectory().toString()
        val myDir = File("$root/saved_images")
        myDir.mkdirs()
        val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ENGLISH).format(Date())
        val fname = "Shutta_$timeStamp.jpg"
        val file = File(myDir, fname)
        if (file.exists()) file.delete()
        try
        {
            val out = FileOutputStream(file)
            finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)
            out.flush()
            out.close()

            log("Image Saved.")
            finish()

        } catch (e: Exception) {
            log("Image Saved Exception: $e")
        }
    }


    private fun encodeImage(bm: Bitmap): String {
        val baos = ByteArrayOutputStream()
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos)
        val b = baos.toByteArray()
        return Base64.encodeToString(b, Base64.DEFAULT)
    }

    override fun onDestroy() {
        super.onDestroy()
    }

}

Please help me out here. thanks

1

There are 1 best solutions below

0
On BEST ANSWER

I solved it my self, what i did is startActivity with these flags

applicationContext.startActivity(
                    Intent(this, ScreenProjectionActivity::class.java)
                        .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                        .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
                        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                )

and in Manifest:

<activity
        android:name=".ScreenProjectionActivity"
        android:excludeFromRecents="true"
        android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen" />