正如你所知道的,如果设备是根的,你可以用代码截屏
Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/sdcard/img.png").getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();但对于SDK>21 (5.0或更高版本),它不支持此功能。所以,我想知道如何使用Android 5.0或更高版本的服务(另一个应用程序)截屏。
我看到了MediaProjectionManager,但它需要运行onActivityResult来接收结果,但在服务中,它不能激活。
发布于 2016-04-13 17:54:40
这将为您提供:在您的类文件中全局声明它-
私有文件imageFile;私有void takeScreenshot() {
try {
String mPath = Environment.getExternalStorageDirectory().toString() +"\\/pic"; View v1 = FirstScreenActivity.mActivity.getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
} catch (Throwable e) {
e.printStackTrace();
}发布于 2016-04-13 18:34:22
首先在您的activity类中添加一个Activity对象,如下所示-
public class FirstScreenActivity extends AppCompatActivity {
public static Activity mActivity;
private File imageFile;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivity=this;
}
@Override
protected void onResume() {
super.onResume();}然后在您的非活动类文件中使用静态mActivity,如下所示,在前面的答案中使用上面的代码:
View v1 = FirstScreenActivity.mActivity.getWindow().getDecorView().getRootView();发布于 2016-04-14 19:52:01
以下是要在清单文件中指定的接收者-
<receiver android:name=".reciever.EventReceiver">
<intent-filter >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
<action android:name="android.intent.action.USER_PRESENT"/>
</intent-filter>
</receiver>像这些动作一样,你也可以选择其他动作。注意:不要忘记为您将在receiver中使用的操作添加权限。这是receiver类,您将在其中编写代码(在本例中为截图)-
public class EventReceiver extends BroadcastReceiver {
private File imageFile;
private Context mContext;
@Override
public void onReceive(final Context context, Intent intent) {
mContext=context;
takeScreenshot();
//you can execute some of your other code also
}
private void takeScreenshot() {
try {
String mPath = Environment.getExternalStorageDirectory().toString() +"\\/pic";
View v1 = FirstScreenActivity.mActivity.getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
} catch (Throwable e) {
e.printStackTrace();
}
}}
使用它,您的接收器类的onReceive()将在您在清单中指定的特定事件操作上执行。
https://stackoverflow.com/questions/36592824
复制相似问题