打算记录一些自己在开发过程中遇到的一些技巧性代码,方便以后遇到相似功能时能够快速的找到,那就从这里开始吧。
1,如何截取当前屏幕(不包括当前Activity
的Title
)并分享:
a,获取当前Activity
的根视图:
View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
或者:
View rootView = findViewById(android.R.id.content);
或者:
View rootView = findViewById(android.R.id.content).getRootView();
关于android.R.id.content
,开发者文档中并没有给予说明,但经过测试它应该是用来获取setContentView()
中设置的View
。
b,截取当前根视图的屏幕:
public static Bitmap getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
return bitmap;
}
getScreenShot
c,将当前屏幕的截屏保存至SDCard
:
private final static String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Screenshots";
public static void store(Bitmap bm, String fileName){
File dir = new File(dir);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
store(Bitmap bm, String fileName)
d,最后将该图片文件分享出来:
private void shareImage(String file){
Uri uri = Uri.fromFile(file);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Share Screenshot"));
}
shareImage(String file)
2,如何对HTML5
中的视频截图:
a,初始化WebView
:
String webUrl = ...;
VideoView vv;
mWebView = (WebView) findViewById(R.id.webview);
mWebView.setWebChromeClient(chromeClient);
mWebView.setWebViewClient(wvClient);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginsEnabled(true);
mWebView.loadUrl(webUrl);
b,覆盖WebChromeClient
中的onShowCustomView
方法:
@Override
public void onShowCustomView(View view, CustomViewCallback callback) {
super.onShowCustomView(view, callback);
if (view instanceof FrameLayout){
FrameLayout frame = (FrameLayout) view;
if (frame.getFocusedChild() instanceof VideoView){
vv = (VideoView) frame.getFocusedChild();
}
}
}
onShowCustomView(View view, CustomViewCallback callback)
c,截取VideoView
中播放的视频内容:
private Bitmap capture(VideoView vv){
MediaMetadataRetriever rev = new MediaMetadataRetriever();
rev.setDataSource(this, uri);//this is a Context;
Bitmap bitmap = rev.getFrameAtTime(vv.getCurrentPosition() * 1000, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
return bitmap;
}
capture(VideoView vv)
d,如何还想将截屏幕保存或分享,请参见上面的代码示例.
3,如何动态获取保存在integer-array
中的动态资源id?
a,在res/values/
目录下创建arrays.xml
文件,创建内容如下:
<integer-array name="frag_home_ids">
<item>@drawable/frag_home_credit_return_money</item>
<item>@drawable/frag_home_transfer</item>
<item>@drawable/frag_home_balance</item>
<item>@drawable/frag_home_charge</item>
<item>@drawable/frag_home_finance_cdd</item>
<item>@drawable/frag_home_finance_ybjr</item>
<item>@drawable/frag_home_more</item>
</integer-array>
arrays.xml
b,通过编码的方式获取integer-array
中的资源id整型值:
TypedArray tArray = getResources().obtainTypedArray(R.array.frag_home_ids);
int count = tArray.length();
int[] ids = new int[count];
for (int i = 0; i < ids.length; i++) {
ids[i] = tArray.getResourceId(i, 0);
}
c,使用已经获取到的资源的id:
holder.iv.setImageResource(ids[position]);
d,我们也还可以用这种方式获取string
, color
, integer
, layout
, menu
等的id
.
4,ListView
或GridView
局部刷新原理的实现:
private void refreshPartially(int position){
int firstVisiblePosition = listview.getFirstVisiblePosition();
int lastVisiblePosition = listview.getLastVisiblePosition();
if(position>=firstVisiblePosition && position<=lastVisiblePosition){
View view = listview.getChildAt(position - firstVisiblePosition);
if(view.getTag() instanceof ViewHolder){
ViewHolder vh = (ViewHolder)view.getTag();
//holder.play.setBackgroundResource(resId);//Do something here.
...
}
}
}
refreshPartially(int position)
5,Google Volley
的单例模式实现:
package me.pc.mobile.tv.util; import android.content.Context;
import android.graphics.Bitmap;
import android.util.LruCache;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley; public class VolleySingleton {
private static VolleySingleton instance;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private VolleySingleton(Context context) {
requestQueue = Volley.newRequestQueue(context);
imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
private final LruCache<string, bitmap=""> cache = new LruCache<string, bitmap="">(20); @Override
public Bitmap getBitmap(String url) {
return cache.get(url);
} @Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
} public static VolleySingleton getInstance(Context context) {
if (instance == null) {
instance = new VolleySingleton(context);
}
return instance;
} public RequestQueue getRequestQueue() {
return requestQueue;
} public ImageLoader getImageLoader() {
return imageLoader;
}
}
VolleySingleton.java
采用Volley
的单例模式,就避免了在每一个Activity
或Frament
中都创建一个RequestQueue
的麻烦.
6,使用Google Volley
来实现文件的分块上传:
public class PhotoMultipartRequest extends Request { private static final String FILE_PART_NAME = "file"; private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
private final Response.Listener mListener;
private final File mImageFile;
protected Map<string, string=""> headers; public PhotoMultipartRequest(String url, ErrorListener errorListener, Listener listener, File imageFile){
super(Method.POST, url, errorListener); mListener = listener;
mImageFile = imageFile; buildMultipartEntity();
} @Override
public Map<string, string=""> getHeaders() throws AuthFailureError {
Map<string, string=""> headers = super.getHeaders(); if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<string, string="">();
} headers.put("Accept", "application/json"); return headers;
} private void buildMultipartEntity(){
mBuilder.addBinaryBody(FILE_PART_NAME, mImageFile, ContentType.create("image/jpeg"), mImageFile.getName());
mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mBuilder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));
} @Override
public String getBodyContentType(){
String contentTypeHeader = mBuilder.build().getContentType().getValue();
return contentTypeHeader;
} @Override
public byte[] getBody() throws AuthFailureError{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
mBuilder.build().writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream bos, building the multipart request.");
} return bos.toByteArray();
} @Override
protected Response parseNetworkResponse(NetworkResponse response) {
T result = null;
return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
} @Override
protected void deliverResponse(T response) {
mListener.onResponse(response);
}
}
PhotoMultipartRequest.java
代码中使用了Apache
的httpclient.jar
文件,用于实现文件的拆分与上传.