合并了钱阳的代码

ChiYanZhen_branch
CYZ 2 years ago
commit 72c4a6c66f

@ -180,27 +180,28 @@ public class Task extends Node {
|| !js.has(GTaskStringUtils.META_HEAD_DATA)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
}
if (js != null) {
try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) {
Log.e(TAG, "invalid type");
return;
}
if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) {
Log.e(TAG, "invalid type");
return;
}
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
setName(data.getString(DataColumns.CONTENT));
break;
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
setName(data.getString(DataColumns.CONTENT));
break;
}
}
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
}
}
}

@ -133,30 +133,31 @@ public class TaskList extends Node {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
}
try {
JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
String name = folder.getString(NoteColumns.SNIPPET);
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);
} else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER)
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);
else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER)
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_CALL_NOTE);
else
Log.e(TAG, "invalid system folder");
} else {
Log.e(TAG, "error type");
if (js != null) {
try {
JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
String name = folder.getString(NoteColumns.SNIPPET);
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);
} else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER)
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);
else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER)
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_CALL_NOTE);
else
Log.e(TAG, "invalid system folder");
} else {
Log.e(TAG, "error type");
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
}
}
}
public JSONObject getLocalJSONFromContent() {
try {
JSONObject js = new JSONObject();
@ -200,13 +201,7 @@ public class TaskList extends Node {
Log.e(TAG, "gtask id doesn't match");
return SYNC_ACTION_ERROR;
}
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// local modification only
return SYNC_ACTION_UPDATE_REMOTE;
} else {
// for folder conflicts, just apply local modification
return SYNC_ACTION_UPDATE_REMOTE;
}
return SYNC_ACTION_UPDATE_REMOTE;
}
} catch (Exception e) {
Log.e(TAG, e.toString());

@ -112,7 +112,7 @@ public class GTaskClient {
public boolean login(Activity activity) {
// we suppose that the cookie would expire after 5 minutes
// then we need to re-login
final long interval = 1000 * 60 * 5;
final long interval = 1000L * 60 * 5;
if (mLastLoginTime + interval < System.currentTimeMillis()) {
mLoggedin = false;
}
@ -306,8 +306,7 @@ public class GTaskClient {
input = new InflaterInputStream(entity.getContent(), inflater);
}
try {
InputStreamReader isr = new InputStreamReader(input);
try(InputStreamReader isr = new InputStreamReader(input)) {
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();

@ -295,6 +295,12 @@ public class GTaskManager {
"(type=? AND parent_id<>?)", new String[] {
String.valueOf(Notes.TYPE_NOTE), String.valueOf(Notes.ID_TRASH_FOLER)
}, NoteColumns.TYPE + " DESC");
Iterator<Map.Entry<String, Node>> iter = mGTaskHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Node> entry = iter.next();
node = entry.getValue();
doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, c);
}
if (c != null) {
while (c.moveToNext()) {
gid = c.getString(SqlNote.GTASK_ID_COLUMN);
@ -327,12 +333,7 @@ public class GTaskManager {
}
// go through remaining items
Iterator<Map.Entry<String, Node>> iter = mGTaskHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Node> entry = iter.next();
node = entry.getValue();
doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
}
// mCancelled can be set by another thread, so we neet to check one by
// one

@ -295,8 +295,7 @@ public class BackupUtils {
mFileName = file.getName();
mFileDirectory = mContext.getString(R.string.file_path);
PrintStream ps = null;
try {
FileOutputStream fos = new FileOutputStream(file);
try (FileOutputStream fos = new FileOutputStream(file)){
ps = new PrintStream(fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
@ -304,6 +303,9 @@ public class BackupUtils {
} catch (NullPointerException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
return ps;
}

@ -0,0 +1,369 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.tool;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.util.Base64;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
public class ImageUtils {
/**
* sizesize21/4
**/
public static Bitmap compressBitmap(String path, byte[] data, Context context, Uri uri, int size, boolean width) {
BitmapFactory.Options options = null;
if (size > 0) {
BitmapFactory.Options info = new BitmapFactory.Options();
/**如果设置true的时候decode时候Bitmap返回的为数据将空*/
info.inJustDecodeBounds = false;
decodeBitmap(path, data, context, uri, info);
int dim = info.outWidth;
if (!width) dim = Math.max(dim, info.outHeight);
options = new BitmapFactory.Options();
/**把图片宽高读取放在Options里*/
options.inSampleSize = size;
}
Bitmap bm = null;
try {
bm = decodeBitmap(path, data, context, uri, options);
} catch (Exception e) {
e.printStackTrace();
}
return bm;
}
/**
* byte
*/
private static Bitmap decodeBitmap(String path, byte[] data, Context context, Uri uri, BitmapFactory.Options options) {
Bitmap result = null;
if (path != null) {
result = BitmapFactory.decodeFile(path, options);
} else if (data != null) {
result = BitmapFactory.decodeByteArray(data, 0, data.length, options);
} else if (uri != null) {
ContentResolver cr = context.getContentResolver();
InputStream inputStream = null;
try {
inputStream = cr.openInputStream(uri);
result = BitmapFactory.decodeStream(inputStream, null, options);
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
/**
* bitmapString
*
* @param filePath
* @return
*/
public static String bitmapToString(String filePath) {
Bitmap bm = getSmallBitmap(filePath, 480, 800);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 40, baos);
byte[] b = baos.toByteArray();
return Base64.encodeToString(b, Base64.DEFAULT);
}
/**
*
*
* @param options
* @param reqWidth
* @param reqHeight
* @return
*/
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
/**
* bitmap
*
* @return
*/
public static Bitmap getSmallBitmap(String filePath, int newWidth, int newHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, newWidth, newHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
Bitmap newBitmap = compressImage(bitmap, 600);
if (bitmap != null){
bitmap.recycle();
}
return newBitmap;
}
/**
*
*
* @param path
*/
public static void deleteTempFile(String path) {
File file = new File(path);
if (file.exists()) {
file.delete();
}
}
/**
*
*/
public static void galleryAddPic(Context context, String path) {
Intent mediaScanIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(path);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
context.sendBroadcast(mediaScanIntent);
}
//使用Bitmap加Matrix来缩放
public static Bitmap resizeImage(Bitmap bitmapOrg, int newWidth, int newHeight)
{
// Bitmap bitmapOrg = BitmapFactory.decodeFile(imagePath);
// 获取这个图片的宽和高
int width = bitmapOrg.getWidth();
int height = bitmapOrg.getHeight();
//如果宽度为0 保持原图
if(newWidth == 0){
newWidth = width;
newHeight = height;
}
// 创建操作图片用的matrix对象
Matrix matrix = new Matrix();
// 计算宽高缩放率
float scaleWidth = (float) newWidth / width;
float scaleHeight = (float) newHeight / height;
// 缩放图片动作
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, newWidth,
newHeight, matrix, true);
//Log.e("###newWidth=", resizedBitmap.getWidth()+"");
//Log.e("###newHeight=", resizedBitmap.getHeight()+"");
resizedBitmap = compressImage(resizedBitmap, 100);//质量压缩
return resizedBitmap;
}
//使用BitmapFactory.Options的inSampleSize参数来缩放
public static Bitmap resizeImage2(String path, int width, int height)
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//不加载bitmap到内存中
BitmapFactory.decodeFile(path,options);
int outWidth = options.outWidth;
int outHeight = options.outHeight;
options.inDither = false;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inSampleSize = 1;
if (outWidth != 0 && outHeight != 0 && width != 0 && height != 0)
{
int sampleSize=(outWidth/width+outHeight/height)/2;
Log.d("###", "sampleSize = " + sampleSize);
options.inSampleSize = sampleSize;
}
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
/**
* Used to get thumbnail
* @param srcPath
* @return
*/
public static Bitmap compressBitmapByPath(String srcPath, float pixelW, float pixelH) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
//开始读入图片此时把options.inJustDecodeBounds 设回true了
newOpts.inJustDecodeBounds = true;
newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//此时返回bm为空
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
//现在主流手机比较多是800*480分辨率所以高和宽我们设置为
float hh = pixelH;//这里设置高度为800f
float ww = pixelW;//这里设置宽度为480f
//缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
int be = 1;//be=1表示不缩放
if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0)
be = 1;
newOpts.inSampleSize = be;//设置缩放比例
//重新读入图片注意此时已经把options.inJustDecodeBounds 设回false了
bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
// return compress(bitmap, maxSize); // 这里再进行质量压缩的意义不大,反而耗资源,删除
return bitmap;
}
/**
* Used to get thumbnail
* @param image
* @param pixelW
* @param pixelH
* @return
*/
public static Bitmap compressBitmapByBmp(Bitmap image, float pixelW, float pixelH) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, os);
if( os.toByteArray().length / 1024>1024) {//判断如果图片大于1M,进行压缩避免在生成图片BitmapFactory.decodeStream时溢出
os.reset();//重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG, 50, os);//这里压缩50%把压缩后的数据存放到baos中
}
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
BitmapFactory.Options newOpts = new BitmapFactory.Options();
//开始读入图片此时把options.inJustDecodeBounds 设回true了
newOpts.inJustDecodeBounds = true;
newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap bitmap = BitmapFactory.decodeStream(is, null, newOpts);
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
float hh = pixelH;// 设置高度为240f时可以明显看到图片缩小了
float ww = pixelW;// 设置宽度为120f可以明显看到图片缩小了
//缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
int be = 1;//be=1表示不缩放
if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0) be = 1;
newOpts.inSampleSize = be;//设置缩放比例
//重新读入图片注意此时已经把options.inJustDecodeBounds 设回false了
is = new ByteArrayInputStream(os.toByteArray());
bitmap = BitmapFactory.decodeStream(is, null, newOpts);
int desWidth = (int) (w / be);
int desHeight = (int) (h / be);
bitmap = Bitmap.createScaledBitmap(bitmap, desWidth, desHeight, true);
//压缩好比例大小后再进行质量压缩
// return compress(bitmap, maxSize); // 这里再进行质量压缩的意义不大,反而耗资源,删除
return bitmap;
}
/**
*
* @param image
* @param maxSize
*/
public static Bitmap compressImage(Bitmap image, int maxSize){
ByteArrayOutputStream os = new ByteArrayOutputStream();
// scale
int options = 80;
// Store the bitmap into output stream(no compress)
image.compress(Bitmap.CompressFormat.JPEG, options, os);
// Compress by loop
while ( os.toByteArray().length / 1024 > maxSize) {
// Clean up os
os.reset();
// interval 10
options -= 10;
image.compress(Bitmap.CompressFormat.JPEG, options, os);
}
Bitmap bitmap = null;
byte[] b = os.toByteArray();
if (b.length != 0) {
bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
}
return bitmap;
}
/**
*
* @param bgimage
* @param newWidth
* @param newHeight
* @return
*/
public static Bitmap zoomImage(Bitmap bgimage, double newWidth, double newHeight) {
// 获取这个图片的宽和高
float width = bgimage.getWidth();
float height = bgimage.getHeight();
//如果宽度为0 保持原图
if(newWidth == 0){
newWidth = width;
newHeight = height;
}
// 创建操作图片用的matrix对象
Matrix matrix = new Matrix();
// 计算宽高缩放率
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// 缩放图片动作
matrix.postScale(scaleWidth, scaleHeight);
Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
(int) height, matrix, true);
bitmap = compressImage(bitmap, 100);//质量压缩
return bitmap;
}
}

@ -0,0 +1,93 @@
package net.micode.notes.tool;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
public class ScreenUtils {
/**
*
* @param context
* @return
*/
public static int getScreenWidth(Context context)
{
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.widthPixels;
}
/**
*
* @param context
* @return
*/
public static int getScreenHeight(Context context) {
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.heightPixels;
}
/**
*
* @param context
* @return
*/
public static int getStatusHeight(Context context) {
int statusHeight = -1;
try {
Class<?> clazz = Class.forName("com.android.internal.R$dimen");
Object object = clazz.newInstance();
int height = Integer.parseInt(clazz.getField("status_bar_height")
.get(object).toString());
statusHeight = context.getResources().getDimensionPixelSize(height);
} catch (Exception e) {
e.printStackTrace();
}
return statusHeight;
}
/**
*
*/
public static Bitmap snapShotWithStatusBar(Activity activity){
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
int width = getScreenWidth(activity);
int height = getScreenHeight(activity);
Bitmap bp = null;
bp = Bitmap.createBitmap(bmp, 0, 0, width, height);
view.destroyDrawingCache();
return bp;
}
/**
*
*
*/
public static Bitmap snapShotWithoutStatusBar(Activity activity){
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
int width = getScreenWidth(activity);
int height = getScreenHeight(activity);
Bitmap bp = null;
bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height
- statusBarHeight);
view.destroyDrawingCache();
return bp;
}
}

@ -77,7 +77,7 @@ public class DateTimePickerDialog extends AlertDialog implements OnClickListener
DateUtils.FORMAT_SHOW_YEAR |
DateUtils.FORMAT_SHOW_DATE |
DateUtils.FORMAT_SHOW_TIME;
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR;
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_12HOUR;
setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));
}

