Search code examples
androidandroid-service

Get pixel color in background on Android


I need to create a service that keeps checking a coordinate of an android screen for the color of a pixel.

Eg.

Bitmap bitmap = ((BitmapDrawable)getBackground()).getBitmap();
int pixel = bitmap.getPixel(x,y);

if(pixel == Color.MAGENTA){
   //Stop Service
}

However instead of just my app, I need it to be in a background service which keeps checking for the color even when I switch apps.

Assuming the device is rooted, is there any superuser commands that does what I need?


Solution

  • To those who need to do something like I am doing,

    I used the system's command /system/bin/screencap -p to capture the screen and check for the pixel on the screenshot.

    This method requires the root permission

    private void getPixelColor(int xcoord, int ycoord)
    {
        try {
            Process sh = Runtime.getRuntime().exec("su", null,null);
    
            OutputStream os = sh.getOutputStream();
            os.write(("/system/bin/screencap -p " + "/sdcard/colorPickerTemp.png").getBytes("ASCII"));
            os.flush();
    
            os.close();
            sh.waitFor();
    
            Bitmap screen = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + File.separator + "colorPickerTemp.png");
            int pixel = screen.getPixel(xcoord ,ycoord + statusHeight);
            Log.d("pixel color", "Pixel Color: + " + Integer.toHexString(pixel) + " at x:" + xcoord + " y:" + ycoord);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }