Android 如何在后台服务中创建视图以将画布另存为图片?
这可能是一个奇怪的要求,但是,它在特定情况下很有用。例如,当您在Android设备上运行web服务并为页面提供特殊图形时 所有web服务内容都将在后台服务的后台线程中运行,没有任何可见的活动窗口。如何将某个布局文件膨胀到视图中,并在后台线程中更改Java中的内容Android 如何在后台服务中创建视图以将画布另存为图片?,android,view,Android,View,这可能是一个奇怪的要求,但是,它在特定情况下很有用。例如,当您在Android设备上运行web服务并为页面提供特殊图形时 所有web服务内容都将在后台服务的后台线程中运行,没有任何可见的活动窗口。如何将某个布局文件膨胀到视图中,并在后台线程中更改Java中的内容 可能吗?如何使用?由于我不确定确切的用例,下面的代码只是概念证明,但应该很容易适应您的需要。在IntentService中扩展示例布局,更改各种视图属性,并将位图保存到外部存储器 public class MyIntentService
可能吗?如何使用?由于我不确定确切的用例,下面的代码只是概念证明,但应该很容易适应您的需要。在IntentService中扩展示例布局,更改各种视图属性,并将位图保存到外部存储器
public class MyIntentService extends IntentService {
@Override
protected void onHandleIntent(Intent intent) {
LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
View view = inflater.inflate(R.layout.view, null);
Button button = (Button) view.findViewById( R.id.button );
String text = intent.getExtras().getString("text");
button.setText(text);
view.setDrawingCacheEnabled(true);
Bitmap bitmap = view.getDrawingCache();
}
}
布局文件off_screen.xml
:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linear_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:background="#aaddff" >
<ImageView android:id="@+id/image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
<TextView android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:text="Hello!" />
</LinearLayout>
以及服务的示例调用:
Intent intent = new Intent(this, ViewPictureService.class);
intent.putExtra(ViewPictureService.EXTRA_RESOURCE, R.layout.off_screen);
intent.putExtra(ViewPictureService.EXTRA_WIDTH, 540);
intent.putExtra(ViewPictureService.EXTRA_HEIGHT, 960);
intent.putExtra(ViewPictureService.EXTRA_FILENAME, "view_" + System.currentTimeMillis() + ".png");
startService(intent);
当然,文件写入需要清单中的权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
该服务需要在
部分输入:
<service android:name=".ViewPictureService" />
我想你误解了我的意思question@Mike是的,我知道在位图上画画在背景中是可以的。但是,在保存位图之前,我想膨胀一些复杂的布局文件并用Java代码对其进行操作。您到底想对UI做什么?您想从后台线程更改它吗?@EJK我没有此应用程序的任何GUI,我想在后台服务中扩展XML布局,并将其保存为图片发送到网页。
<service android:name=".ViewPictureService" />