@ -31,6 +31,9 @@ import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.location.Address;
@ -38,15 +41,20 @@ import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.format.DateUtils;
import android.text.style.BackgroundColorSpan;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
@ -79,8 +87,10 @@ import net.micode.notes.gtask.data.TaskList;
import net.micode.notes.model.WorkingNote;
import net.micode.notes.model.WorkingNote.NoteSettingChangedListener;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ImageUtils;
import net.micode.notes.tool.ResourceParser;
import net.micode.notes.tool.ResourceParser.TextAppearanceResources;
import net.micode.notes.tool.ScreenUtils;
import net.micode.notes.ui.DateTimePickerDialog.OnDateTimeSetListener;
import net.micode.notes.ui.NoteEditText.OnTextViewChangeListener;
import net.micode.notes.widget.NoteWidgetProvider_2x;
@ -90,9 +100,14 @@ import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.Timestamp;
import java.util.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
@ -103,7 +118,7 @@ import java.util.Stack;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.support.v13.app.ActivityCompat;
public class NoteEditActivity extends Activity implements OnClickListener,
NoteSettingChangedListener, OnTextViewChangeListener {
@ -334,6 +349,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
protected void onResume() {
super.onResume();
initNoteScreen();
initImage();
}
private void initNoteScreen() {
@ -524,7 +540,6 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE;
}
mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list);
}
@Override
@ -800,6 +815,11 @@ public class NoteEditActivity extends Activity implements OnClickListener,
case R.id.menu_delete_remind:
mWorkingNote.setAlertDate(0, false);
break;
case R.id.menu_Insert_Image:
Intent albumIntent = new Intent(Intent.ACTION_PICK);
albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(albumIntent, 1);
break;
case R.id.menu_private_folder:
moveToPrivateFolder();
break;
@ -1283,4 +1303,112 @@ public class NoteEditActivity extends Activity implements OnClickListener,
alertDialog2.show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {//处理从图库中返回的图片。
if (requestCode == 1) {//callGallery()方法是以请求码为1来开启活动的此处为响应活动结束
try {
// 获得图片的资源标识符
Uri originalUri = data.getData();
String[] proj = {MediaStore.Images.Media.DATA};
//从数据库中查询
Cursor cursor = getContentResolver().query(originalUri, proj, null, null, null);
//获得用户选择的图片的索引值
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
// 将光标移至开头 ,这个很重要,不小心很容易引起越界
cursor.moveToFirst();
// 最后根据索引值获取图片路径
String path = cursor.getString(column_index);
//插入图片
insertImg(path);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(NoteEditActivity.this, "图片插入失败", Toast.LENGTH_SHORT).show();
}
}
}
private void initImage() {
String input = String.valueOf(mWorkingNote.getContent());
if(!input.equals("null")) {//创建新便签时input的值是“null”必须判断不然创建的新便签都会有一个null的字符串
Pattern p = Pattern.compile("\\<img src=\".*?\"\\/>");
Matcher m = p.matcher(input);
SpannableString spannable = new SpannableString(input);
while (m.find()) {
String s = m.group();
int start = m.start();
int end = m.end();
String path = s.replaceAll("\\<img src=\"|\"\\/>", "").trim();//得到路径
int width = ScreenUtils.getScreenWidth(NoteEditActivity.this);//屏幕的宽度
//int height = ScreenUtils.getScreenHeight(NoteEditActivity.this);
try {
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
//适应屏幕,锁定横纵比缩小图片。
bitmap = ImageUtils.zoomImage(bitmap, (width - 32) * 0.8,
bitmap.getHeight() / (bitmap.getWidth() / ((width - 32) * 0.8)));
ImageSpan imageSpan = new ImageSpan(NoteEditActivity.this, bitmap);
spannable.setSpan(imageSpan, start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
} catch (Exception e) {
e.printStackTrace();
}
}
mNoteEditor.setVisibility(View.VISIBLE);
mNoteEditor.setText(spannable);
}
}
private SpannableString getBitmapMime(String path, String tagPath) {
SpannableString ss = new SpannableString(tagPath);//这里使用加了<img>标签的图片路径
int width = ScreenUtils.getScreenWidth(NoteEditActivity.this);
//int height = ScreenUtils.getScreenHeight(NoteEditActivity.this);
BitmapFactory.Options options = new BitmapFactory.Options();
//路径对应的图片
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
//适应屏幕,锁定横纵比缩小图片。
bitmap = ImageUtils.zoomImage(bitmap, (width - 32) * 0.8,
bitmap.getHeight() / (bitmap.getWidth() / ((width - 32) * 0.8)));
ImageSpan imageSpan = new ImageSpan(this, bitmap);
ss.setSpan(imageSpan, 0, tagPath.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return ss;
}
private void insertImg(String path) {
String tagPath = "<img src=\"" + path + "\"/>";//为图片路径加上<img>标签
Bitmap bitmap = BitmapFactory.decodeFile(path);//根据路径找到图片
if (bitmap != null) {
//格式化存储路径
SpannableString ss = getBitmapMime(path, tagPath);
//将图片插入文本视图
insertPhotoToEditText(ss);
Log.d("insertimage", path + "与" + tagPath);
} else {
Toast.makeText(NoteEditActivity.this, "插入失败,无读写存储权限,请到权限中心开启", Toast.LENGTH_LONG).show();
}
}
private void insertPhotoToEditText(SpannableString ss) {//把文本插入便签,如
Editable et = mNoteEditor.getText();
int start = mNoteEditor.getSelectionStart();
ss.getSpans(0, ss.length(), ImageSpan.class);
// 将图片添加进EditText中
if(start < 0 || start >= et.length()){
//如果是在文本的结尾
et.append(ss);
}else{
//如果是在文本的中间
et.insert(start, ss);
}
//将图片路径写入数据库——非常关键,否则无法显示图片
mWorkingNote.setWorkingText(et+"\n");
mNoteEditor.setText(et);
mNoteEditor.setSelection(start + ss.length());
mNoteEditor.setFocusableInTouchMode(true);
mNoteEditor.setFocusable(true);
}
}

Loading…
Cancel
Save