如何在Service Class android中获取/保存后台截图?

时间:2015-06-03 05:33:18

标签: android

我的应用程序在前台运行正常,但我想实现在后台运行screenshot ..我坚持如何实现它...

我认为服务可以提供帮助......

public class MainActivity extends Activity implements OnClickListener {
    ListView listview;
    List<ParseObject> ob;
    ProgressDialog mProgressDialog;
    ArrayAdapter<String> adapter;
    EditText et;
    Button bt, bt2;
    String[] values;
    List<String> list11 = new ArrayList<String>();
    private SensorManager mSensorManager;
    private float mAccel; // acceleration apart from gravity
    private float mAccelCurrent; // current acceleration including gravity
    private float mAccelLast; // last acceleration including gravity

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mSensorManager.registerListener(mSensorListener,
                mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_NORMAL);
        mAccel = 0.00f;
        mAccelCurrent = SensorManager.GRAVITY_EARTH;
        mAccelLast = SensorManager.GRAVITY_EARTH;

    }

    private final SensorEventListener mSensorListener = new SensorEventListener() {

        public void onSensorChanged(SensorEvent se) {
            float x = se.values[0];
            float y = se.values[1];
            float z = se.values[2];
            mAccelLast = mAccelCurrent;
            mAccelCurrent = (float) Math.sqrt((double) (x * x + y * y + z * z));
            float delta = mAccelCurrent - mAccelLast;
            mAccel = mAccel * 0.9f + delta; // perform low-cut filter
            if (mAccel > 2) {
                Toast toast = Toast.makeText(getApplicationContext(),
                        "Device has shaken.", Toast.LENGTH_LONG);
                toast.show();
                save();

            }
        }

        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }
    };

    public void save() {
        final String SCREENSHOTS_LOCATIONS = Environment
                .getExternalStorageDirectory().toString() + "/screenshots/";

        // Get device dimmensions
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);

        // Get root view
        View view = getWindow().getDecorView().getRootView();

        // Create the bitmap to use to draw the screenshot
        final Bitmap bitmap = Bitmap.createBitmap(size.x, size.y,
                Bitmap.Config.ARGB_4444);
        final Canvas canvas = new Canvas(bitmap);

        // Get current theme to know which background to use
        final Activity activity = MainActivity.this;
        final Theme theme = activity.getTheme();
        final TypedArray ta = theme
                .obtainStyledAttributes(new int[] { android.R.attr.windowBackground });
        final int res = ta.getResourceId(0, 0);
        final Drawable background = activity.getResources().getDrawable(res);

        // Draw background
        background.draw(canvas);

        // Draw views
        view.draw(canvas);

        // Save the screenshot to the file system
        FileOutputStream fos = null;
        try {
            final File sddir = new File(SCREENSHOTS_LOCATIONS);
            if (!sddir.exists()) {
                sddir.mkdirs();
            }
            fos = new FileOutputStream(SCREENSHOTS_LOCATIONS
                    + System.currentTimeMillis() + ".jpg");
            if (fos != null) {
                if (!bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos)) {
                }
                fos.flush();
                fos.close();
            }

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(mSensorListener,
                mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    protected void onPause() {
        mSensorManager.unregisterListener(mSensorListener);
        super.onPause();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}

1 个答案:

答案 0 :(得分:0)

您可以使用此代码段进行截屏,

    View screen = getWindow().getDecorView().getRootView();
    screen.setDrawingCacheEnabled(true);
    Bitmap bitmap = screen.getDrawingCache();

    File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "yourpath");
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d("Error", "path not created");
        }
    }
    String filePath = Environment.getExternalStorageDirectory() + File.separator + "yourpath" + "/" + "fileName" + ".png";
    try {
         bitmap.compress(CompressFormat.PNG, 100, new FileOutputStream(newFile(filePath)));
    } catch (FileNotFoundException e) {
         e.printStackTrace();
    }

不要忘记将此权限添加到ypur manifest.xml文件

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