code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
package com.zz.common.app;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.util.Properties;
import com.zz.common.utils.DateTimeUtil;
import com.zz.common.utils.ZLog;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Process;
public class CrashController implements UncaughtExceptionHandler {
public interface OnCrashListener {
public boolean onCrash(String filePath, CrashController handler);
}
private static final String TAG = "CrashController";
/**
*
*/
private Thread.UncaughtExceptionHandler mDefaultHandler;
private Context mContext;
/**
*/
private Properties mDeviceCrashInfo = new Properties();
private static final String VERSION_NAME = "versionName";
private static final String VERSION_CODE = "versionCode";
private static final String CRASH_REPORTER_EXTENSION = ".txt";
private OnCrashListener mListener;
private String mCrashDirPath;
private String mCrashFilePath;
public CrashController(Context ctx, String logFileDirPath, OnCrashListener l) {
mContext = ctx;
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
mCrashDirPath = logFileDirPath;
mListener = l;
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
mDefaultHandler.uncaughtException(thread, ex);
} else {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
Process.killProcess(Process.myPid());
}
}
private boolean handleException(Throwable ex) {
if (ex == null) {
return true;
}
collectCrashDeviceInfo(mContext);
mCrashFilePath = saveCrashInfoToFile(ex);
ZLog.d(BaseConfig.TAG, ZLog.LOG_LEVEL_KEY, "Crash File: " + mCrashFilePath);
invokeCrashToListener();
return true;
}
private void invokeCrashToListener() {
if(null != mListener) {
mListener.onCrash(mCrashFilePath, this);
}
}
private String saveCrashInfoToFile(Throwable ex) {
Writer info = new StringWriter();
PrintWriter printWriter = new PrintWriter(info);
ex.printStackTrace(printWriter);
Throwable cause = ex.getCause();
while (cause != null) {
cause.printStackTrace(printWriter);
cause = cause.getCause();
}
String result = "\nstack:\n"+info.toString();
ZLog.d(TAG, result);
printWriter.close();
FileOutputStream trace = null;
String fileName = null;
try {
long timestamp = System.currentTimeMillis();
String path = mCrashDirPath;
File pathFile = new File(path);
if(!pathFile.exists() || !pathFile.isDirectory()) {
pathFile.mkdirs();
}
fileName = path+"crash-" + DateTimeUtil.getDateString(timestamp) + CRASH_REPORTER_EXTENSION;
trace = new FileOutputStream(new File(fileName));
mDeviceCrashInfo.store(trace, "");
trace.write(result.getBytes());
trace.flush();
} catch (Exception e) {
ZLog.d(TAG, "an error occured while writing report file..."+ e.toString());
fileName = null;
} finally {
if(null != trace) {
try {
trace.close();
} catch(Exception e) {
e = null;
}
}
}
return fileName;
}
private void collectCrashDeviceInfo(Context ctx) {
try {
PackageManager pm = ctx.getPackageManager();
PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(),
PackageManager.GET_ACTIVITIES);
if (pi != null) {
mDeviceCrashInfo.put(VERSION_NAME,
pi.versionName == null ? "not set" : pi.versionName);
mDeviceCrashInfo.put(VERSION_CODE, pi.versionCode+"");
}
} catch (NameNotFoundException e) {
ZLog.d(TAG, "Error while collect package info"+ e.toString());
}
Field[] fields = Build.class.getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
mDeviceCrashInfo.put(field.getName(), field.get(null)+"");
ZLog.d(TAG, field.getName() + " : " + field.get(null));
} catch (Exception e) {
ZLog.d(TAG, "Error while collect crash info"+ e);
}
}
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/app/CrashController.java
|
Java
|
epl
| 4,435
|
package com.zz.common.app;
import java.util.Collection;
import java.util.HashMap;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabContentFactory;
public class BaseFrameActivity extends BaseActivity implements TabContentFactory
, OnTabChangeListener {
private static final String INDEX_CURRENT_TAB_TAG = "current_tab_tag";
protected TabHost mTabHost;
private final HashMap<String, BaseFrame> mFrames = new HashMap<String, BaseFrame>(3);
private BaseFrame mPreFrame;
@Override
public void onStart() {
super.onStart();
getCurrentFrame().onStart();
}
@Override
public void onRestart() {
super.onRestart();
getCurrentFrame().onRestart();
}
@Override
public void onResume() {
super.onResume();
getCurrentFrame().onResume();
}
@Override
public void onPause() {
super.onPause();
getCurrentFrame().onPause();
}
@Override
public void onStop() {
super.onStop();
getCurrentFrame().onStop();
}
@Override
public void onDestroy() {
super.onDestroy();
Collection<BaseFrame> all = mFrames.values();
for (BaseFrame frame : all) {
frame.onDestroy();
}
}
public void addFrame(Class<? extends BaseFrame> clz, View tab) {
if (mTabHost == null) {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
mTabHost.setOnTabChangedListener(this);
}
mTabHost.addTab(mTabHost.newTabSpec(clz.getName()).setIndicator(tab).setContent(this));
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
getCurrentFrame().onActivityResult(requestCode, resultCode, data);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Collection<BaseFrame> all = mFrames.values();
for (BaseFrame frame : all) {
frame.onConfigurationChanged(newConfig);
}
}
@Override //TabContentFactory
public View createTabContent(String tag) {
final String className = tag;
View content = null;
BaseFrame frame = null;
try {
frame = (BaseFrame) Class.forName(className).newInstance();
} catch (Exception e) {
return null;
}
frame.setActivity(this);
content = frame.onCreateView(getLayoutInflater());
frame.setContentView(content);
frame.onCreate();
mFrames.put(className, frame);
return content;
}
@Override //TabHost.OnTabChangedListener
public void onTabChanged(String tabId) {
if (mPreFrame != null) {
mPreFrame.onPause();
}
mPreFrame = getCurrentFrame();
mPreFrame.onResume();
}
protected BaseFrame getCurrentFrame() {
return mFrames.get(mTabHost.getCurrentTabTag());
}
public int getCurrentTab() {
return mTabHost.getCurrentTab();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
String currentTabTag = mTabHost.getCurrentTabTag();
if (null != currentTabTag) {
outState.putString(INDEX_CURRENT_TAB_TAG, currentTabTag);
}
for(BaseFrame frame: mFrames.values()) {
frame.onSaveInstanceState(outState);
}
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
String currentTabTag = savedInstanceState.getString(INDEX_CURRENT_TAB_TAG);
if (null != currentTabTag) {
mTabHost.setCurrentTabByTag(currentTabTag);
}
for(BaseFrame frame: mFrames.values()) {
frame.onRestoreInstanceState(savedInstanceState);
}
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/app/BaseFrameActivity.java
|
Java
|
epl
| 4,302
|
package com.zz.common.app;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import com.zz.common.utils.ZLog;
import android.app.Application;
import android.os.Process;
public class BaseApplication extends Application implements CrashController.OnCrashListener {
public static String sCrashPath;
private static BaseApplication sApplication;
public static BaseApplication getBaseApplication() {
return sApplication;
}
public void exit() {
ArrayList<WeakReference<BaseActivity>> activityStack = BaseActivity.getActivityStack();
try {
for(WeakReference<BaseActivity> ref: activityStack) {
BaseActivity activity = ref.get();
if(null != activity && !activity.isFinishing()) {
activity.finish();
}
}
} catch(Exception e) {
e = null;
}
Process.killProcess(Process.myPid());
}
@Override
public void onCreate() {
super.onCreate();
sApplication = this;
CrashController controller = new CrashController(this, sCrashPath, this);
Thread.setDefaultUncaughtExceptionHandler(controller);
ZLog.d(BaseConfig.TAG, ZLog.LOG_LEVEL_KEY, "onCreate: " + this);
}
@Override
public void onTerminate() {
super.onTerminate();
ZLog.d(BaseConfig.TAG, ZLog.LOG_LEVEL_KEY, "onDestroy: " + this);
}
@Override //CrashController.OnCrashListener
public boolean onCrash(String filePath, CrashController handler) {
exit();
return false;
}
//
protected void onEnterBackground() {
ZLog.d(BaseConfig.TAG, ZLog.LOG_LEVEL_DEV, "onEnterBackground: " + this);
}
//
protected void onEnterForeground() {
ZLog.d(BaseConfig.TAG, ZLog.LOG_LEVEL_DEV, "onEnterForeground: " + this);
}
public static interface IBaseApplicationattachment {
public BaseApplication getBaseApplication();
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/app/BaseApplication.java
|
Java
|
epl
| 1,829
|
package com.zz.common.app;
import com.zz.common.app.BaseApplication.IBaseApplicationattachment;
import android.content.BroadcastReceiver;
public abstract class BaseBroadcastReceiver extends BroadcastReceiver implements IBaseApplicationattachment {
@Override // BaseApplication.IBaseApplicationattachment
public BaseApplication getBaseApplication() {
return BaseApplication.getBaseApplication();
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/app/BaseBroadcastReceiver.java
|
Java
|
epl
| 424
|
package com.zz.common.app;
public final class BaseConfig {
public static final String TAG = "zz";
// /* package */ static final
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/app/BaseConfig.java
|
Java
|
epl
| 142
|
package com.zz.common.app;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
public abstract class BaseFrame {
private BaseActivity mActivity;
private View mContentView;
protected void post(Runnable r) {
if(null != mContentView) {
mContentView.post(r);
}
}
void setActivity(BaseActivity act) {
this.mActivity = act;
}
void setContentView(View content) {
this.mContentView = content;
}
public View onCreateView(LayoutInflater inflater) {
return null;
}
public final BaseActivity getActivity() {
return mActivity;
}
protected void onCreate() {
}
protected void onStart() {
}
protected void onRestart() {
}
protected void onResume() {
}
protected void onPause() {
}
protected void onStop() {
}
protected void onDestroy() {
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
}
public void onConfigurationChanged(Configuration newConfig) {
}
protected void onSaveInstanceState(Bundle outState) {
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
}
public Resources getResources() {
return mActivity.getResources();
}
public View findViewById(int id) {
return mContentView.findViewById(id);
}
public void startActivity(Intent intent) {
mActivity.startActivity(intent);
}
public void startActivityForResult(Intent intent, int requestCode) {
mActivity.startActivityForResult(intent, requestCode);
}
public String getString(int resId) {
return mActivity.getString(resId);
}
public void runOnUiThread(Runnable action) {
mActivity.runOnUiThread(action);
}
public Object getSystemService(String name) {
return mActivity.getSystemService(name);
}
public ContentResolver getContentResolver() {
return mActivity.getContentResolver();
}
public void finish() {
mActivity.finish();
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/app/BaseFrame.java
|
Java
|
epl
| 2,425
|
package com.zz.common.app;
import com.zz.common.app.BaseApplication.IBaseApplicationattachment;
import com.zz.common.utils.ZLog;
import android.app.Service;
public abstract class BaseService extends Service implements IBaseApplicationattachment {
@Override
public void onCreate() {
super.onCreate();
ZLog.d(BaseConfig.TAG, ZLog.LOG_LEVEL_KEY, "onCreate: " + this);
}
@Override
public void onDestroy() {
super.onDestroy();
ZLog.d(BaseConfig.TAG, ZLog.LOG_LEVEL_KEY, "onDestroy: " + this);
}
@Override // BaseApplication.IBaseApplicationattachment
public BaseApplication getBaseApplication() {
return BaseApplication.getBaseApplication();
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/app/BaseService.java
|
Java
|
epl
| 696
|
package com.zz.common.app;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import com.zz.common.app.BaseApplication.IBaseApplicationattachment;
import com.zz.common.utils.ZLog;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class BaseActivity extends Activity implements IBaseApplicationattachment {
private static final String INDEX_LAST_TITLE_MIRROR = "last_title_mirror";
private static WeakReference<BaseActivity> sTopActivityRef;
private static int sActiveActivityCount;
private static final ArrayList<WeakReference<BaseActivity>> sActivityStack = new ArrayList<WeakReference<BaseActivity>>();
private String mLastTitleMirror;
public static BaseActivity getTopActivity() {
BaseActivity topActivity = null;
if(null != sTopActivityRef) {
topActivity = sTopActivityRef.get();
}
return topActivity;
}
public static ArrayList<WeakReference<BaseActivity>> getActivityStack() {
return sActivityStack;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLastTitleMirror = getIntent().getStringExtra(INDEX_LAST_TITLE_MIRROR);
WeakReference<BaseActivity> curActivityRef = new WeakReference<BaseActivity>(this);
synchronized (sActivityStack) {
sActivityStack.add(curActivityRef);
}
ZLog.d(BaseConfig.TAG, ZLog.LOG_LEVEL_KEY, "onCreate: " + this + " TaskId: " + super.getTaskId());
}
@Override
public void onStart() {
super.onStart();
ZLog.d(BaseConfig.TAG, ZLog.LOG_LEVEL_DEV, "onStart: " + this);
int preActiveCount = sActiveActivityCount;
sActiveActivityCount ++;
if(preActiveCount == 0) {
getBaseApplication().onEnterForeground();
}
}
@Override
public void onRestart() {
super.onRestart();
ZLog.d(BaseConfig.TAG, ZLog.LOG_LEVEL_DEV, "onRestart: " + this);
}
@Override
public void onResume() {
super.onResume();
ZLog.d(BaseConfig.TAG, ZLog.LOG_LEVEL_DEV, "onResume: " + this);
}
@Override
public void onPause() {
super.onPause();
ZLog.d(BaseConfig.TAG, ZLog.LOG_LEVEL_DEV, "onPause: " + this);
}
@Override
public void onStop() {
super.onStop();
ZLog.d(BaseConfig.TAG, ZLog.LOG_LEVEL_DEV, "onStop: " + this);
sActiveActivityCount --;
if(sActiveActivityCount == 0) {
getBaseApplication().onEnterBackground();
}
}
@Override
public void onDestroy() {
super.onDestroy();
synchronized (sActivityStack) {
int size = sActivityStack.size();
if(size > 0) {
sActivityStack.remove(size - 1);
}
}
ZLog.d(BaseConfig.TAG, ZLog.LOG_LEVEL_KEY, "onDestroy: " + this + " TaskId: " + super.getTaskId());
}
@Override // BaseApplication.IBaseApplicationattachment
public BaseApplication getBaseApplication() {
return BaseApplication.getBaseApplication();
}
@Override
public void startActivityForResult(Intent intent, int requestCode) {
String titleMirror = onGetTitleMirror();
intent.putExtra(INDEX_LAST_TITLE_MIRROR, titleMirror);
super.startActivityForResult(intent, requestCode);
}
@Override
protected void finalize() {
ZLog.d(BaseConfig.TAG, ZLog.LOG_LEVEL_DEV, "finalize: " + this);
try {
super.finalize();
} catch (Throwable e) {
e = null;
}
}
protected String onGetTitleMirror() {
return "";
}
protected String getLastTitleMirror() {
return mLastTitleMirror;
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/app/BaseActivity.java
|
Java
|
epl
| 3,519
|
package com.zz.common.app;
import com.zz.common.app.BaseApplication.IBaseApplicationattachment;
import android.content.ContentProvider;
public abstract class BaseContentProvider extends ContentProvider implements IBaseApplicationattachment {
@Override // BaseApplication.IBaseApplicationattachment
public BaseApplication getBaseApplication() {
return BaseApplication.getBaseApplication();
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/app/BaseContentProvider.java
|
Java
|
epl
| 417
|
package com.zz.common.widget;
import android.widget.Button;
import android.widget.ImageView;
public class SizeCallBackForMenu implements SizeCallBack {
private Button menu;
private int menuWidth;
public SizeCallBackForMenu(Button menu){
super();
this.menu = menu;
}
@Override
public void onGlobalLayout() {
this.menuWidth = this.menu.getMeasuredWidth() + 80;
}
@Override
public void getViewSize(int idx, int width, int height, int[] dims) {
dims[0] = width;
dims[1] = height;
if(idx != 1){
dims[0] = width - this.menuWidth;
}
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/widget/SizeCallBackForMenu.java
|
Java
|
epl
| 600
|
package com.zz.common.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ScrollView;
public class ZScrollView extends ScrollView {
public ZScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
setOverScrollMode(ScrollView.OVER_SCROLL_ALWAYS);
setFadingEdgeLength(0);
}
public ZScrollView(Context context)
{
super(context);
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/widget/ZScrollView.java
|
Java
|
epl
| 455
|
package com.zz.common.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.PopupWindow;
import android.widget.TextView;
public class ZBladeView extends View {
private OnItemClickListener mOnItemClickListener;
String[] b = { "#", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
"L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
"Y", "Z" };
int choose = -1;
Paint paint = new Paint();
boolean showBkg = false;
private PopupWindow mPopupWindow;
private TextView mPopupText;
private Handler handler = new Handler();
public ZBladeView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public ZBladeView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ZBladeView(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (showBkg) {
canvas.drawColor(Color.parseColor("#00000000"));
}
int height = getHeight();
int width = getWidth();
int singleHeight = height / b.length;
for (int i = 0; i < b.length; i++) {
paint.setColor(Color.BLACK);
paint.setTypeface(Typeface.DEFAULT_BOLD);
paint.setFakeBoldText(true);
paint.setAntiAlias(true);
if (i == choose) {
paint.setColor(Color.parseColor("#3399ff"));
}
float xPos = width / 2 - paint.measureText(b[i]) / 2;
float yPos = singleHeight * i + singleHeight;
canvas.drawText(b[i], xPos, yPos, paint);
paint.reset();
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
final int action = event.getAction();
final float y = event.getY();
final int oldChoose = choose;
final int c = (int) (y / getHeight() * b.length);
switch (action) {
case MotionEvent.ACTION_DOWN:
showBkg = true;
if (oldChoose != c) {
if (c > 0 && c < b.length) {
performItemClicked(c);
choose = c;
invalidate();
}
}
break;
case MotionEvent.ACTION_MOVE:
if (oldChoose != c) {
if (c > 0 && c < b.length) {
performItemClicked(c);
choose = c;
invalidate();
}
}
break;
case MotionEvent.ACTION_UP:
showBkg = false;
choose = -1;
dismissPopup();
invalidate();
break;
}
return true;
}
private void showPopup(int item) {
if (mPopupWindow == null) {
handler.removeCallbacks(dismissRunnable);
mPopupText = new TextView(getContext());
mPopupText.setBackgroundColor(Color.GRAY);
mPopupText.setTextColor(Color.CYAN);
mPopupText.setTextSize(50);
mPopupText.setGravity(Gravity.CENTER_HORIZONTAL
| Gravity.CENTER_VERTICAL);
mPopupWindow = new PopupWindow(mPopupText, 100, 100);
}
String text = "";
if (item == 0) {
text = "#";
} else {
text = Character.toString((char) ('A' + item - 1));
}
mPopupText.setText(text);
if (mPopupWindow.isShowing()) {
mPopupWindow.update();
} else {
mPopupWindow.showAtLocation(getRootView(),
Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
}
}
private void dismissPopup() {
handler.postDelayed(dismissRunnable, 800);
}
Runnable dismissRunnable = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
if (mPopupWindow != null) {
mPopupWindow.dismiss();
}
}
};
public boolean onTouchEvent(MotionEvent event) {
return super.onTouchEvent(event);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mOnItemClickListener = listener;
}
private void performItemClicked(int item) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(b[item]);
showPopup(item);
}
}
public interface OnItemClickListener {
void onItemClick(String s);
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/widget/ZBladeView.java
|
Java
|
epl
| 3,972
|
package com.zz.common.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ExpandableListView;
public class ZExpandableListView extends ExpandableListView {
public ZExpandableListView(Context context) {
super(context);
}
public ZExpandableListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ZExpandableListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/widget/ZExpandableListView.java
|
Java
|
epl
| 490
|
package com.zz.common.widget;
/**
* Copyright (C) 2010 The Android Open Source Project
*
* 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.
*/
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
/***
* A ListView that maintains a header pinned at the top of the list. The
* pinned header can be pushed up and dissolved as needed.
*/
public class ZPinnedHeaderListView extends ListView {
/***
* Adapter interface. The list adapter must implement this interface.
*/
public interface PinnedHeaderAdapter {
/***
* Pinned header state: don't show the header.
*/
public static final int PINNED_HEADER_GONE = 0;
/***
* Pinned header state: show the header at the top of the list.
*/
public static final int PINNED_HEADER_VISIBLE = 1;
/***
* Pinned header state: show the header. If the header extends beyond
* the bottom of the first shown element, push it up and clip.
*/
public static final int PINNED_HEADER_PUSHED_UP = 2;
/***
* Computes the desired state of the pinned header for the given
* position of the first visible list item. Allowed return values are
* {@link #PINNED_HEADER_GONE}, {@link #PINNED_HEADER_VISIBLE} or
* {@link #PINNED_HEADER_PUSHED_UP}.
*/
int getPinnedHeaderState(int position);
/***
* Configures the pinned header view to match the first visible list item.
*
* @param header pinned header view.
* @param position position of the first visible list item.
* @param alpha fading of the header view, between 0 and 255.
*/
void configurePinnedHeader(View header, int position, int alpha);
}
private static final int MAX_ALPHA = 255;
private PinnedHeaderAdapter mAdapter;
private View mHeaderView;
private boolean mHeaderViewVisible;
private int mHeaderViewWidth;
private int mHeaderViewHeight;
public ZPinnedHeaderListView(Context context) {
super(context);
}
public ZPinnedHeaderListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ZPinnedHeaderListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setPinnedHeaderView(View view) {
mHeaderView = view;
// Disable vertical fading when the pinned header is present
// TODO change ListView to allow separate measures for top and bottom fading edge;
// in this particular case we would like to disable the top, but not the bottom edge.
if (mHeaderView != null) {
setFadingEdgeLength(0);
}
requestLayout();
}
@Override
public void setAdapter(ListAdapter adapter) {
super.setAdapter(adapter);
mAdapter = (PinnedHeaderAdapter)adapter;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mHeaderView != null) {
measureChild(mHeaderView, widthMeasureSpec, heightMeasureSpec);
mHeaderViewWidth = mHeaderView.getMeasuredWidth();
mHeaderViewHeight = mHeaderView.getMeasuredHeight();
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (mHeaderView != null) {
mHeaderView.layout(0, 0, mHeaderViewWidth, mHeaderViewHeight);
configureHeaderView(getFirstVisiblePosition());
}
}
public void configureHeaderView(int position) {
if (mHeaderView == null) {
return;
}
int state = mAdapter.getPinnedHeaderState(position);
switch (state) {
case PinnedHeaderAdapter.PINNED_HEADER_GONE: {
mHeaderViewVisible = false;
break;
}
case PinnedHeaderAdapter.PINNED_HEADER_VISIBLE: {
mAdapter.configurePinnedHeader(mHeaderView, position, MAX_ALPHA);
if (mHeaderView.getTop() != 0) {
mHeaderView.layout(0, 0, mHeaderViewWidth, mHeaderViewHeight);
}
mHeaderViewVisible = true;
break;
}
case PinnedHeaderAdapter.PINNED_HEADER_PUSHED_UP: {
View firstView = getChildAt(0);
int bottom = firstView.getBottom();
int itemHeight = firstView.getHeight();
int headerHeight = mHeaderView.getHeight();
int y;
int alpha;
if (bottom < headerHeight) {
y = (bottom - headerHeight);
alpha = MAX_ALPHA * (headerHeight + y) / headerHeight;
} else {
y = 0;
alpha = MAX_ALPHA;
}
mAdapter.configurePinnedHeader(mHeaderView, position, alpha);
if (mHeaderView.getTop() != y) {
mHeaderView.layout(0, y, mHeaderViewWidth, mHeaderViewHeight + y);
}
mHeaderViewVisible = true;
break;
}
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
if (mHeaderViewVisible) {
drawChild(canvas, mHeaderView, getDrawingTime());
}
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/widget/ZPinnedHeaderListView.java
|
Java
|
epl
| 6,220
|
package com.zz.common.widget;
import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ListView;
public class ZHorizontalScrollView extends HorizontalScrollView {
private ZHorizontalScrollView me;
private ListView menu;
public static boolean menuOut;
private final int ENLARGE_WIDTH = 80;
private int menuWidth;
private float lastMotionX = -1;
private Button expandButton;
private int current;
private int scrollToViewPos;
private int menuFoldRid;
private int menuUnfoldRid;
public ZHorizontalScrollView(Context context) {
super(context);
init();
}
public ZHorizontalScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ZHorizontalScrollView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init(){
this.setHorizontalFadingEdgeEnabled(false);
this.setVerticalFadingEdgeEnabled(false);
this.me = this;
this.me.setVisibility(View.INVISIBLE);
menuOut = false;
}
public void initViews(View[] children, SizeCallBack sizeCallBack, ListView menu){
this.menu = menu;
ViewGroup parent = (ViewGroup)getChildAt(0);
for(int i = 0; i < children.length; i++){
children[i].setVisibility(View.INVISIBLE);
parent.addView(children[i]);
}
OnGlobalLayoutListener onGlLayoutistener = new MenuOnGlobalLayoutListener(parent,
children, sizeCallBack);
getViewTreeObserver().addOnGlobalLayoutListener(onGlLayoutistener);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev){
return false;
}
public void setExpandButton(Button btn){
this.expandButton = btn;
}
public void clickExpandButton(){
if(!menuOut){
this.menuWidth = 0;
}
else{
this.menuWidth = this.menu.getMeasuredWidth() - this.expandButton.getMeasuredWidth() - this.ENLARGE_WIDTH;
}
menuSlide();
}
private void menuSlide(){
if(this.menuWidth == 0){
menuOut = true;
}
else{
menuOut = false;
}
me.scrollTo(this.menuWidth, 0);
if(menuOut == true)
this.expandButton.setBackgroundResource(menuFoldRid);
else
this.expandButton.setBackgroundResource(menuUnfoldRid);
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
// TODO Auto-generated method stub
super.onScrollChanged(l, t, oldl, oldt);
if(l < (this.menu.getMeasuredWidth() - this.expandButton.getMeasuredWidth() - this.ENLARGE_WIDTH) / 2){
this.menuWidth = 0;
}
else{
this.menuWidth = this.menu.getWidth() - this.expandButton.getMeasuredWidth() - this.ENLARGE_WIDTH;
}
this.current = l;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
// TODO Auto-generated method stub
int x = (int)ev.getRawX();
if(ev.getAction() == MotionEvent.ACTION_DOWN){
this.lastMotionX = (int)ev.getRawX();
}
if((this.current == 0 && x < this.scrollToViewPos) ||
(this.current == this.scrollToViewPos * 2 && x > this.ENLARGE_WIDTH)){
return false;
}
if(menuOut == false && this.lastMotionX > 20){
return true;
}
else{
if(ev.getAction() == MotionEvent.ACTION_UP){
menuSlide();
return false;
}
}
return super.onTouchEvent(ev);
}
public class MenuOnGlobalLayoutListener implements OnGlobalLayoutListener {
private ViewGroup parent;
private View[] children;
//private int scrollToViewIndex = 0;
private SizeCallBack sizeCallBack;
public MenuOnGlobalLayoutListener(ViewGroup parent, View[] children, SizeCallBack sizeCallBack) {
this.parent = parent;
this.children = children;
this.sizeCallBack = sizeCallBack;
}
@Override
public void onGlobalLayout() {
// TODO Auto-generated method stub
me.getViewTreeObserver().removeGlobalOnLayoutListener(this);
this.sizeCallBack.onGlobalLayout();
this.parent.removeViewsInLayout(0, children.length);
int width = me.getMeasuredWidth();
int height = me.getMeasuredHeight();
int[] dims = new int[2];
scrollToViewPos = 0;
for(int i = 0; i < children.length; i++){
this.sizeCallBack.getViewSize(i, width, height, dims);
children[i].setVisibility(View.VISIBLE);
parent.addView(children[i], dims[0], dims[1]);
if(i == 0){
scrollToViewPos += dims[0];
}
}
new Handler().post(new Runnable(){
@Override
public void run(){
me.scrollBy(scrollToViewPos, 0);
me.setVisibility(View.VISIBLE);
menu.setVisibility(View.VISIBLE);
}
});
}
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/widget/ZHorizontalScrollView.java
|
Java
|
epl
| 5,216
|
package com.zz.common.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;
public class ZListView extends ListView {
public ZListView(Context context) {
super(context);
}
public ZListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ZListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/widget/ZListView.java
|
Java
|
epl
| 451
|
package com.zz.common.widget;
import com.zz.common.utils.ZLog;
import android.content.Context;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
public class ZFixedGridView extends ViewGroup {
private static final String TAG = "ZFixedGridView";
private int mCellWidth;
private int mCellHeight;
private int mColNum;
public ZFixedGridView(Context context) {
super(context);
}
public ZFixedGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ZFixedGridView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setColNom(int colNum) {
if (colNum > 0) {
mColNum = colNum;
} else {
throw new IllegalArgumentException("colNum must bigger than 0");
}
}
public void setCellHeightByPixel(int pixels) {
mCellHeight = pixels;
}
public void setCellHeightByDip(int dip) {
DisplayMetrics dm = getResources().getDisplayMetrics();
int heightPixels = (int) (dip * dm.density + 0.5);
setCellHeightByPixel(heightPixels);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int cellWidthSpec = MeasureSpec.makeMeasureSpec(mCellWidth,
MeasureSpec.AT_MOST);
int cellHeightSpec = MeasureSpec.makeMeasureSpec(mCellHeight,
MeasureSpec.AT_MOST);
int count = getChildCount();
for (int index = 0; index < count; index++) {
final View child = getChildAt(index);
child.measure(cellWidthSpec, cellHeightSpec);
}
// Use the size our parents gave us
setMeasuredDimension(resolveSize(mCellWidth * count, widthMeasureSpec),
resolveSize(mCellHeight * count, heightMeasureSpec));
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int cellWidth = mCellWidth;
int cellHeight = mCellHeight;
int columns = (r - l) / cellWidth;
if (columns < 0) {
columns = 1;
}
int x = 0;
int y = 0;
int i = 0;
int count = getChildCount();
for (int index = 0; index < count; index++) {
final View child = getChildAt(index);
int w = child.getMeasuredWidth();
int h = child.getMeasuredHeight();
int left = x + ((cellWidth - w) / 2);
int top = y + ((cellHeight - h) / 2);
child.layout(left, top, left + w, top + h);
if (i >= (columns - 1)) {
// advance to next row
i = 0;
x = 0;
y += cellHeight;
} else {
i++;
x += cellWidth;
}
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
ZLog.d(TAG, ZLog.LOG_LEVEL_DEBUG, "onSizeChanged");
if(mColNum > 0) {
mCellWidth = w/mColNum;
} else {
mCellWidth = w;
}
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/widget/ZFixedGridView.java
|
Java
|
epl
| 2,863
|
package com.zz.common.widget;
public interface SizeCallBack {
public void onGlobalLayout();
public void getViewSize(int idx, int width, int height, int[] dims);
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/widget/SizeCallBack.java
|
Java
|
epl
| 176
|
package com.zz.common.utils;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.util.Base64;
public abstract class AlgorithmUtil {
public static String md5(String key) {
try {
char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
MessageDigest md;
md = MessageDigest.getInstance("MD5");
byte[] buf = key.getBytes();
md.update(buf, 0, buf.length);
byte[] bytes = md.digest();
StringBuilder sb = new StringBuilder(32);
for (byte b : bytes) {
sb.append(hex[((b >> 4) & 0xF)]).append(hex[((b >> 0) & 0xF)]);
}
key = sb.toString();
} catch (NoSuchAlgorithmException e) {
e = null;
}
return key;
}
public static String base64Encode(String str) {
if (null == str) {
return null;
}
return Base64.encodeToString(str.getBytes(), Base64.NO_WRAP);
}
public static String encodeUrl(String str) {
String result = "";
try {
result = URLEncoder.encode(str,"UTF-8");
result = URLEncoder.encode(result);
} catch (Exception e) {
e = null;
}
return result;
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/utils/AlgorithmUtil.java
|
Java
|
epl
| 1,189
|
package com.zz.common.utils;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
public abstract class PackageUtil {
public static int getVerCode(Context context) {
String packageName = context.getPackageName();
return getVerCode(context, packageName);
}
public static int getVerCode(Context context, String packageName) {
int verCode = -1;
try {
verCode = context.getPackageManager().getPackageInfo(packageName, 0).versionCode;
} catch (NameNotFoundException e) {
e = null;
}
return verCode;
}
public static String getVerName(Context context) {
String packageName = context.getPackageName();
return getVerName(context, packageName);
}
public static String getVerName(Context context, String packageName) {
String verName = "";
try {
verName = context.getPackageManager().getPackageInfo(packageName, 0).versionName;
} catch (NameNotFoundException e) {
e = null;
}
return verName;
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/utils/PackageUtil.java
|
Java
|
epl
| 1,021
|
package com.zz.common.utils;
public class HexUtil {
private static final char[] digits = new char[] { '0', '1', '2', '3', '4',//
'5', '6', '7', '8', '9',//
'A', 'B', 'C', 'D', 'E',//
'F' };
public static final byte[] emptybytes = new byte[0];
/**
* @return String Hex String
*/
public static String byte2HexStr(byte b) {
char[] buf = new char[2];
buf[1] = digits[b & 0xF];
b = (byte) (b >>> 4);
buf[0] = digits[b & 0xF];
return new String(buf);
}
/**
* @param b
* @return String
*/
public static String bytes2HexStr(byte[] bytes) {
if (bytes == null || bytes.length == 0) {
return null;
}
char[] buf = new char[2 * bytes.length];
for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
buf[2 * i + 1] = digits[b & 0xF];
b = (byte) (b >>> 4);
buf[2 * i + 0] = digits[b & 0xF];
}
return new String(buf);
}
/**
* @return byte
*/
public static byte hexStr2Byte(String str) {
if (str != null && str.length() == 1) {
return char2Byte(str.charAt(0));
} else {
return 0;
}
}
/**
* @return byte
*/
public static byte char2Byte(char ch) {
if (ch >= '0' && ch <= '9') {
return (byte) (ch - '0');
} else if (ch >= 'a' && ch <= 'f') {
return (byte) (ch - 'a' + 10);
} else if (ch >= 'A' && ch <= 'F') {
return (byte) (ch - 'A' + 10);
} else {
return 0;
}
}
public static byte[] hexStr2Bytes(String str) {
if (str == null || str.equals("")) {
return emptybytes;
}
byte[] bytes = new byte[str.length() / 2];
for (int i = 0; i < bytes.length; i++) {
char high = str.charAt(i * 2);
char low = str.charAt(i * 2 + 1);
bytes[i] = (byte) (char2Byte(high) * 16 + char2Byte(low));
}
return bytes;
}
public static String hexString2String(String hexString){
byte[] hexFileKeyByte = HexUtil.hexStr2Bytes(hexString);
String string = new String(hexFileKeyByte);
return string;
}
public static String String2HexString(String string){
byte[] temp = string.getBytes();
String hexString = HexUtil.bytes2HexStr(temp);
return hexString;
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/utils/HexUtil.java
|
Java
|
epl
| 2,171
|
package com.zz.common.utils;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
public abstract class DeviceUtil {
public static int px2dip(Context context, float pxValue){
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(pxValue / scale + 0.5f);
}
public static int dip2px(Context context, float dipValue){
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(dipValue * scale + 0.5f);
}
public static String getMacAddr(Context context){
String result = "";
WifiManager wfm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wfm.getConnectionInfo();
if(null != info) {
result = info.getMacAddress();
}
return result;
}
public static String getIMEI(Context ctx) {
TelephonyManager tm = (TelephonyManager) ctx
.getSystemService(Context.TELEPHONY_SERVICE);
String imei = tm.getDeviceId();
if (null == imei || "".equals(imei)) {
imei = "000000000000000";
}
return imei;
}
public static String getMac(Context ctx){
WifiManager wifiMgr = (WifiManager) ctx
.getSystemService(Context.WIFI_SERVICE);
String mac = wifiMgr.getConnectionInfo().getMacAddress();
return mac;
}
public static String getPeerId(Context c) {
String peerid = getIMEI(c)+"V";
if ("000000000000000V".equals(peerid)){
String mac = getMac(c);
if (mac!=null){
peerid = mac.replace(":", "")+"003V";
}
}
return peerid;
}
public static int getScreenWidth(Context context) {
return context.getResources().getDisplayMetrics().widthPixels;
}
public static int getScreenHeight(Context context) {
return context.getResources().getDisplayMetrics().heightPixels;
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/utils/DeviceUtil.java
|
Java
|
epl
| 1,919
|
package com.zz.common.utils;
import java.io.File;
import android.os.Environment;
import android.os.StatFs;
public abstract class StorageUtil {
public static String getSDCardDir() {
String path = Environment.getExternalStorageDirectory().getPath();
if(null != path && !path.endsWith("/")) {
path = path + "/";
}
return path;
}
public static boolean isSDCardExist() {
return Environment.MEDIA_MOUNTED.equalsIgnoreCase(Environment.getExternalStorageState());
}
public static long getAvailableExternalMemorySize() {
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
return availableBlocks * blockSize;
}
public static long getTotalExternalMemorySize() {
File path = Environment.getExternalStorageDirectory();
Environment.getExternalStorageState();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
return totalBlocks * blockSize;
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/utils/StorageUtil.java
|
Java
|
epl
| 1,254
|
package com.zz.common.utils;
import android.util.Log;
public final class ZLog {
/**
* only console, only debug version;
*/
public static final int LOG_LEVEL_DEBUG = 0x01;
/**
* console and local file, only debug version;
*/
public static final int LOG_LEVEL_DEV = 0x02;
/**
* console and local file, debug version and release version;
*/
public static final int LOG_LEVEL_KEY = 0x03;
public static int sLogLevel = LOG_LEVEL_DEBUG;
/**
* d(tag, {@link LOG_LEVEL_DEV}, content)
*/
public static void d(String tag, byte[] content) {
d(tag, LOG_LEVEL_DEV, content);
}
/**
*
* @param logLevel {@link LOG_LEVEL_DEBUG}, {@link LOG_LEVEL_DEV}, {@link LOG_LEVEL_KEY}
*/
public static void d(String tag, int logLevel, byte[] content) {
if(logLevel >= sLogLevel) {
String strContent = new String(content);
d(tag, logLevel, strContent);
}
}
/**
* d(tag, {@link LOG_LEVEL_DEV}, content)
*/
public static void d(String tag, String content) {
d(tag, LOG_LEVEL_DEV, content);
}
/**
*
* @param logLevel {@link LOG_LEVEL_DEBUG}, {@link LOG_LEVEL_DEV}, {@link LOG_LEVEL_KEY}
*/
public static void d(String tag, int logLevel, String content) {
if(logLevel >= sLogLevel) {
Log.d(tag, content);
}
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/utils/ZLog.java
|
Java
|
epl
| 1,329
|
package com.zz.common.utils;
import java.net.URLEncoder;
public class URLEncoderUtil {
public static String string2DoubleEncode(String originalString){
String result = null;
try {
result = URLEncoder.encode(originalString,"UTF-8");
result = URLEncoder.encode(result,"UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/utils/URLEncoderUtil.java
|
Java
|
epl
| 384
|
package com.zz.common.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ExifInterface;
public abstract class ImageUtil {
public static Bitmap decodeStream(InputStream is){
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is);
long temp = opts.outHeight * opts.outWidth;
if(temp >= 1280 * 768) {
opts.inSampleSize = 3;
} else if(temp >= 480 * 800) {
opts.inSampleSize = 2;
}
Bitmap bitmap =null;
try {
bitmap = BitmapFactory.decodeStream(is);
} catch(Throwable t) {
t = null;
bitmap = null;
}
return bitmap;
}
public static Bitmap decodeLocalFile(String localpath, int len){
java.io.File localFile = new java.io.File(localpath);
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 1;
if (localFile.length()>=100*1024) {
if (len == 240 || len == 320) {
opts.inSampleSize = 2;
}else {
opts.inSampleSize = 1;
}
}
if (localFile.length()>=200*1024) {
if (len == 240 || len == 320) {
opts.inSampleSize = 3;
}else {
opts.inSampleSize = 1;
}
}
if (localFile.length()>=400*1024) {
if (len == 240|| len == 320) {
opts.inSampleSize = 4;
}else {
opts.inSampleSize = 2;
}
}
if (localFile.length()>=500*1024) {
if (len == 240 || len == 320) {
opts.inSampleSize = 6;
}else {
opts.inSampleSize = 4;
}
}
opts.inPreferredConfig = Bitmap.Config.RGB_565;
opts.inPurgeable = true;
opts.inInputShareable = true;
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeFile(localpath, opts);
} catch (Throwable t) {
}
return bitmap;
}
public static void saveBitmapToFile(Bitmap bitmap, File file) throws IOException {
String parentPath = file.getParent();
File parentFile = new File(parentPath);
if(!parentFile.exists() || !parentFile.isDirectory()) {
parentFile.mkdirs();
parentFile = null;
}
if(!file.exists() || !file.isFile()) {
file.createNewFile();
}
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
} catch (IOException e) {
} finally {
if(null != fOut) {
fOut.close();
}
}
}
public static void saveBitmapFileAsJPEG(Bitmap bitmap, File file) throws IOException{
String parentPath = file.getParent();
File parentFile = new File(parentPath);
if(!parentFile.exists() || !parentFile.isDirectory()) {
parentFile.mkdirs();
parentFile = null;
}
if(!file.exists() || !file.isFile()) {
file.createNewFile();
}
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
} catch (IOException e) {
} finally {
if(null != fOut) {
fOut.close();
}
}
}
public static final Bitmap round(Bitmap src, float corner) {
if(null == src) {
return null;
}
Bitmap output = null;
try {
output = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Config.ARGB_8888);
}
catch(OutOfMemoryError oome) {
}
if(output != null) {
Canvas canvas = new Canvas(output);
Paint paint = new Paint();
final Rect rect = new Rect(0, 0, src.getWidth(), src.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = corner;
paint.setAntiAlias(true);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(src, rect, rect, paint);
}
return output;
}
public static final void roundInCanvas(Bitmap src, Canvas outCanvas, int x, int y
, float corner, int bgColor) {
if(null == src || null == outCanvas) {
return;
}
int imageWidth = src.getWidth();
int imageHeight = src.getHeight();
final Rect dstRect = new Rect(x, y, imageWidth+x, imageHeight+y);
final Rect srcRect = new Rect(0, 0, imageWidth, imageHeight);
final RectF rectF = new RectF(srcRect);
final float roundPx = corner;
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(bgColor);
Bitmap mask = Bitmap.createBitmap(imageWidth, imageHeight, Config.ARGB_8888);
Canvas maskCanvas = new Canvas(mask);
maskCanvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
maskCanvas.drawBitmap(src, srcRect, srcRect, paint);
outCanvas.drawBitmap(mask, srcRect, dstRect, null);
}
public static BitmapFactory.Options getImageOptions(InputStream in) {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, opts);
return opts;
}
public static Bitmap zoomIn(Bitmap bitmap, int maxW, int maxH) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
if (width <= maxW && height <= maxH)
return bitmap;
Matrix matrix = new Matrix();
float ratio = (float) getRatio(width, height, maxW, maxH);
matrix.postScale(ratio, ratio);
Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
return newbmp;
}
private static double getRatio(int srcWidth, int srcHeight, int maxWidth, int maxHeight) {
double ratio = 0.0;
double ratio_w = 0.0;
double ratio_h = 0.0;
if (srcWidth <= maxWidth && srcHeight <= maxHeight) {
return 0.0;
}
ratio_w = (double) maxWidth / (double) srcWidth;
ratio_h = (double) maxHeight / (double) srcHeight;
if (ratio_w < ratio_h) {
ratio = ratio_w;
} else {
ratio = ratio_h;
}
return ratio;
}
public static Bitmap rotateBitmap(File destFile, Bitmap bitmapOrg) {
if (bitmapOrg == null) {
return null;
}
Bitmap newBitmap = null;
try {
int rotateDegree = ImageUtil.getExifOrientation(destFile.getPath());
if (rotateDegree != 0 && 0 == rotateDegree % 90) {
Matrix m = new Matrix();
m.setRotate(rotateDegree, bitmapOrg.getWidth() / 2f,
bitmapOrg.getHeight() / 2f);
newBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
bitmapOrg.getWidth(), bitmapOrg.getHeight(), m, true);
}
} catch (Exception exception) {
newBitmap = null;
} catch (OutOfMemoryError e) {
newBitmap = null;
}
if (newBitmap != null) {
if (bitmapOrg != null && !bitmapOrg.isRecycled()
&& !bitmapOrg.equals(newBitmap)) {
bitmapOrg.recycle();
}
return newBitmap;
} else {
return bitmapOrg;
}
}
public static int getExifOrientation(String filepath) {
int degree = 0;
ExifInterface exif = null;
try {
exif = new ExifInterface(filepath);
} catch (IOException ex) {
}
if (exif != null) {
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, -1);
if (orientation != -1) {
// We only recognize a subset of orientation tag values.
switch(orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
}
}
return degree;
}
private static Bitmap scaleBitmap(Bitmap bitmapOrg, int max) {
if (bitmapOrg == null) {
return null;
}
Matrix m = new Matrix();
int bitmapWidth = bitmapOrg.getWidth();
int bitmapHeight = bitmapOrg.getHeight();
float scale = max / (Math.max(bitmapWidth, bitmapHeight) * 1.0f);
Bitmap newBitmap = null;
try {
if (scale != 1.0f && scale > 0) {
m.postScale(scale, scale);
newBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, bitmapWidth,bitmapHeight, m, true);
}
} catch(Exception e){
e = null;
} catch (OutOfMemoryError error) {
error = null;
}
if (newBitmap != null) {
if (bitmapOrg != null && !bitmapOrg.isRecycled()
&& !bitmapOrg.equals(newBitmap)) {
bitmapOrg.recycle();
}
return newBitmap;
} else {
return bitmapOrg;
}
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/utils/ImageUtil.java
|
Java
|
epl
| 9,506
|
package com.zz.common.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
public abstract class DateTimeUtil {
public static String getDateString(long ms) {
return getDateString(ms, "yyyy-MM-dd HH:mm:ss");
}
public static String getDateString(long ms, String format) {
Date curDate = new Date(ms);
return getDateString(curDate, format);
}
public static String getNowDateString() {
return getNowDateString("yyyy-MM-dd HH:mm:ss");
}
public static String getNowDateString(String format) {
Date curDate = new Date(System.currentTimeMillis());
return getDateString(curDate, format);
}
public static String getDateString(Date date) {
return getDateString(date, "yyyy-MM-dd HH:mm:ss");
}
public static String getDateString(Date date, String format) {
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.format(date);
}
}
|
zzdache
|
trunk/android/Common/sdk/com/zz/common/utils/DateTimeUtil.java
|
Java
|
epl
| 1,001
|
package com.zz.cc.business.data;
public class StoreBasicInfo {
public String mUserName;
public String mPwd;
public String mStoreName;
public String mAddress;
public String mPhoneNum;
public String mID;
}
|
zzdache
|
trunk/android/cc/Business/src/com/zz/cc/business/data/StoreBasicInfo.java
|
Java
|
epl
| 211
|
package com.zz.cc.business.data;
public class ServiceType {
private static final ServiceType []sServiceTypes = new ServiceType[] {
new ServiceType(0x100001, "维修"),
new ServiceType(0x100002, "美容"),
new ServiceType(0x100003, "洗车"),
};
public long mTypeId;
public String mTypeName;
private ServiceType(long typeId, String typeName) {
mTypeId = typeId;
mTypeName = typeName;
}
public static ServiceType []getAllServiceTypes() {
return sServiceTypes;
}
}
|
zzdache
|
trunk/android/cc/Business/src/com/zz/cc/business/data/ServiceType.java
|
Java
|
epl
| 489
|
package com.zz.cc.business.data;
import android.content.Context;
import com.zz.cc.business.BusinessApplication;
import com.zz.cc.common.data.IFileManager;
import com.zz.common.tools.ImageLoader.IUrlLocalFilePathCreator;
import com.zz.common.utils.AlgorithmUtil;
import com.zz.common.utils.FileUtil;
import com.zz.common.utils.StorageUtil;
public final class FileManager extends IFileManager implements IUrlLocalFilePathCreator {
private static final String FILE_NAME_QR_CODE = "qrCode.jpg";
private static FileManager sInstance;
private String mWorkPath;
private String mIconCachePath;
public static FileManager getInstance() {
if(null == sInstance) {
sInstance = new FileManager(BusinessApplication.getBaseApplication());
}
return sInstance;
}
@Override
public String getWorkDir() {
return mWorkPath;
}
public String getIconPathForUrl(String url) {
String md5 = AlgorithmUtil.md5(url);
String path = mIconCachePath + md5 + ICON_FILE_EXTENSION;
return path;
}
@Override //ImageLoader.IUrlLocalFilePathCreator
public String createLocalFilePathForUrl(String url) {
return getIconPathForUrl(url);
}
public String getQrCodePath() {
return mWorkPath + FILE_NAME_QR_CODE;
}
private FileManager(Context c) {
String path = StorageUtil.getSDCardDir();
mWorkPath = path + PATH_ROOT + PATH_BUSINES;
mIconCachePath = mWorkPath + PATH_ICON_CACHE;
FileUtil.ensureDir(mIconCachePath);
makeDirNoMedia(mIconCachePath);
}
}
|
zzdache
|
trunk/android/cc/Business/src/com/zz/cc/business/data/FileManager.java
|
Java
|
epl
| 1,532
|
package com.zz.cc.business.data;
import java.util.List;
import com.zz.cc.business.BusinessApplication;
import android.app.Application;
public class ModelCenter {
private static final String TAG = "ModelCenter";
private static ModelCenter sCenter;
private Application mContext;
public static ModelCenter getCenter() {
synchronized (TAG) {
if(null == sCenter) {
sCenter = new ModelCenter(BusinessApplication.getBaseApplication());
}
}
return sCenter;
}
//limit Context as Application
private ModelCenter(Application app) {
mContext = app;
}
}
|
zzdache
|
trunk/android/cc/Business/src/com/zz/cc/business/data/ModelCenter.java
|
Java
|
epl
| 585
|
package com.zz.cc.business.data;
import java.util.ArrayList;
import java.util.List;
public class ServiceInfo {
public String mUserName;
public String mCarNum;
public String mPhoneNum;
public String mServiceTime;
public String mCost;
public int mServiceCount;
public static List<ServiceInfo> generateServiceInfoList() {
List<ServiceInfo> list = new ArrayList<ServiceInfo>();
ServiceInfo s = new ServiceInfo();
s.mUserName = "zhoupeng";
s.mCarNum = "BMW";
s.mPhoneNum = "1234567";
s.mServiceTime = "2013-01-01";
s.mCost = "10000";
s.mServiceCount = 2;
list.add(s);
s = new ServiceInfo();
s.mUserName = "zhongbingxin";
s.mCarNum = "BMW";
s.mPhoneNum = "1234567";
s.mServiceTime = "2013-11-01";
s.mCost = "10000";
s.mServiceCount = 3;
list.add(s);
return list;
}
}
|
zzdache
|
trunk/android/cc/Business/src/com/zz/cc/business/data/ServiceInfo.java
|
Java
|
epl
| 855
|
package com.zz.cc.business.data;
import java.util.ArrayList;
import java.util.List;
public class StoreDetailInfo {
public float mServicePrice;
public float mVipPrice;
public String mSummary;
public final List<ServiceType> mServiceTypes = new ArrayList<ServiceType>();
public final List<String> mIconUrls = new ArrayList<String>();
}
|
zzdache
|
trunk/android/cc/Business/src/com/zz/cc/business/data/StoreDetailInfo.java
|
Java
|
epl
| 348
|
package com.zz.cc.business.data;
public abstract class BoxAction {
public static final int ACTION_LOGIN = 0x10000;
public static final int ACTION_LOGOUT = ACTION_LOGIN + 1;
}
|
zzdache
|
trunk/android/cc/Business/src/com/zz/cc/business/data/BoxAction.java
|
Java
|
epl
| 179
|
package com.zz.cc.business.data;
import com.zz.common.tools.ImageLoader;
public class BsImageLoader extends ImageLoader{
private static BsImageLoader sLoader;
public static BsImageLoader getLoader() {
if(null == sLoader) {
FileManager fm = FileManager.getInstance();
sLoader = new BsImageLoader(fm);
}
return sLoader;
}
protected BsImageLoader(IUrlLocalFilePathCreator creator) {
super(creator);
}
}
|
zzdache
|
trunk/android/cc/Business/src/com/zz/cc/business/data/BsImageLoader.java
|
Java
|
epl
| 452
|
package com.zz.cc.business.view;
import com.zz.cc.business.R;
import com.zz.common.tools.WeakReferenceHandler;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Resources;
import android.os.Handler.Callback;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.TextView;
public class ActionSheet extends Dialog implements Callback {
private static final String TAG = "ActionSheet";
private Context mContext;
private LayoutInflater mInflater;
private Resources mResources;
private WeakReferenceHandler mHandler;
private TranslateAnimation animation;
/**
* actionsheet根View
*/
private ScrollView mRootView;
/**
* 下方actionview
*/
private LinearLayout mActionView;
/**
* 头部view
*/
private LinearLayout mTitleContainer;
/**
* 内容view
*/
private LinearLayout mContentContainer;
/**
* title部分View
*/
private LinearLayout mTitleView = null;
private int mButtonCount;
/**
* action Button选中时的监听器
*/
private OnButtonClickListener mOnButtonsListener = null;
private OnDismissListener mOnDismissListener = null;
public interface OnDismissListener {
public void onDismiss();
}
public interface OnButtonClickListener {
public void OnClick(View clickedView, int which);
}
public static ActionSheet create(Context context) {
final ActionSheet dialog = new ActionSheet(context);
dialog.getWindow().setWindowAnimations(R.style.MenuDialogAnimation);
return dialog;
}
/**
* 构造函数
* @param context
* @param checkMode 单选模式标识一个按钮被选定
*/
protected ActionSheet(Context context) {
super(context, R.style.MenuDialogStyle);
mContext = context;
mInflater = LayoutInflater.from(context);
mResources = context.getResources();
mHandler = new WeakReferenceHandler(Looper.getMainLooper(), this);
mRootView = (ScrollView) mInflater.inflate(R.layout.action_sheet_base, null);
mActionView = (LinearLayout) mRootView.findViewById(R.id.action_sheet_actionView);
mTitleContainer = (LinearLayout) mRootView.findViewById(R.id.action_sheet_titleContainer);
mContentContainer = (LinearLayout) mRootView
.findViewById(R.id.action_sheet_contentView);
super.setContentView(mRootView);
}
/**
* 对话框按钮点击事件监听
*/
private View.OnClickListener mHandleBtnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
int id = v.getId();
/**
* 回调click事件
*/
if (mOnButtonsListener != null) {
mOnButtonsListener.OnClick(v, id);
}
}
};
/**
* 默认的关闭对话框监听器
*/
private View.OnClickListener mHandleDismissListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
if (mOnDismissListener != null) {
mOnDismissListener.onDismiss();
}
}
};
public void setOnButtonClickListener(OnButtonClickListener l) {
mOnButtonsListener = l;
}
public void setOnDismissListener(OnDismissListener lis) {
mOnDismissListener = lis;
}
/**
* 原Dialog方法,已无作用
*
* @deprecated
*/
@Override
public void setContentView(View view) {
throw new UnsupportedOperationException("this method is not support");
}
@Override
public void setContentView(int layoutResID) {
throw new UnsupportedOperationException("this method is not support");
}
@Override
public void setTitle(int resId) {
throw new UnsupportedOperationException("this method is not support");
}
@Override
public void setTitle(CharSequence title) {
throw new UnsupportedOperationException("this method is not support");
}
public void setMainTitle(int resid) {
CharSequence text = mResources.getText(resid);
setMainTitle(text);
}
public void setMainTitle(CharSequence text) {
if (text != null && text.length() != 0) {
if (mTitleView == null) {
mTitleView = (LinearLayout)mInflater.inflate(R.layout.action_sheet_title, null);
mTitleContainer.addView(mTitleView, new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
}
TextView tilteView = (TextView)mTitleView.findViewById(R.id.action_sheet_title);
tilteView.setVisibility(View.VISIBLE);
tilteView.setText(text);
}
}
public void setSecondaryTitle(int resid) {
CharSequence text = mResources.getText(resid);
setSecondaryTitle(text);
}
public void setSecondaryTitle(CharSequence text) {
if (text != null && text.length() != 0) {
if (mTitleView == null) {
mTitleView = (LinearLayout)mInflater.inflate(R.layout.action_sheet_title, null);
mTitleContainer.addView(mTitleView, new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
}
TextView tilteView = (TextView)mTitleView.findViewById(R.id.action_sheet_secondary_title);
tilteView.setVisibility(View.VISIBLE);
tilteView.setText(text);
}
}
public void addButton(int id) {
CharSequence text = mResources.getText(id);
addButton(text);
}
public void addButton(CharSequence text) {
View btnView = mInflater.inflate(R.layout.action_sheet_normal_button, null);
// 设置button文字和id
Button btn = (Button)btnView.findViewById(R.id.action_sheet_button);
btn.setText(text);
btn.setId(mButtonCount);
mContentContainer.addView(btnView, new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
btn.setOnClickListener(mHandleBtnClickListener);
mButtonCount++;
}
public void addCancelButton(int resid) {
CharSequence text = mResources.getText(resid);
addCancelButton(text);
}
public void addCancelButton(CharSequence text) {
View cancelView = mInflater.inflate(R.layout.action_sheet_cancel_button, null);
Button btnCancel = (Button)cancelView.findViewById(R.id.action_sheet_btnCancel);
btnCancel.setText(text);
btnCancel.setId(mButtonCount);
mContentContainer.addView(cancelView, new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
btnCancel.setOnClickListener(mHandleDismissListener);
mButtonCount++;
}
@Override
public void show() {
super.show();
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
/**
* 播放View动画从下升起
*/
animation = new TranslateAnimation(0, 0,
mActionView.getHeight(), 0);
animation.setFillEnabled(true);
animation.setInterpolator(AnimationUtils.loadInterpolator(
mContext, android.R.anim.decelerate_interpolator));
animation.setDuration(300);
mActionView.startAnimation(animation);
}
}, 0);
}
@Override
public void dismiss() {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
animation = new TranslateAnimation(0, 0, 0, mActionView.getHeight());
animation.setInterpolator(AnimationUtils.loadInterpolator(
mContext, android.R.anim.decelerate_interpolator));
animation.setDuration(200);
animation.setFillAfter(true);
mActionView.startAnimation(animation);
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationEnd(Animation animation) {
ActionSheet.super.dismiss();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationStart(Animation animation) {
}
});
}
}, 0);
}
public void superDismiss() {
try{
super.dismiss();
}catch(Exception e){
e = null;
}
}
@Override
public boolean handleMessage(Message msg) {
return true;
}
}
|
zzdache
|
trunk/android/cc/Business/src/com/zz/cc/business/view/ActionSheet.java
|
Java
|
epl
| 8,697
|
package com.zz.cc.business.app;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;
import com.zz.cc.business.R;
import com.zz.cc.business.R.id;
import com.zz.cc.business.R.layout;
import com.zz.common.app.BaseActivity;
public class BaseInfoActivity extends BaseActivity implements OnClickListener, OnCheckedChangeListener {
private static final int REQUEST_CODE_FOR_REGISTER = 100;
private EditText mUserNameInput;
private EditText mPasswordInput;
private EditText mEnsureInput;
private EditText mBusinessNameInput;
private EditText mAddressInput;
private EditText mPhoneNumInput;
private EditText mIdInput;
private Button mNext;
private RadioButton mTipsChecker;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base_info);
initUI();
fillView();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_CODE_FOR_REGISTER) {
finish();
overridePendingTransition(R.anim.activity_slide_left_in, R.anim.activity_slide_right_out);
}
}
private void initUI() {
mUserNameInput = (EditText) findViewById(R.id.login_input_user_name);
mPasswordInput = (EditText) findViewById(R.id.login_input_password);
mEnsureInput = (EditText) findViewById(R.id.login_input_ensure);
mBusinessNameInput = (EditText) findViewById(R.id.login_input_business_name);
mAddressInput = (EditText) findViewById(R.id.login_input_address);
mPhoneNumInput = (EditText) findViewById(R.id.login_input_phone_number);
mIdInput = (EditText) findViewById(R.id.login_input_id);
mNext = (Button) findViewById(R.id.register_next);
mTipsChecker = (RadioButton) findViewById(R.id.register_tips);
}
private void fillView() {
mNext.setOnClickListener(this);
mTipsChecker.setOnCheckedChangeListener(this);
}
private void gotoNext() {
Intent intent = new Intent(this, BusinessDetailActivity.class);
startActivityForResult(intent, REQUEST_CODE_FOR_REGISTER);
overridePendingTransition(R.anim.activity_slide_right_in, R.anim.activity_slide_left_out);
}
@Override //View.OnClickListener
public void onClick(View v) {
int id = v.getId();
if(id == R.id.register_next) {
gotoNext();
}
}
@Override //OnCheckChangedListener
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
}
|
zzdache
|
trunk/android/cc/Business/src/com/zz/cc/business/app/BaseInfoActivity.java
|
Java
|
epl
| 2,854
|
package com.zz.cc.business.app;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import com.zz.cc.business.R;
import com.zz.cc.business.R.anim;
import com.zz.cc.business.R.id;
import com.zz.cc.business.R.layout;
import com.zz.common.app.BaseActivity;
public class LoginActivity extends BaseActivity implements OnClickListener, OnCheckedChangeListener {
private static final int REQUEST_CODE_FOR_REGISTER = 9527;
private static final int REQUEST_CODE_FOR_FORGET_PASSWORD = 9528;
private EditText mUserNameInput;
private EditText mPasswordInput;
private Button mRegister;
private Button mLoginer;
private TextView mForgetPasswordInput;
private RadioButton mExplanationer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
initUI();
fillView();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_CODE_FOR_REGISTER) {
//TODO register
} else if(requestCode == REQUEST_CODE_FOR_FORGET_PASSWORD) {
//nothing
}
}
private void initUI() {
mUserNameInput = (EditText) findViewById(R.id.login_input_user_name);
mPasswordInput = (EditText) findViewById(R.id.login_input_password);
mRegister = (Button) findViewById(R.id.login_register);
mLoginer = (Button) findViewById(R.id.login_login);
mForgetPasswordInput = (TextView) findViewById(R.id.login_forget_password);
mExplanationer = (RadioButton) findViewById(R.id.login_explanation);
}
private void fillView() {
mRegister.setOnClickListener(this);
mLoginer.setOnClickListener(this);
mForgetPasswordInput.setOnClickListener(this);
mExplanationer.setOnCheckedChangeListener(this);
}
private void gotoMainActivity() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.activity_slide_right_in, R.anim.activity_slide_left_out);
}
private void gotoRegisterActivity() {
Intent intent = new Intent(this, BaseInfoActivity.class);
startActivityForResult(intent, REQUEST_CODE_FOR_REGISTER);
overridePendingTransition(R.anim.activity_slide_right_in, R.anim.activity_slide_left_out);
}
private void gotoForgetPasswordActivity() {
Intent intent = new Intent(this, ForgetPasswordActivity.class);
startActivityForResult(intent, REQUEST_CODE_FOR_FORGET_PASSWORD);
overridePendingTransition(R.anim.activity_slide_right_in, R.anim.activity_slide_left_out);
}
@Override //View.OnClickListener
public void onClick(View view) {
switch(view.getId()) {
case R.id.login_login:
//TODO login
gotoMainActivity();
break;
case R.id.login_register:
gotoRegisterActivity();
break;
case R.id.login_forget_password:
gotoForgetPasswordActivity();
break;
default:
break;
}
}
@Override //OnCheckChangedListener
public void onCheckedChanged(CompoundButton button, boolean check) {
}
}
|
zzdache
|
trunk/android/cc/Business/src/com/zz/cc/business/app/LoginActivity.java
|
Java
|
epl
| 3,461
|
package com.zz.cc.business.app;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler.Callback;
import android.os.Message;
import com.zz.cc.business.R;
import com.zz.cc.business.R.anim;
import com.zz.cc.business.R.layout;
import com.zz.common.app.BaseActivity;
import com.zz.common.tools.WeakReferenceHandler;
public class StartUpActivity extends BaseActivity implements Callback {
private static final int ACTION_START_UP_FINISH = 100;
private static final int PERIOD_START_UP = 1000;
private WeakReferenceHandler mHandler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new WeakReferenceHandler(this);
setContentView(R.layout.activity_start_up);
mHandler.sendEmptyMessageDelayed(ACTION_START_UP_FINISH, PERIOD_START_UP);
}
@Override
public void onDestroy() {
super.onDestroy();
mHandler.removeMessages(ACTION_START_UP_FINISH);
}
@Override
public boolean handleMessage(Message msg) {
if(msg.what == ACTION_START_UP_FINISH) {
startNextActivity();
}
return true;
}
private void startNextActivity() {
Intent intent = new Intent(this, UserGuideActivity.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.activity_slide_right_in, R.anim.activity_slide_left_out);
}
}
|
zzdache
|
trunk/android/cc/Business/src/com/zz/cc/business/app/StartUpActivity.java
|
Java
|
epl
| 1,383
|
package com.zz.cc.business.app;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.zxing.client.android.encode.QRCodeEncoder;
import com.zz.cc.business.R;
import com.zz.cc.business.data.FileManager;
import com.zz.common.app.BaseActivity;
public class QrCodeActivity extends BaseActivity {
public static final String INDEX_QR_CODE = "index_qr_code";
private String mQrCode;
private ImageView mQrCodeView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
getArgumentsFromIntent(intent);
setContentView(R.layout.activity_qrcode);
initUI();
fillView();
}
private void initUI() {
mQrCodeView = (ImageView) findViewById(R.id.qrcode_image);
}
private void fillView() {
try {
String filePath = FileManager.getInstance().getQrCodePath();
Bitmap b = QRCodeEncoder.encode(mQrCode, filePath);
mQrCodeView.setImageDrawable(new BitmapDrawable(b));
} catch(Throwable t) {
Toast.makeText(this, "生成二维码失败!", Toast.LENGTH_SHORT).show();
}
}
private void getArgumentsFromIntent(Intent intent) {
mQrCode = intent.getStringExtra(INDEX_QR_CODE);
}
}
|
zzdache
|
trunk/android/cc/Business/src/com/zz/cc/business/app/QrCodeActivity.java
|
Java
|
epl
| 1,406
|
package com.zz.cc.business.app;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.zz.cc.business.R;
import com.zz.cc.business.data.ServiceInfo;
import com.zz.common.app.BaseActivity;
import com.zz.common.app.BaseApplication;
import com.zz.common.widget.ZListView;
public class ReserveListActivity extends BaseActivity {
private ZListView mListView;
private ReserveAdapter mAdapter;
private final List<ServiceInfo> mServices = new ArrayList<ServiceInfo>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reserve_list);
initUI();
fillView();
refresh();
}
private void initUI() {
mListView = (ZListView) findViewById(R.id.reserve_list_view);
}
private void fillView() {
mAdapter = new ReserveAdapter();
mListView.setAdapter(mAdapter);
}
private void refresh() {
mServices.clear();
mServices.addAll(ServiceInfo.generateServiceInfoList());
mAdapter.notifyDataSetChanged();
}
private static class ViewHolder {
public TextView mTvUserName;
public TextView mTvCarNumber;
public TextView mTvPhoneNumber;
public TextView mTvTime;
public TextView mTvCost;
}
private class ReserveAdapter extends BaseAdapter {
@Override
public int getCount() {
return mServices.size();
}
@Override
public Object getItem(int position) {
return mServices.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(null == convertView) {
convertView = LayoutInflater.from(ReserveListActivity.this).inflate(R.layout.list_item_reserve, null);
holder = new ViewHolder();
holder.mTvUserName = (TextView) convertView.findViewById(R.id.reserve_user_name);
holder.mTvCarNumber = (TextView) convertView.findViewById(R.id.reserve_car_number);
holder.mTvPhoneNumber = (TextView) convertView.findViewById(R.id.reserve_phone_number);
holder.mTvTime = (TextView) convertView.findViewById(R.id.reserve_time);
holder.mTvCost = (TextView) convertView.findViewById(R.id.reserve_cost);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ServiceInfo s = mServices.get(position);
holder.mTvUserName.setText(s.mUserName);
holder.mTvCarNumber.setText(s.mCarNum);
holder.mTvPhoneNumber.setText(s.mPhoneNum);
holder.mTvTime.setText(s.mServiceTime);
holder.mTvCost.setText(s.mCost);
return convertView;
}
}
}
|
zzdache
|
trunk/android/cc/Business/src/com/zz/cc/business/app/ReserveListActivity.java
|
Java
|
epl
| 2,879
|
package com.zz.cc.business.app;
import com.zz.common.app.BaseActivity;
public class RegisterActivity extends BaseActivity {
}
|
zzdache
|
trunk/android/cc/Business/src/com/zz/cc/business/app/RegisterActivity.java
|
Java
|
epl
| 136
|
package com.zz.cc.business.app;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.zz.cc.business.R;
import com.zz.cc.business.R.anim;
import com.zz.cc.business.R.id;
import com.zz.cc.business.R.layout;
import com.zz.common.app.BaseActivity;
public class ForgetPasswordActivity extends BaseActivity implements OnClickListener {
private EditText mPhoneNumberInput;
private Button mSubmiter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forget_password);
initUI();
fillView();
}
private void initUI() {
mPhoneNumberInput = (EditText) findViewById(R.id.login_input_phone_number);
mSubmiter = (Button) findViewById(R.id.submit);;
}
private void fillView() {
mSubmiter.setOnClickListener(this);
}
@Override //View.OnClickListener
public void onClick(View v) {
int id = v.getId();
if(id == R.id.submit) {
finish();
overridePendingTransition(R.anim.activity_slide_left_in, R.anim.activity_slide_right_out);
}
}
}
|
zzdache
|
trunk/android/cc/Business/src/com/zz/cc/business/app/ForgetPasswordActivity.java
|
Java
|
epl
| 1,208
|
package com.zz.cc.business.app;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.zz.cc.business.R;
import com.zz.cc.business.data.ServiceInfo;
import com.zz.common.app.BaseActivity;
import com.zz.common.widget.ZListView;
public class ServiceListActivity extends BaseActivity {
private ZListView mListView;
private ServiceAdapter mAdapter;
private final List<ServiceInfo> mServices = new ArrayList<ServiceInfo>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service_list);
initUI();
fillView();
refresh();
}
private void initUI() {
mListView = (ZListView) findViewById(R.id.service_list_view);
}
private void fillView() {
mAdapter = new ServiceAdapter();
mListView.setAdapter(mAdapter);
}
private void refresh() {
mServices.clear();
mServices.addAll(ServiceInfo.generateServiceInfoList());
mAdapter.notifyDataSetChanged();
}
private static class ViewHolder {
public TextView mTvSummary;
}
private class ServiceAdapter extends BaseAdapter {
@Override
public int getCount() {
return mServices.size();
}
@Override
public Object getItem(int position) {
return mServices.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(null == convertView) {
convertView = LayoutInflater.from(ServiceListActivity.this).inflate(R.layout.list_item_service, null);
holder = new ViewHolder();
holder.mTvSummary = (TextView) convertView.findViewById(R.id.service_summary);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ServiceInfo s = mServices.get(position);
String summary = String.format(getString(R.string.service_summary)
, s.mPhoneNum, s.mCarNum, s.mServiceCount);
holder.mTvSummary.setText(summary);
return convertView;
}
}
}
|
zzdache
|
trunk/android/cc/Business/src/com/zz/cc/business/app/ServiceListActivity.java
|
Java
|
epl
| 2,310
|
package com.zz.cc.business.app;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.zz.cc.business.R;
import com.zz.common.app.BaseActivity;
import com.zz.common.widget.ZListView;
public class OtherActivity extends BaseActivity implements OnItemClickListener{
private ZListView mListView;
private SettingAdapter mAdapter;
private final List<Integer> mSettingsId = new ArrayList<Integer>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_other);
initUI();
fillView();
refresh();
}
private void initUI() {
mListView = (ZListView) findViewById(R.id.settings_list_view);
}
private void fillView() {
mAdapter = new SettingAdapter();
mListView.setAdapter(mAdapter);
}
private void refresh() {
mSettingsId.clear();
mSettingsId.add(R.string.settings_modify_business_detail);
mSettingsId.add(R.string.settings_query_bill);
mSettingsId.add(R.string.settings_publish_info);
mSettingsId.add(R.string.settings_modify_base_info);
mAdapter.notifyDataSetChanged();
}
@Override //AdapterView.OnItemClickListener
public void onItemClick(AdapterView<?> parent, View convertView, int position, long id) {
ViewHolder holder = (ViewHolder) convertView.getTag();
if(null != holder) {
switch(holder.mRId) {
case R.string.settings_modify_business_detail:
//TODO
break;
case R.string.settings_query_bill:
//TODO
break;
case R.string.settings_publish_info:
//TODO
break;
case R.string.settings_modify_base_info:
//TODO
break;
default:
break;
}
}
}
private static class ViewHolder {
public TextView mTvSetting;
public int mRId;
}
private class SettingAdapter extends BaseAdapter {
@Override
public int getCount() {
return mSettingsId.size();
}
@Override
public Object getItem(int position) {
return mSettingsId.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(null == convertView) {
convertView = LayoutInflater.from(OtherActivity.this).inflate(R.layout.list_item_settings, null);
holder = new ViewHolder();
holder.mTvSetting = (TextView) convertView.findViewById(R.id.setting);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.mRId = mSettingsId.get(position);
holder.mTvSetting.setText(holder.mRId);
return convertView;
}
}
}
|
zzdache
|
trunk/android/cc/Business/src/com/zz/cc/business/app/OtherActivity.java
|
Java
|
epl
| 3,012
|
package com.zz.cc.business.app;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler.Callback;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import com.zz.cc.business.R;
import com.zz.cc.business.data.BsImageLoader;
import com.zz.cc.business.data.FileManager;
import com.zz.cc.business.data.ServiceType;
import com.zz.cc.business.view.ActionSheet;
import com.zz.cc.business.view.ActionSheet.OnButtonClickListener;
import com.zz.common.app.BaseActivity;
import com.zz.common.tools.ImageLoader;
import com.zz.common.tools.ImageLoader.IconFlinger;
import com.zz.common.tools.ImageLoader.IconToken;
import com.zz.common.tools.WeakReferenceHandler;
import com.zz.common.utils.ImageUtil;
import com.zz.common.utils.ZLog;
import com.zz.common.widget.ZFixedGridView;
public class BusinessDetailActivity extends BaseActivity implements OnClickListener, Callback {
private static final String TAG = "BusinessDetailActivity";
private static final int REQUEST_CODE_FOR_TAKE_PICTURE = 10000;
private static final int REQUEST_CODE_FOR_SELECT_LOCAL_PICTURE = REQUEST_CODE_FOR_TAKE_PICTURE + 1;
private Button mSubmit;
private ZFixedGridView mServiceTypesGridView;
private Button mSelectPicturesBtn;
private ZFixedGridView mIconsGridView;
private WeakReferenceHandler mHandler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business_detail);
mHandler = new WeakReferenceHandler(this);
initUI();
fillView();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE_FOR_TAKE_PICTURE) {
onTaskPicture(resultCode, data);
} else if(requestCode == REQUEST_CODE_FOR_SELECT_LOCAL_PICTURE) {
onSelectLocalPicture(resultCode, data);
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
private void initUI() {
mSubmit = (Button) findViewById(R.id.detail_submit);
mServiceTypesGridView = (ZFixedGridView) findViewById(R.id.detail_services_grid_view);
mSelectPicturesBtn = (Button) findViewById(R.id.detail_button_select_pictures);
mIconsGridView = (ZFixedGridView) findViewById(R.id.detail_pictures_grid_view);
}
private void fillView() {
mSubmit.setOnClickListener(this);
mServiceTypesGridView.setColNom(2);
mServiceTypesGridView.setCellHeightByDip(30);
ServiceType []types = ServiceType.getAllServiceTypes();
for(ServiceType type: types) {
CheckBox box = new CheckBox(mServiceTypesGridView.getContext());
box.setText(type.mTypeName);
box.setChecked(true);
box.setTextColor(Color.RED);
mServiceTypesGridView.addView(box);
}
mSelectPicturesBtn.setOnClickListener(this);
mIconsGridView.setColNom(2);
mIconsGridView.setCellHeightByDip(100);
}
@Override //View.OnClickListener
public void onClick(View v) {
int id = v.getId();
if(id == R.id.detail_submit) {
finish();
overridePendingTransition(R.anim.activity_slide_left_in, R.anim.activity_slide_right_out);
} else if(id == R.id.detail_button_select_pictures) {
final ActionSheet as = ActionSheet.create(this);
as.addButton("拍照");
as.addButton("本地相册");
as.addCancelButton("取消");
as.setOnButtonClickListener(new OnButtonClickListener() {
@Override
public void OnClick(View clickedView, int which) {
if(0 == which) {
takePicture();
} else {
selectLocalPicture();
}
as.dismiss();
}
});
as.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface di) {}
});
try {
as.show();
} catch(Exception e) {
e = null;
}
}
}
private void takePicture() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(intent, REQUEST_CODE_FOR_TAKE_PICTURE);
}
private void onTaskPicture(int resultCode, Intent data) {
if(resultCode != Activity.RESULT_OK || null == data) {
return;
}
Bundle bundle = data.getExtras();
Bitmap bitmap = (Bitmap)bundle.get("data");
FileManager fm = FileManager.getInstance();
String filePath = fm.getWorkDir() + System.currentTimeMillis() + ".jpg";
File file = new File(filePath);
try {
ImageUtil.saveBitmapFileAsJPEG(bitmap, file);
handleNewPicture(filePath);
} catch (IOException e) {
e = null;
}
}
private void selectLocalPicture() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "选择图片"), REQUEST_CODE_FOR_SELECT_LOCAL_PICTURE);
}
private void onSelectLocalPicture(int resultCode, Intent data) {
if(resultCode != Activity.RESULT_OK || null == data) {
return;
}
Uri uri = data.getData();
String [] proj={MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery( uri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(column_index);
// cursor.close();
handleNewPicture(path);
}
private void handleNewPicture(String path) {
ZLog.d(TAG, "handleNewPicture: " + path);
BsImageLoader.getLoader().loadIcon(path, mHandler, null);
}
private void onNewPicture(IconFlinger flinger) {
if(null != flinger.mIcon) {
ImageView imageView = new ImageView(mIconsGridView.getContext());
imageView.setImageBitmap(flinger.mIcon);
mIconsGridView.addView(imageView);
}
}
@Override
public boolean handleMessage(Message msg) {
switch(msg.what) {
case ImageLoader.ACTION_IMAGE_LOADER:
IconFlinger flinger = (IconFlinger) msg.obj;
onNewPicture(flinger);
break;
default:
break;
}
return false;
}
}
|
zzdache
|
trunk/android/cc/Business/src/com/zz/cc/business/app/BusinessDetailActivity.java
|
Java
|
epl
| 6,913
|
package com.zz.cc.business.app;
import java.io.InputStream;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ViewFlipper;
import com.zz.cc.business.R;
import com.zz.cc.business.R.anim;
import com.zz.cc.business.R.id;
import com.zz.cc.business.R.layout;
import com.zz.common.app.BaseActivity;
import com.zz.common.utils.DeviceUtil;
import com.zz.common.utils.ImageUtil;
import com.zz.common.utils.ZLog;
public class UserGuideActivity extends BaseActivity
implements OnClickListener, OnTouchListener, GestureDetector.OnGestureListener {
private static final String TAG = "UserGuideActivity";
private ViewFlipper mViewFlipper;
private Button mDirectionView;
private int mScreenWidth;
private int mScreenHeight;
private GestureDetector mDetetor;
private int mCurrentIndex;
private String []mGuides = new String[] {
"guide/guide00.jpg",
"guide/guide01.jpg",
"guide/guide02.jpg"
};
@Override
public final void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mScreenHeight = DeviceUtil.getScreenHeight(this);
mScreenWidth = DeviceUtil.getScreenWidth(this);
setContentView(R.layout.activity_user_guide);
initUI();
initGuides();
}
private void initUI() {
mViewFlipper = (ViewFlipper) findViewById(R.id.guide_image_container);
mDirectionView = (Button) findViewById(R.id.guide_redirect);
mDirectionView.setOnClickListener(this);
mViewFlipper.setInAnimation(getInAnimation());
mViewFlipper.setOutAnimation(getOutAnimation());
mViewFlipper.setOnTouchListener(this);
mDetetor = new GestureDetector(this, this);
}
private void initGuides() {
AssetManager am = getAssets();
for(String path: mGuides) {
InputStream is = null;
try {
is = am.open(path);
Bitmap b = ImageUtil.decodeStream(is);
mViewFlipper.addView(makeView(b));
} catch (Throwable t) {
t = null;
} finally {
if(null != is) {
try {
is.close();
} catch(Exception e) {
e = null;
}
}
}
}
}
private View makeView(Bitmap b) {
ImageView imageView = new ImageView(this);
imageView.setLayoutParams(new LayoutParams(mScreenWidth, mScreenHeight));
imageView.setImageBitmap(b);
imageView.setScaleType(ScaleType.FIT_XY);
imageView.setClickable(false);
imageView.setEnabled(false);
return imageView;
}
@Override //View.OnClickListener
public void onClick(View view) {
int id = view.getId();
if(id == R.id.guide_redirect) {
if(mViewFlipper.isFlipping()) {
return;
}
if(mCurrentIndex == mGuides.length - 1) {
//the last guide image
onEndOfGuide();
} else {
showNextGuide();
}
}
}
@Override //View.OnTouchListener
public boolean onTouch(View v, MotionEvent event) {
mDetetor.onTouchEvent(event);
return true;
}
@Override //GestureDetector.OnGestureListener
public boolean onDown(MotionEvent e) {
return false;
}
@Override //GestureDetector.OnGestureListener
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
if(mViewFlipper.isFlipping()){
return false;
}
if(Math.abs((e1.getY() - e2.getY())) < 30){
return false;
}
if((e1.getY() - e2.getY()) > 30){
if(mCurrentIndex == (mGuides.length - 1)){
onEndOfGuide();
} else {
showNextGuide();
}
}else if((e1.getY()-e2.getY())<-30){
if(mCurrentIndex == 0){
return false;
} else {
showPreGuide();
}
}
return true;
}
@Override //GestureDetector.OnGestureListener
public void onLongPress(MotionEvent e) {
}
@Override //GestureDetector.OnGestureListener
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
return false;
}
@Override //GestureDetector.OnGestureListener
public void onShowPress(MotionEvent e) {
}
@Override //GestureDetector.OnGestureListener
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
private void showNextGuide() {
mViewFlipper.setInAnimation(getInAnimation());
mViewFlipper.setOutAnimation(getOutAnimation());
mViewFlipper.showNext();
mCurrentIndex ++;
}
private void showPreGuide() {
mViewFlipper.setInAnimation(getPrivousInAnimation());
mViewFlipper.setOutAnimation(getPrivousOutAnimation());
mViewFlipper.showPrevious();
mCurrentIndex --;
}
private void onEndOfGuide() {
ZLog.d(TAG, "onEndOfGuide");
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.activity_slide_right_in, R.anim.activity_slide_left_out);
}
private Animation getInAnimation() {
Animation animation = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 1, Animation.RELATIVE_TO_SELF, 0,
Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0);
animation.setDuration(250);
return animation;
}
private Animation getOutAnimation() {
Animation animation = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1,
Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0);
animation.setDuration(250);
return animation;
}
private Animation getPrivousInAnimation() {
Animation animation = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, -1, Animation.RELATIVE_TO_SELF, 0,
Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0);
animation.setDuration(250);
return animation;
}
private Animation getPrivousOutAnimation() {
Animation animation = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1,
Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0);
animation.setDuration(250);
return animation;
}
}
|
zzdache
|
trunk/android/cc/Business/src/com/zz/cc/business/app/UserGuideActivity.java
|
Java
|
epl
| 6,427
|
package com.zz.cc.business.app;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import com.zz.cc.business.R;
import com.zz.common.app.BaseActivity;
import com.zz.common.widget.ZListView;
public class MainActivity extends BaseActivity implements OnClickListener, OnItemClickListener {
private EditText mInputPublish;
private ZListView mListView;
private PublishAdapter mAdapter;
private Button mReserve;
private Button mService;
private Button mOther;
private Button mQrCode;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
fillView();
}
private void initUI() {
mInputPublish = (EditText) findViewById(R.id.main_publish_info);
mListView = (ZListView) findViewById(R.id.main_info_list);
View buttonGroup = findViewById(R.id.main_button_group);
mReserve = (Button) buttonGroup.findViewById(R.id.main_button_reserve);
mService = (Button) buttonGroup.findViewById(R.id.main_button_service);
mOther = (Button) buttonGroup.findViewById(R.id.main_button_other);
mQrCode = (Button) buttonGroup.findViewById(R.id.main_button_qrcode);
}
private void fillView() {
mAdapter = new PublishAdapter();
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(this);
mReserve.setOnClickListener(this);
mService.setOnClickListener(this);
mOther.setOnClickListener(this);
mQrCode.setOnClickListener(this);
}
private void gotoReserveListActivity() {
Intent intent = new Intent(this, ReserveListActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.activity_slide_right_in, R.anim.activity_slide_left_out);
}
private void gotoServiceListActivity() {
Intent intent = new Intent(this, ServiceListActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.activity_slide_right_in, R.anim.activity_slide_left_out);
}
private void gotoOtherActivity() {
Intent intent = new Intent(this, OtherActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.activity_slide_right_in, R.anim.activity_slide_left_out);
}
private void gotoQrCodeActivity() {
Intent intent = new Intent(this, QrCodeActivity.class);
intent.putExtra(QrCodeActivity.INDEX_QR_CODE, "http://www.google.com.tw");
startActivity(intent);
overridePendingTransition(R.anim.activity_slide_right_in, R.anim.activity_slide_left_out);
}
@Override //View.OnClickListener
public void onClick(View v) {
switch(v.getId()) {
case R.id.main_button_reserve:
gotoReserveListActivity();
break;
case R.id.main_button_service:
gotoServiceListActivity();
break;
case R.id.main_button_other:
gotoOtherActivity();
break;
case R.id.main_button_qrcode:
gotoQrCodeActivity();
break;
default:
break;
}
}
@Override //AdapterView.OnItemClickListener
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
private class PublishAdapter extends BaseAdapter {
@Override
public int getCount() {
// TODO
return 0;
}
@Override
public Object getItem(int position) {
// TODO
return null;
}
@Override
public long getItemId(int position) {
// TODO
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//TODO
return null;
}
}
}
|
zzdache
|
trunk/android/cc/Business/src/com/zz/cc/business/app/MainActivity.java
|
Java
|
epl
| 3,831
|
package com.zz.cc.business;
import com.zz.cc.business.data.FileManager;
import com.zz.common.app.BaseApplication;
public class BusinessApplication extends BaseApplication {
@Override
public void onCreate() {
sCrashPath = FileManager.getInstance().getWorkDir();
super.onCreate();
}
}
|
zzdache
|
trunk/android/cc/Business/src/com/zz/cc/business/BusinessApplication.java
|
Java
|
epl
| 306
|
/*
* Copyright 2007 ZXing authors
*
* 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 com.google.zxing;
/**
* Enumerates barcode formats known to this package. Please keep alphabetized.
*
* @author Sean Owen
*/
public enum BarcodeFormat {
/** Aztec 2D barcode format. */
AZTEC,
/** CODABAR 1D format. */
CODABAR,
/** Code 39 1D format. */
CODE_39,
/** Code 93 1D format. */
CODE_93,
/** Code 128 1D format. */
CODE_128,
/** Data Matrix 2D barcode format. */
DATA_MATRIX,
/** EAN-8 1D format. */
EAN_8,
/** EAN-13 1D format. */
EAN_13,
/** ITF (Interleaved Two of Five) 1D format. */
ITF,
/** MaxiCode 2D barcode format. */
MAXICODE,
/** PDF417 format. */
PDF_417,
/** QR Code 2D barcode format. */
QR_CODE,
/** RSS 14 */
RSS_14,
/** RSS EXPANDED */
RSS_EXPANDED,
/** UPC-A 1D format. */
UPC_A,
/** UPC-E 1D format. */
UPC_E,
/** UPC/EAN extension format. Not a stand-alone format. */
UPC_EAN_EXTENSION
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/BarcodeFormat.java
|
Java
|
epl
| 1,516
|
/*
* Copyright (C) 2012 ZXing authors
*
* 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 com.google.zxing.client.android;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.preference.PreferenceManager;
import com.google.zxing.client.android.camera.CameraManager;
import com.google.zxing.client.android.camera.FrontLightMode;
/**
* Detects ambient light and switches on the front light when very dark, and off again when sufficiently light.
*
* @author Sean Owen
* @author Nikolaus Huber
*/
@SuppressLint("NewApi")
public final class AmbientLightManager implements SensorEventListener {
private static final float TOO_DARK_LUX = 45.0f;
private static final float BRIGHT_ENOUGH_LUX = 450.0f;
private final Context context;
private CameraManager cameraManager;
private Sensor lightSensor;
public AmbientLightManager(Context context) {
this.context = context;
}
public void start(CameraManager cameraManager) {
this.cameraManager = cameraManager;
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
SensorManager sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if (lightSensor != null) {
sensorManager.registerListener(this, lightSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
}
public void stop() {
if (lightSensor != null) {
SensorManager sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
sensorManager.unregisterListener(this);
cameraManager = null;
lightSensor = null;
}
}
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
float ambientLightLux = sensorEvent.values[0];
if (cameraManager != null) {
if (ambientLightLux <= TOO_DARK_LUX) {
cameraManager.setTorch(true);
} else if (ambientLightLux >= BRIGHT_ENOUGH_LUX) {
cameraManager.setTorch(false);
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// do nothing
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/AmbientLightManager.java
|
Java
|
epl
| 2,845
|
/*
* Copyright (C) 2010 ZXing authors
*
* 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 com.google.zxing.client.android;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.BatteryManager;
import android.util.Log;
import com.google.zxing.client.android.common.executor.AsyncTaskExecInterface;
import com.google.zxing.client.android.common.executor.AsyncTaskExecManager;
/**
* Finishes an activity after a period of inactivity if the device is on battery power.
*/
@SuppressLint("NewApi")
public final class InactivityTimer {
private static final String TAG = InactivityTimer.class.getSimpleName();
private static final long INACTIVITY_DELAY_MS = 5 * 60 * 1000L;
private final Activity activity;
private final AsyncTaskExecInterface taskExec;
private final BroadcastReceiver powerStatusReceiver;
private InactivityAsyncTask inactivityTask;
public InactivityTimer(Activity activity) {
this.activity = activity;
taskExec = new AsyncTaskExecManager().build();
powerStatusReceiver = new PowerStatusReceiver();
onActivity();
}
public synchronized void onActivity() {
cancel();
inactivityTask = new InactivityAsyncTask();
taskExec.execute(inactivityTask);
}
public void onPause() {
cancel();
activity.unregisterReceiver(powerStatusReceiver);
}
public void onResume(){
activity.registerReceiver(powerStatusReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
onActivity();
}
private synchronized void cancel() {
AsyncTask<?,?,?> task = inactivityTask;
if (task != null) {
task.cancel(true);
inactivityTask = null;
}
}
public void shutdown() {
cancel();
}
private final class PowerStatusReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent){
if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
// 0 indicates that we're on battery
boolean onBatteryNow = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) <= 0;
if (onBatteryNow) {
InactivityTimer.this.onActivity();
} else {
InactivityTimer.this.cancel();
}
}
}
}
private final class InactivityAsyncTask extends AsyncTask<Object,Object,Object> {
@Override
protected Object doInBackground(Object... objects) {
try {
Thread.sleep(INACTIVITY_DELAY_MS);
Log.i(TAG, "Finishing activity due to inactivity");
activity.finish();
} catch (InterruptedException e) {
// continue without killing
}
return null;
}
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/InactivityTimer.java
|
Java
|
epl
| 3,329
|
/*
* Copyright (C) 2013 ZXing authors
*
* 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 com.google.zxing.client.android;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import com.google.zxing.DecodeHintType;
/**
* @author Lachezar Dobrev
*/
public final class DecodeHintManager {
private static final String TAG = DecodeHintManager.class.getSimpleName();
// This pattern is used in decoding integer arrays.
private static final Pattern COMMA = Pattern.compile(",");
private DecodeHintManager() {}
/**
* <p>Split a query string into a list of name-value pairs.</p>
*
* <p>This is an alternative to the {@link Uri#getQueryParameterNames()} and
* {@link Uri#getQueryParameters(String)}, which are quirky and not suitable
* for exist-only Uri parameters.</p>
*
* <p>This method ignores multiple parameters with the same name and returns the
* first one only. This is technically incorrect, but should be acceptable due
* to the method of processing Hints: no multiple values for a hint.</p>
*
* @param query query to split
* @return name-value pairs
*/
private static Map<String,String> splitQuery(String query) {
Map<String,String> map = new HashMap<String,String>();
int pos = 0;
while (pos < query.length()) {
if (query.charAt(pos) == '&') {
// Skip consecutive ampersand separators.
pos ++;
continue;
}
int amp = query.indexOf('&', pos);
int equ = query.indexOf('=', pos);
if (amp < 0) {
// This is the last element in the query, no more ampersand elements.
String name;
String text;
if (equ < 0) {
// No equal sign
name = query.substring(pos);
name = name.replace('+', ' '); // Preemptively decode +
name = Uri.decode(name);
text = "";
} else {
// Split name and text.
name = query.substring(pos, equ);
name = name.replace('+', ' '); // Preemptively decode +
name = Uri.decode(name);
text = query.substring(equ + 1);
text = text.replace('+', ' '); // Preemptively decode +
text = Uri.decode(text);
}
if (!map.containsKey(name)) {
map.put(name, text);
}
break;
}
if (equ < 0 || equ > amp) {
// No equal sign until the &: this is a simple parameter with no value.
String name = query.substring(pos, amp);
name = name.replace('+', ' '); // Preemptively decode +
name = Uri.decode(name);
if (!map.containsKey(name)) {
map.put(name, "");
}
pos = amp + 1;
continue;
}
String name = query.substring(pos, equ);
name = name.replace('+', ' '); // Preemptively decode +
name = Uri.decode(name);
String text = query.substring(equ+1, amp);
text = text.replace('+', ' '); // Preemptively decode +
text = Uri.decode(text);
if (!map.containsKey(name)) {
map.put(name, text);
}
pos = amp + 1;
}
return map;
}
public static Map<DecodeHintType,?> parseDecodeHints(Uri inputUri) {
String query = inputUri.getEncodedQuery();
if (query == null || query.length() == 0) {
return null;
}
// Extract parameters
Map<String, String> parameters = splitQuery(query);
Map<DecodeHintType, Object> hints = new EnumMap<DecodeHintType, Object>(DecodeHintType.class);
for (DecodeHintType hintType: DecodeHintType.values()) {
if (hintType == DecodeHintType.CHARACTER_SET ||
hintType == DecodeHintType.NEED_RESULT_POINT_CALLBACK ||
hintType == DecodeHintType.POSSIBLE_FORMATS) {
continue; // This hint is specified in another way
}
String parameterName = hintType.name();
String parameterText = parameters.get(parameterName);
if (parameterText == null) {
continue;
}
if (hintType.getValueType().equals(Object.class)) {
// This is an unspecified type of hint content. Use the value as is.
// TODO: Can we make a different assumption on this?
hints.put(hintType, parameterText);
continue;
}
if (hintType.getValueType().equals(Void.class)) {
// Void hints are just flags: use the constant specified by DecodeHintType
hints.put(hintType, Boolean.TRUE);
continue;
}
if (hintType.getValueType().equals(String.class)) {
// A string hint: use the decoded value.
hints.put(hintType, parameterText);
continue;
}
if (hintType.getValueType().equals(Boolean.class)) {
// A boolean hint: a few values for false, everything else is true.
// An empty parameter is simply a flag-style parameter, assuming true
if (parameterText.length() == 0) {
hints.put(hintType, Boolean.TRUE);
} else if ("0".equals(parameterText) ||
"false".equalsIgnoreCase(parameterText) ||
"no".equalsIgnoreCase(parameterText)) {
hints.put(hintType, Boolean.FALSE);
} else {
hints.put(hintType, Boolean.TRUE);
}
continue;
}
if (hintType.getValueType().equals(int[].class)) {
// An integer array. Used to specify valid lengths.
// Strip a trailing comma as in Java style array initialisers.
if (parameterText.length() > 0 && parameterText.charAt(parameterText.length() - 1) == ',') {
parameterText = parameterText.substring(0, parameterText.length() - 1);
}
String[] values = COMMA.split(parameterText);
int[] array = new int[values.length];
for (int i = 0; i < values.length; i++) {
try {
array[i] = Integer.parseInt(values[i]);
} catch (NumberFormatException ignored) {
Log.w(TAG, "Skipping array of integers hint " + hintType + " due to invalid numeric value: '" + values[i] + '\'');
array = null;
break;
}
}
if (array != null) {
hints.put(hintType, array);
}
continue;
}
Log.w(TAG, "Unsupported hint type '" + hintType + "' of type " + hintType.getValueType());
}
Log.i(TAG, "Hints from the URI: " + hints);
return hints;
}
public static Map<DecodeHintType, Object> parseDecodeHints(Intent intent) {
Bundle extras = intent.getExtras();
if (extras == null || extras.isEmpty()) {
return null;
}
Map<DecodeHintType,Object> hints = new EnumMap<DecodeHintType,Object>(DecodeHintType.class);
for (DecodeHintType hintType: DecodeHintType.values()) {
if (hintType == DecodeHintType.CHARACTER_SET ||
hintType == DecodeHintType.NEED_RESULT_POINT_CALLBACK ||
hintType == DecodeHintType.POSSIBLE_FORMATS) {
continue; // This hint is specified in another way
}
String hintName = hintType.name();
if (extras.containsKey(hintName)) {
if (hintType.getValueType().equals(Void.class)) {
// Void hints are just flags: use the constant specified by the DecodeHintType
hints.put(hintType, Boolean.TRUE);
} else {
Object hintData = extras.get(hintName);
if (hintType.getValueType().isInstance(hintData)) {
hints.put(hintType, hintData);
} else {
Log.w(TAG, "Ignoring hint " + hintType + " because it is not assignable from " + hintData);
}
}
}
}
Log.i(TAG, "Hints from the Intent: " + hints);
return hints;
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/DecodeHintManager.java
|
Java
|
epl
| 8,300
|
/*
* Copyright (C) 2010 ZXing authors
*
* 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 com.google.zxing.client.android;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;
import java.util.regex.Pattern;
import android.content.Intent;
import android.net.Uri;
import com.google.zxing.BarcodeFormat;
public final class DecodeFormatManager {
private static final Pattern COMMA_PATTERN = Pattern.compile(",");
public static final Collection<BarcodeFormat> PRODUCT_FORMATS;
public static final Collection<BarcodeFormat> ONE_D_FORMATS;
public static final Collection<BarcodeFormat> QR_CODE_FORMATS = EnumSet.of(BarcodeFormat.QR_CODE);
public static final Collection<BarcodeFormat> DATA_MATRIX_FORMATS = EnumSet.of(BarcodeFormat.DATA_MATRIX);
static {
PRODUCT_FORMATS = EnumSet.of(BarcodeFormat.UPC_A,
BarcodeFormat.UPC_E,
BarcodeFormat.EAN_13,
BarcodeFormat.EAN_8,
BarcodeFormat.RSS_14,
BarcodeFormat.RSS_EXPANDED);
ONE_D_FORMATS = EnumSet.of(BarcodeFormat.CODE_39,
BarcodeFormat.CODE_93,
BarcodeFormat.CODE_128,
BarcodeFormat.ITF,
BarcodeFormat.CODABAR);
ONE_D_FORMATS.addAll(PRODUCT_FORMATS);
}
private DecodeFormatManager() {}
public static Collection<BarcodeFormat> parseDecodeFormats(Intent intent) {
List<String> scanFormats = null;
String scanFormatsString = intent.getStringExtra(Intents.Scan.FORMATS);
if (scanFormatsString != null) {
scanFormats = Arrays.asList(COMMA_PATTERN.split(scanFormatsString));
}
return parseDecodeFormats(scanFormats, intent.getStringExtra(Intents.Scan.MODE));
}
public static Collection<BarcodeFormat> parseDecodeFormats(Uri inputUri) {
List<String> formats = inputUri.getQueryParameters(Intents.Scan.FORMATS);
if (formats != null && formats.size() == 1 && formats.get(0) != null){
formats = Arrays.asList(COMMA_PATTERN.split(formats.get(0)));
}
return parseDecodeFormats(formats, inputUri.getQueryParameter(Intents.Scan.MODE));
}
private static Collection<BarcodeFormat> parseDecodeFormats(Iterable<String> scanFormats,
String decodeMode) {
if (scanFormats != null) {
Collection<BarcodeFormat> formats = EnumSet.noneOf(BarcodeFormat.class);
try {
for (String format : scanFormats) {
formats.add(BarcodeFormat.valueOf(format));
}
return formats;
} catch (IllegalArgumentException iae) {
// ignore it then
}
}
if (decodeMode != null) {
if (Intents.Scan.PRODUCT_MODE.equals(decodeMode)) {
return PRODUCT_FORMATS;
}
if (Intents.Scan.QR_CODE_MODE.equals(decodeMode)) {
return QR_CODE_FORMATS;
}
if (Intents.Scan.DATA_MATRIX_MODE.equals(decodeMode)) {
return DATA_MATRIX_FORMATS;
}
if (Intents.Scan.ONE_D_MODE.equals(decodeMode)) {
return ONE_D_FORMATS;
}
}
return null;
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/DecodeFormatManager.java
|
Java
|
epl
| 3,791
|
/*
* Copyright (C) 2011 ZXing authors
*
* 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 com.google.zxing.client.android;
public enum IntentSource {
NATIVE_APP_INTENT,
PRODUCT_SEARCH_LINK,
ZXING_LINK,
NONE
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/IntentSource.java
|
Java
|
epl
| 741
|
/*
* Copyright (C) 2010 ZXing authors
*
* 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 com.google.zxing.client.android;
import android.app.Activity;
import android.content.DialogInterface;
/**
* Simple listener used to exit the app in a few cases.
*
* @author Sean Owen
*/
public final class FinishListener implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener {
private final Activity activityToFinish;
public FinishListener(Activity activityToFinish) {
this.activityToFinish = activityToFinish;
}
@Override
public void onCancel(DialogInterface dialogInterface) {
run();
}
@Override
public void onClick(DialogInterface dialogInterface, int i) {
run();
}
private void run() {
activityToFinish.finish();
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/FinishListener.java
|
Java
|
epl
| 1,304
|
/*
* Copyright (C) 2008 ZXing authors
*
* 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 com.google.zxing.client.android;
import com.google.zxing.ResultPoint;
import com.google.zxing.client.android.camera.CameraManager;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
/**
* This view is overlaid on top of the camera preview. It adds the viewfinder rectangle and partial
* transparency outside it, as well as the laser scanner animation and result points.
*
* @author dswitkin@google.com (Daniel Switkin)
*/
public final class ViewfinderView extends View {
private static final int[] SCANNER_ALPHA = {0, 64, 128, 192, 255, 192, 128, 64};
private static final long ANIMATION_DELAY = 80L;
private static final int CURRENT_POINT_OPACITY = 0xA0;
private static final int MAX_RESULT_POINTS = 20;
private static final int POINT_SIZE = 6;
private CameraManager cameraManager;
private final Paint paint;
private Bitmap resultBitmap;
private final int maskColor;
private final int resultColor;
private final int laserColor;
private final int resultPointColor;
private int scannerAlpha;
private List<ResultPoint> possibleResultPoints;
private List<ResultPoint> lastPossibleResultPoints;
// This constructor is used when the class is built from an XML resource.
public ViewfinderView(Context context, AttributeSet attrs) {
super(context, attrs);
// Initialize these once for performance rather than calling them every time in onDraw().
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
maskColor = 0x60000000;
resultColor = Color.GREEN;
laserColor = Color.RED;
resultPointColor = Color.YELLOW;
scannerAlpha = 0;
possibleResultPoints = new ArrayList<ResultPoint>(5);
lastPossibleResultPoints = null;
}
public void setCameraManager(CameraManager cameraManager) {
this.cameraManager = cameraManager;
}
@Override
public void onDraw(Canvas canvas) {
if (cameraManager == null) {
return; // not ready yet, early draw before done configuring
}
Rect frame = cameraManager.getFramingRect();
if (frame == null) {
return;
}
int width = canvas.getWidth();
int height = canvas.getHeight();
// Draw the exterior (i.e. outside the framing rect) darkened
paint.setColor(resultBitmap != null ? resultColor : maskColor);
canvas.drawRect(0, 0, width, frame.top, paint);
canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint);
canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1, paint);
canvas.drawRect(0, frame.bottom + 1, width, height, paint);
if (resultBitmap != null) {
// Draw the opaque result bitmap over the scanning rectangle
paint.setAlpha(CURRENT_POINT_OPACITY);
canvas.drawBitmap(resultBitmap, null, frame, paint);
} else {
// Draw a red "laser scanner" line through the middle to show decoding is active
paint.setColor(laserColor);
paint.setAlpha(SCANNER_ALPHA[scannerAlpha]);
scannerAlpha = (scannerAlpha + 1) % SCANNER_ALPHA.length;
int middle = frame.height() / 2 + frame.top;
canvas.drawRect(frame.left + 2, middle - 1, frame.right - 1, middle + 2, paint);
Rect previewFrame = cameraManager.getFramingRectInPreview();
float scaleX = frame.width() / (float) previewFrame.width();
float scaleY = frame.height() / (float) previewFrame.height();
List<ResultPoint> currentPossible = possibleResultPoints;
List<ResultPoint> currentLast = lastPossibleResultPoints;
int frameLeft = frame.left;
int frameTop = frame.top;
if (currentPossible.isEmpty()) {
lastPossibleResultPoints = null;
} else {
possibleResultPoints = new ArrayList<ResultPoint>(5);
lastPossibleResultPoints = currentPossible;
paint.setAlpha(CURRENT_POINT_OPACITY);
paint.setColor(resultPointColor);
synchronized (currentPossible) {
for (ResultPoint point : currentPossible) {
canvas.drawCircle(frameLeft + (int) (point.getX() * scaleX),
frameTop + (int) (point.getY() * scaleY),
POINT_SIZE, paint);
}
}
}
if (currentLast != null) {
paint.setAlpha(CURRENT_POINT_OPACITY / 2);
paint.setColor(resultPointColor);
synchronized (currentLast) {
float radius = POINT_SIZE / 2.0f;
for (ResultPoint point : currentLast) {
canvas.drawCircle(frameLeft + (int) (point.getX() * scaleX),
frameTop + (int) (point.getY() * scaleY),
radius, paint);
}
}
}
// Request another update at the animation interval, but only repaint the laser line,
// not the entire viewfinder mask.
postInvalidateDelayed(ANIMATION_DELAY,
frame.left - POINT_SIZE,
frame.top - POINT_SIZE,
frame.right + POINT_SIZE,
frame.bottom + POINT_SIZE);
}
}
public void drawViewfinder() {
Bitmap resultBitmap = this.resultBitmap;
this.resultBitmap = null;
if (resultBitmap != null) {
resultBitmap.recycle();
}
invalidate();
}
/**
* Draw a bitmap with the result points highlighted instead of the live scanning display.
*
* @param barcode An image of the decoded barcode.
*/
public void drawResultBitmap(Bitmap barcode) {
resultBitmap = barcode;
invalidate();
}
public void addPossibleResultPoint(ResultPoint point) {
List<ResultPoint> points = possibleResultPoints;
synchronized (points) {
points.add(point);
int size = points.size();
if (size > MAX_RESULT_POINTS) {
// trim it
points.subList(0, size - MAX_RESULT_POINTS / 2).clear();
}
}
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/ViewfinderView.java
|
Java
|
epl
| 6,714
|
/*
* Copyright (C) 2011 ZXing authors
*
* 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 com.google.zxing.client.android.encode;
import android.telephony.PhoneNumberUtils;
import java.util.regex.Pattern;
/**
* Encodes contact information according to the MECARD format.
*
* @author Sean Owen
*/
final class MECARDContactEncoder extends ContactEncoder {
private static final Pattern RESERVED_MECARD_CHARS = Pattern.compile("([\\\\:;])");
private static final Pattern NEWLINE = Pattern.compile("\\n");
private static final Pattern COMMA = Pattern.compile(",");
private static final Formatter MECARD_FIELD_FORMATTER = new Formatter() {
@Override
public String format(String source) {
return NEWLINE.matcher(RESERVED_MECARD_CHARS.matcher(source).replaceAll("\\\\$1")).replaceAll("");
}
};
private static final char TERMINATOR = ';';
private static final Pattern NOT_DIGITS = Pattern.compile("[^0-9]+");
@Override
public String[] encode(Iterable<String> names,
String organization,
Iterable<String> addresses,
Iterable<String> phones,
Iterable<String> emails,
Iterable<String> urls,
String note) {
StringBuilder newContents = new StringBuilder(100);
newContents.append("MECARD:");
StringBuilder newDisplayContents = new StringBuilder(100);
appendUpToUnique(newContents, newDisplayContents, "N", names, 1, new Formatter() {
@Override
public String format(String source) {
return source == null ? null : COMMA.matcher(source).replaceAll("");
}
});
append(newContents, newDisplayContents, "ORG", organization);
appendUpToUnique(newContents, newDisplayContents, "ADR", addresses, 1, null);
appendUpToUnique(newContents, newDisplayContents, "TEL", phones, Integer.MAX_VALUE, new Formatter() {
@Override
public String format(String source) {
return keepOnlyDigits(PhoneNumberUtils.formatNumber(source));
}
});
appendUpToUnique(newContents, newDisplayContents, "EMAIL", emails, Integer.MAX_VALUE, null);
appendUpToUnique(newContents, newDisplayContents, "URL", urls, Integer.MAX_VALUE, null);
append(newContents, newDisplayContents, "NOTE", note);
newContents.append(';');
return new String[] { newContents.toString(), newDisplayContents.toString() };
}
private static String keepOnlyDigits(CharSequence s) {
return s == null ? null : NOT_DIGITS.matcher(s).replaceAll("");
}
private static void append(StringBuilder newContents,
StringBuilder newDisplayContents,
String prefix,
String value) {
doAppend(newContents, newDisplayContents, prefix, value, MECARD_FIELD_FORMATTER, TERMINATOR);
}
private static void appendUpToUnique(StringBuilder newContents,
StringBuilder newDisplayContents,
String prefix,
Iterable<String> values,
int max,
Formatter formatter) {
doAppendUpToUnique(newContents,
newDisplayContents,
prefix,
values,
max,
formatter,
MECARD_FIELD_FORMATTER,
TERMINATOR);
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/encode/MECARDContactEncoder.java
|
Java
|
epl
| 4,082
|
/*
* Copyright (C) 2011 ZXing authors
*
* 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 com.google.zxing.client.android.encode;
/**
* Encapsulates some simple formatting logic, to aid refactoring in {@link ContactEncoder}.
*
* @author Sean Owen
*/
interface Formatter {
String format(String source);
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/encode/Formatter.java
|
Java
|
epl
| 838
|
/*
* Copyright (C) 2011 ZXing authors
*
* 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 com.google.zxing.client.android.encode;
import android.telephony.PhoneNumberUtils;
import java.util.regex.Pattern;
/**
* Encodes contact information according to the vCard format.
*
* @author Sean Owen
*/
final class VCardContactEncoder extends ContactEncoder {
private static final Pattern RESERVED_VCARD_CHARS = Pattern.compile("([\\\\,;])");
private static final Pattern NEWLINE = Pattern.compile("\\n");
private static final Formatter VCARD_FIELD_FORMATTER = new Formatter() {
@Override
public String format(String source) {
return NEWLINE.matcher(RESERVED_VCARD_CHARS.matcher(source).replaceAll("\\\\$1")).replaceAll("");
}
};
private static final char TERMINATOR = '\n';
@Override
public String[] encode(Iterable<String> names,
String organization,
Iterable<String> addresses,
Iterable<String> phones,
Iterable<String> emails,
Iterable<String> urls,
String note) {
StringBuilder newContents = new StringBuilder(100);
newContents.append("BEGIN:VCARD").append(TERMINATOR);
newContents.append("VERSION:3.0").append(TERMINATOR);
StringBuilder newDisplayContents = new StringBuilder(100);
appendUpToUnique(newContents, newDisplayContents, "N", names, 1, null);
append(newContents, newDisplayContents, "ORG", organization);
appendUpToUnique(newContents, newDisplayContents, "ADR", addresses, 1, null);
appendUpToUnique(newContents, newDisplayContents, "TEL", phones, Integer.MAX_VALUE, new Formatter() {
@Override
public String format(String source) {
return PhoneNumberUtils.formatNumber(source);
}
});
appendUpToUnique(newContents, newDisplayContents, "EMAIL", emails, Integer.MAX_VALUE, null);
appendUpToUnique(newContents, newDisplayContents, "URL", urls, Integer.MAX_VALUE, null);
append(newContents, newDisplayContents, "NOTE", note);
newContents.append("END:VCARD").append(TERMINATOR);
return new String[] { newContents.toString(), newDisplayContents.toString() };
}
private static void append(StringBuilder newContents,
StringBuilder newDisplayContents,
String prefix,
String value) {
doAppend(newContents, newDisplayContents, prefix, value, VCARD_FIELD_FORMATTER, TERMINATOR);
}
private static void appendUpToUnique(StringBuilder newContents,
StringBuilder newDisplayContents,
String prefix,
Iterable<String> values,
int max,
Formatter formatter) {
doAppendUpToUnique(newContents,
newDisplayContents,
prefix,
values,
max,
formatter,
VCARD_FIELD_FORMATTER,
TERMINATOR);
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/encode/VCardContactEncoder.java
|
Java
|
epl
| 3,739
|
/*
* Copyright (C) 2011 ZXing authors
*
* 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 com.google.zxing.client.android.encode;
import java.util.Collection;
import java.util.HashSet;
/**
* Implementations encode according to some scheme for encoding contact information, like VCard or
* MECARD.
*
* @author Sean Owen
*/
abstract class ContactEncoder {
/**
* @return first, the best effort encoding of all data in the appropriate format; second, a
* display-appropriate version of the contact information
*/
abstract String[] encode(Iterable<String> names,
String organization,
Iterable<String> addresses,
Iterable<String> phones,
Iterable<String> emails,
Iterable<String> urls,
String note);
/**
* @return null if s is null or empty, or result of s.trim() otherwise
*/
static String trim(String s) {
if (s == null) {
return null;
}
String result = s.trim();
return result.length() == 0 ? null : result;
}
static void doAppend(StringBuilder newContents,
StringBuilder newDisplayContents,
String prefix,
String value,
Formatter fieldFormatter,
char terminator) {
String trimmed = trim(value);
if (trimmed != null) {
newContents.append(prefix).append(':').append(fieldFormatter.format(trimmed)).append(terminator);
newDisplayContents.append(trimmed).append('\n');
}
}
static void doAppendUpToUnique(StringBuilder newContents,
StringBuilder newDisplayContents,
String prefix,
Iterable<String> values,
int max,
Formatter formatter,
Formatter fieldFormatter,
char terminator) {
if (values == null) {
return;
}
int count = 0;
Collection<String> uniques = new HashSet<String>(2);
for (String value : values) {
String trimmed = trim(value);
if (trimmed != null && trimmed.length() > 0 && !uniques.contains(trimmed)) {
newContents.append(prefix).append(':').append(fieldFormatter.format(trimmed)).append(terminator);
String display = formatter == null ? trimmed : formatter.format(trimmed);
newDisplayContents.append(display).append('\n');
if (++count == max) {
break;
}
uniques.add(trimmed);
}
}
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/encode/ContactEncoder.java
|
Java
|
epl
| 3,251
|
/*
* Copyright (C) 2008 ZXing authors
*
* 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 com.google.zxing.client.android.encode;
import android.provider.ContactsContract;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.android.Contents;
import com.google.zxing.client.android.Intents;
import com.google.zxing.client.result.AddressBookParsedResult;
import com.google.zxing.client.result.ParsedResult;
import com.google.zxing.client.result.ResultParser;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.encoder.ByteMatrix;
import com.zz.common.utils.ImageUtil;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.Map;
/**
* This class does the work of decoding the user's request and extracting all the data
* to be encoded in a barcode.
*
* @author dswitkin@google.com (Daniel Switkin)
*/
final public class QRCodeEncoder {
private static final String TAG = QRCodeEncoder.class.getSimpleName();
private static final int WHITE = 0xFFFFFFFF;
private static final int BLACK = 0xFF000000;
private final Activity activity;
private String contents;
private BarcodeFormat format;
private final int dimension;
private final boolean useVCard;
QRCodeEncoder(Activity activity, Intent intent, int dimension, boolean useVCard) throws WriterException {
this.activity = activity;
this.dimension = dimension;
this.useVCard = useVCard;
String action = intent.getAction();
if (action.equals(Intents.Encode.ACTION)) {
encodeContentsFromZXingIntent(intent);
} else if (action.equals(Intent.ACTION_SEND)) {
encodeContentsFromShareIntent(intent);
}
}
public static Bitmap encode(String content, String filePath) throws Throwable {
File file = new File(filePath);
if(!file.exists() || !file.isFile()) {
file.createNewFile();
}
BitMatrix byteMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, 200, 200);
Bitmap bitmap = toBitmap(byteMatrix);
ImageUtil.saveBitmapFileAsJPEG(bitmap, file);
return bitmap;
}
private static Bitmap toBitmap(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
Bitmap bmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
bmap.setPixel(x, y, matrix.get(x, y)? 0xFF000000 : 0xFFFFFFFF);
}
}
return bmap;
}
String getContents() {
return contents;
}
boolean isUseVCard() {
return useVCard;
}
// It would be nice if the string encoding lived in the core ZXing library,
// but we use platform specific code like PhoneNumberUtils, so it can't.
private boolean encodeContentsFromZXingIntent(Intent intent) {
// Default to QR_CODE if no format given.
String formatString = intent.getStringExtra(Intents.Encode.FORMAT);
format = null;
if (formatString != null) {
try {
format = BarcodeFormat.valueOf(formatString);
} catch (IllegalArgumentException iae) {
// Ignore it then
}
}
if (format == null || format == BarcodeFormat.QR_CODE) {
String type = intent.getStringExtra(Intents.Encode.TYPE);
if (type == null || type.length() == 0) {
return false;
}
this.format = BarcodeFormat.QR_CODE;
encodeQRCodeContents(intent, type);
} else {
String data = intent.getStringExtra(Intents.Encode.DATA);
if (data != null && data.length() > 0) {
contents = data;
}
}
return contents != null && contents.length() > 0;
}
// Handles send intents from multitude of Android applications
private void encodeContentsFromShareIntent(Intent intent) throws WriterException {
// Check if this is a plain text encoding, or contact
if (intent.hasExtra(Intent.EXTRA_STREAM)) {
encodeFromStreamExtra(intent);
} else {
encodeFromTextExtras(intent);
}
}
private void encodeFromTextExtras(Intent intent) throws WriterException {
// Notice: Google Maps shares both URL and details in one text, bummer!
String theContents = ContactEncoder.trim(intent.getStringExtra(Intent.EXTRA_TEXT));
if (theContents == null) {
theContents = ContactEncoder.trim(intent.getStringExtra("android.intent.extra.HTML_TEXT"));
// Intent.EXTRA_HTML_TEXT
if (theContents == null) {
theContents = ContactEncoder.trim(intent.getStringExtra(Intent.EXTRA_SUBJECT));
if (theContents == null) {
String[] emails = intent.getStringArrayExtra(Intent.EXTRA_EMAIL);
if (emails != null) {
theContents = ContactEncoder.trim(emails[0]);
} else {
theContents = "?";
}
}
}
}
// Trim text to avoid URL breaking.
if (theContents == null || theContents.length() == 0) {
throw new WriterException("Empty EXTRA_TEXT");
}
contents = theContents;
// We only do QR code.
format = BarcodeFormat.QR_CODE;
}
// Handles send intents from the Contacts app, retrieving a contact as a VCARD.
private void encodeFromStreamExtra(Intent intent) throws WriterException {
format = BarcodeFormat.QR_CODE;
Bundle bundle = intent.getExtras();
if (bundle == null) {
throw new WriterException("No extras");
}
Uri uri = bundle.getParcelable(Intent.EXTRA_STREAM);
if (uri == null) {
throw new WriterException("No EXTRA_STREAM");
}
byte[] vcard;
String vcardString;
try {
InputStream stream = activity.getContentResolver().openInputStream(uri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int bytesRead;
while ((bytesRead = stream.read(buffer)) > 0) {
baos.write(buffer, 0, bytesRead);
}
vcard = baos.toByteArray();
vcardString = new String(vcard, 0, vcard.length, "UTF-8");
} catch (IOException ioe) {
throw new WriterException(ioe);
}
Log.d(TAG, "Encoding share intent content:");
Log.d(TAG, vcardString);
Result result = new Result(vcardString, vcard, null, BarcodeFormat.QR_CODE);
ParsedResult parsedResult = ResultParser.parseResult(result);
if (!(parsedResult instanceof AddressBookParsedResult)) {
throw new WriterException("Result was not an address");
}
encodeQRCodeContents((AddressBookParsedResult) parsedResult);
if (contents == null || contents.length() == 0) {
throw new WriterException("No content to encode");
}
}
private void encodeQRCodeContents(Intent intent, String type) {
if (type.equals(Contents.Type.TEXT)) {
String data = intent.getStringExtra(Intents.Encode.DATA);
if (data != null && data.length() > 0) {
contents = data;
}
} else if (type.equals(Contents.Type.EMAIL)) {
String data = ContactEncoder.trim(intent.getStringExtra(Intents.Encode.DATA));
if (data != null) {
contents = "mailto:" + data;
}
} else if (type.equals(Contents.Type.PHONE)) {
String data = ContactEncoder.trim(intent.getStringExtra(Intents.Encode.DATA));
if (data != null) {
contents = "tel:" + data;
}
} else if (type.equals(Contents.Type.SMS)) {
String data = ContactEncoder.trim(intent.getStringExtra(Intents.Encode.DATA));
if (data != null) {
contents = "sms:" + data;
}
} else if (type.equals(Contents.Type.CONTACT)) {
Bundle bundle = intent.getBundleExtra(Intents.Encode.DATA);
if (bundle != null) {
String name = bundle.getString(ContactsContract.Intents.Insert.NAME);
String organization = bundle.getString(ContactsContract.Intents.Insert.COMPANY);
String address = bundle.getString(ContactsContract.Intents.Insert.POSTAL);
Collection<String> phones = new ArrayList<String>(Contents.PHONE_KEYS.length);
for (int x = 0; x < Contents.PHONE_KEYS.length; x++) {
phones.add(bundle.getString(Contents.PHONE_KEYS[x]));
}
Collection<String> emails = new ArrayList<String>(Contents.EMAIL_KEYS.length);
for (int x = 0; x < Contents.EMAIL_KEYS.length; x++) {
emails.add(bundle.getString(Contents.EMAIL_KEYS[x]));
}
String url = bundle.getString(Contents.URL_KEY);
Collection<String> urls = url == null ? null : Collections.singletonList(url);
String note = bundle.getString(Contents.NOTE_KEY);
ContactEncoder mecardEncoder = useVCard ? new VCardContactEncoder() : new MECARDContactEncoder();
String[] encoded = mecardEncoder.encode(Collections.singleton(name),
organization,
Collections.singleton(address),
phones,
emails,
urls,
note);
// Make sure we've encoded at least one field.
if (encoded[1].length() > 0) {
contents = encoded[0];
}
}
} else if (type.equals(Contents.Type.LOCATION)) {
Bundle bundle = intent.getBundleExtra(Intents.Encode.DATA);
if (bundle != null) {
// These must use Bundle.getFloat(), not getDouble(), it's part of the API.
float latitude = bundle.getFloat("LAT", Float.MAX_VALUE);
float longitude = bundle.getFloat("LONG", Float.MAX_VALUE);
if (latitude != Float.MAX_VALUE && longitude != Float.MAX_VALUE) {
contents = "geo:" + latitude + ',' + longitude;
}
}
}
}
private void encodeQRCodeContents(AddressBookParsedResult contact) {
ContactEncoder encoder = useVCard ? new VCardContactEncoder() : new MECARDContactEncoder();
String[] encoded = encoder.encode(toIterable(contact.getNames()),
contact.getOrg(),
toIterable(contact.getAddresses()),
toIterable(contact.getPhoneNumbers()),
toIterable(contact.getEmails()),
toIterable(contact.getURLs()),
null);
// Make sure we've encoded at least one field.
if (encoded[1].length() > 0) {
contents = encoded[0];
}
}
private static Iterable<String> toIterable(String[] values) {
return values == null ? null : Arrays.asList(values);
}
Bitmap encodeAsBitmap() throws WriterException {
String contentsToEncode = contents;
if (contentsToEncode == null) {
return null;
}
Map<EncodeHintType,Object> hints = null;
String encoding = guessAppropriateEncoding(contentsToEncode);
if (encoding != null) {
hints = new EnumMap<EncodeHintType,Object>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, encoding);
}
BitMatrix result;
try {
result = new MultiFormatWriter().encode(contentsToEncode, format, dimension, dimension, hints);
} catch (IllegalArgumentException iae) {
// Unsupported format
return null;
}
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
private static String guessAppropriateEncoding(CharSequence contents) {
// Very crude at the moment
for (int i = 0; i < contents.length(); i++) {
if (contents.charAt(i) > 0xFF) {
return "UTF-8";
}
}
return null;
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/encode/QRCodeEncoder.java
|
Java
|
epl
| 13,141
|
/*
* Copyright (C) 2009 ZXing authors
*
* 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 com.google.zxing.client.android;
import com.google.zxing.ResultPoint;
import com.google.zxing.ResultPointCallback;
final class ViewfinderResultPointCallback implements ResultPointCallback {
private final ViewfinderView viewfinderView;
ViewfinderResultPointCallback(ViewfinderView viewfinderView) {
this.viewfinderView = viewfinderView;
}
@Override
public void foundPossibleResultPoint(ResultPoint point) {
viewfinderView.addPossibleResultPoint(point);
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/ViewfinderResultPointCallback.java
|
Java
|
epl
| 1,093
|
/*
* Copyright (C) 2010 ZXing authors
*
* 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 com.google.zxing.client.android;
import android.graphics.Bitmap;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.client.android.camera.CameraManager;
import com.google.zxing.common.HybridBinarizer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.util.Map;
final class DecodeHandler extends Handler {
public interface IHandleDecoding {
public CameraManager getCameraManager();
public Handler getHandler();
}
private static final String TAG = DecodeHandler.class.getSimpleName();
private final IHandleDecoding activity;
private final MultiFormatReader multiFormatReader;
private boolean running = true;
DecodeHandler(IHandleDecoding activity, Map<DecodeHintType,Object> hints) {
multiFormatReader = new MultiFormatReader();
multiFormatReader.setHints(hints);
this.activity = activity;
}
@Override
public void handleMessage(Message message) {
if (!running) {
return;
}
switch (message.what) {
case Action.ACTION_DECODE:
decode((byte[]) message.obj, message.arg1, message.arg2);
break;
case Action.ACTION_QUIT:
running = false;
Looper.myLooper().quit();
break;
}
}
/**
* Decode the data within the viewfinder rectangle, and time how long it took. For efficiency,
* reuse the same reader objects from one decode to the next.
*
* @param data The YUV preview frame.
* @param width The width of the preview frame.
* @param height The height of the preview frame.
*/
private void decode(byte[] data, int width, int height) {
long start = System.currentTimeMillis();
Result rawResult = null;
PlanarYUVLuminanceSource source = activity.getCameraManager().buildLuminanceSource(data, width, height);
if (source != null) {
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
rawResult = multiFormatReader.decodeWithState(bitmap);
} catch (ReaderException re) {
// continue
} finally {
multiFormatReader.reset();
}
}
Handler handler = activity.getHandler();
if (rawResult != null) {
// Don't log the barcode contents for security.
long end = System.currentTimeMillis();
Log.d(TAG, "Found barcode in " + (end - start) + " ms");
if (handler != null) {
Message message = Message.obtain(handler, Action.ACTION_DECODE_SUCCESS, rawResult);
Bundle bundle = new Bundle();
bundleThumbnail(source, bundle);
message.setData(bundle);
message.sendToTarget();
}
} else {
if (handler != null) {
Message message = Message.obtain(handler, Action.ACTION_DECODE_FAILED);
message.sendToTarget();
}
}
}
private static void bundleThumbnail(PlanarYUVLuminanceSource source, Bundle bundle) {
int[] pixels = source.renderThumbnail();
int width = source.getThumbnailWidth();
int height = source.getThumbnailHeight();
Bitmap bitmap = Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.ARGB_8888);
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, out);
bundle.putByteArray(DecodeThread.BARCODE_BITMAP, out.toByteArray());
bundle.putFloat(DecodeThread.BARCODE_SCALED_FACTOR, (float) width / source.getWidth());
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/DecodeHandler.java
|
Java
|
epl
| 4,321
|
/*
* Copyright (C) 2008 ZXing authors
*
* 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 com.google.zxing.client.android;
import android.graphics.BitmapFactory;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
import com.google.zxing.Result;
import com.google.zxing.client.android.DecodeHandler.IHandleDecoding;
import com.google.zxing.client.android.camera.CameraManager;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.util.Collection;
import java.util.Map;
/**
* This class handles all the messaging which comprises the state machine for capture.
*
* @author dswitkin@google.com (Daniel Switkin)
*/
public final class DecodeActivityHandler extends Handler {
public interface IHandleActivity extends IHandleDecoding{
public void drawViewfinder();
public ViewfinderView getViewfinderView();
public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor);
}
private static final String TAG = DecodeActivityHandler.class.getSimpleName();
private final IHandleActivity activity;
private final DecodeThread decodeThread;
private State state;
private final CameraManager cameraManager;
private enum State {
PREVIEW,
SUCCESS,
DONE
}
public DecodeActivityHandler(IHandleActivity activity,
Collection<BarcodeFormat> decodeFormats,
Map<DecodeHintType,?> baseHints,
String characterSet,
CameraManager cameraManager) {
this.activity = activity;
decodeThread = new DecodeThread(activity, decodeFormats, baseHints, characterSet,
new ViewfinderResultPointCallback(activity.getViewfinderView()));
decodeThread.start();
state = State.SUCCESS;
// Start ourselves capturing previews and decoding.
this.cameraManager = cameraManager;
cameraManager.startPreview();
restartPreviewAndDecode();
}
@Override
public void handleMessage(Message message) {
switch (message.what) {
case Action.ACTION_RESTART_PREVIEW:
Log.d(TAG, "Got restart preview message");
restartPreviewAndDecode();
break;
case Action.ACTION_DECODE_SUCCESS:
Log.d(TAG, "Got decode succeeded message");
state = State.SUCCESS;
Bundle bundle = message.getData();
Bitmap barcode = null;
float scaleFactor = 1.0f;
if (bundle != null) {
byte[] compressedBitmap = bundle.getByteArray(DecodeThread.BARCODE_BITMAP);
if (compressedBitmap != null) {
barcode = BitmapFactory.decodeByteArray(compressedBitmap, 0, compressedBitmap.length, null);
// Mutable copy:
barcode = barcode.copy(Bitmap.Config.ARGB_8888, true);
}
scaleFactor = bundle.getFloat(DecodeThread.BARCODE_SCALED_FACTOR);
}
activity.handleDecode((Result) message.obj, barcode, scaleFactor);
break;
case Action.ACTION_DECODE_FAILED:
// We're decoding as fast as possible, so when one decode fails, start another.
state = State.PREVIEW;
cameraManager.requestPreviewFrame(decodeThread.getHandler(), Action.ACTION_DECODE);
break;
// case Action.ACTION_RETURN_SCAN_RESULT:
// Log.d(TAG, "Got return scan result message");
// activity.setResult(Activity.RESULT_OK, (Intent) message.obj);
// activity.finish();
// break;
default:
break;
}
}
public void quitSynchronously() {
state = State.DONE;
cameraManager.stopPreview();
Message quit = Message.obtain(decodeThread.getHandler(), Action.ACTION_QUIT);
quit.sendToTarget();
try {
// Wait at most half a second; should be enough time, and onPause() will timeout quickly
decodeThread.join(500L);
} catch (InterruptedException e) {
// continue
}
// Be absolutely sure we don't send any queued up messages
removeMessages(Action.ACTION_DECODE_SUCCESS);
removeMessages(Action.ACTION_DECODE_FAILED);
}
private void restartPreviewAndDecode() {
if (state == State.SUCCESS) {
state = State.PREVIEW;
cameraManager.requestPreviewFrame(decodeThread.getHandler(), Action.ACTION_DECODE);
activity.drawViewfinder();
}
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/DecodeActivityHandler.java
|
Java
|
epl
| 4,971
|
/*
* Copyright (C) 2008 ZXing authors
*
* 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 com.google.zxing.client.android;
import android.provider.ContactsContract;
/**
* The set of constants to use when sending Barcode Scanner an Intent which requests a barcode
* to be encoded.
*
* @author dswitkin@google.com (Daniel Switkin)
*/
public final class Contents {
private Contents() {
}
public static final class Type {
/**
* Plain text. Use Intent.putExtra(DATA, string). This can be used for URLs too, but string
* must include "http://" or "https://".
*/
public static final String TEXT = "TEXT_TYPE";
/**
* An email type. Use Intent.putExtra(DATA, string) where string is the email address.
*/
public static final String EMAIL = "EMAIL_TYPE";
/**
* Use Intent.putExtra(DATA, string) where string is the phone number to call.
*/
public static final String PHONE = "PHONE_TYPE";
/**
* An SMS type. Use Intent.putExtra(DATA, string) where string is the number to SMS.
*/
public static final String SMS = "SMS_TYPE";
/**
* A contact. Send a request to encode it as follows:
* <p/>
* import android.provider.Contacts;
* <p/>
* Intent intent = new Intent(Intents.Encode.ACTION);
* intent.putExtra(Intents.Encode.TYPE, CONTACT);
* Bundle bundle = new Bundle();
* bundle.putString(Contacts.Intents.Insert.NAME, "Jenny");
* bundle.putString(Contacts.Intents.Insert.PHONE, "8675309");
* bundle.putString(Contacts.Intents.Insert.EMAIL, "jenny@the80s.com");
* bundle.putString(Contacts.Intents.Insert.POSTAL, "123 Fake St. San Francisco, CA 94102");
* intent.putExtra(Intents.Encode.DATA, bundle);
*/
public static final String CONTACT = "CONTACT_TYPE";
/**
* A geographic location. Use as follows:
* Bundle bundle = new Bundle();
* bundle.putFloat("LAT", latitude);
* bundle.putFloat("LONG", longitude);
* intent.putExtra(Intents.Encode.DATA, bundle);
*/
public static final String LOCATION = "LOCATION_TYPE";
private Type() {
}
}
public static final String URL_KEY = "URL_KEY";
public static final String NOTE_KEY = "NOTE_KEY";
/**
* When using Type.CONTACT, these arrays provide the keys for adding or retrieving multiple
* phone numbers and addresses.
*/
public static final String[] PHONE_KEYS = {
ContactsContract.Intents.Insert.PHONE,
ContactsContract.Intents.Insert.SECONDARY_PHONE,
ContactsContract.Intents.Insert.TERTIARY_PHONE
};
public static final String[] PHONE_TYPE_KEYS = {
ContactsContract.Intents.Insert.PHONE_TYPE,
ContactsContract.Intents.Insert.SECONDARY_PHONE_TYPE,
ContactsContract.Intents.Insert.TERTIARY_PHONE_TYPE
};
public static final String[] EMAIL_KEYS = {
ContactsContract.Intents.Insert.EMAIL,
ContactsContract.Intents.Insert.SECONDARY_EMAIL,
ContactsContract.Intents.Insert.TERTIARY_EMAIL
};
public static final String[] EMAIL_TYPE_KEYS = {
ContactsContract.Intents.Insert.EMAIL_TYPE,
ContactsContract.Intents.Insert.SECONDARY_EMAIL_TYPE,
ContactsContract.Intents.Insert.TERTIARY_EMAIL_TYPE
};
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/Contents.java
|
Java
|
epl
| 3,768
|
package com.google.zxing.client.android;
public final class Action {
public static final int ACTION_DECODE = 0x10000;
public static final int ACTION_QUIT = ACTION_DECODE + 1;
public static final int ACTION_DECODE_SUCCESS = ACTION_QUIT + 1;
public static final int ACTION_DECODE_FAILED = ACTION_DECODE_SUCCESS + 1;
public static final int ACTION_RESTART_PREVIEW = ACTION_DECODE_FAILED + 1;
public static final int ACTION_RETURN_SCAN_RESULT = ACTION_RESTART_PREVIEW + 1;
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/Action.java
|
Java
|
epl
| 484
|
/*
* Copyright (C) 2012 ZXing authors
*
* 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 com.google.zxing.client.android.camera;
import android.content.SharedPreferences;
/**
* Enumerates settings of the prefernce controlling the front light.
*/
public enum FrontLightMode {
/** Always on. */
ON,
/** On only when ambient light is low. */
AUTO,
/** Always off. */
OFF;
private static FrontLightMode parse(String modeString) {
return modeString == null ? OFF : valueOf(modeString);
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/camera/FrontLightMode.java
|
Java
|
epl
| 1,034
|
/*
* Copyright (C) 2010 ZXing authors
*
* 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 com.google.zxing.client.android.camera;
import android.graphics.Point;
import android.hardware.Camera;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
final class PreviewCallback implements Camera.PreviewCallback {
private static final String TAG = PreviewCallback.class.getSimpleName();
private final CameraConfigurationManager configManager;
private Handler previewHandler;
private int previewMessage;
PreviewCallback(CameraConfigurationManager configManager) {
this.configManager = configManager;
}
void setHandler(Handler previewHandler, int previewMessage) {
this.previewHandler = previewHandler;
this.previewMessage = previewMessage;
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
Point cameraResolution = configManager.getCameraResolution();
Handler thePreviewHandler = previewHandler;
if (cameraResolution != null && thePreviewHandler != null) {
Message message = thePreviewHandler.obtainMessage(previewMessage, cameraResolution.x,
cameraResolution.y, data);
message.sendToTarget();
previewHandler = null;
} else {
Log.d(TAG, "Got preview callback, but no handler or resolution available");
}
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/camera/PreviewCallback.java
|
Java
|
epl
| 1,865
|
/*
* Copyright (C) 2012 ZXing authors
*
* 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 com.google.zxing.client.android.camera.open;
import android.annotation.TargetApi;
import android.hardware.Camera;
import android.util.Log;
/**
* Implementation for Android API 9 (Gingerbread) and later. This opens up the possibility of accessing
* front cameras, and rotated cameras.
*/
@TargetApi(9)
public final class GingerbreadOpenCameraInterface implements OpenCameraInterface {
private static final String TAG = "GingerbreadOpenCamera";
/**
* Opens a rear-facing camera with {@link Camera#open(int)}, if one exists, or opens camera 0.
*/
@Override
public Camera open() {
int numCameras = Camera.getNumberOfCameras();
if (numCameras == 0) {
Log.w(TAG, "No cameras!");
return null;
}
int index = 0;
while (index < numCameras) {
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
Camera.getCameraInfo(index, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
break;
}
index++;
}
Camera camera;
if (index < numCameras) {
Log.i(TAG, "Opening camera #" + index);
camera = Camera.open(index);
} else {
Log.i(TAG, "No camera facing back; returning camera #0");
camera = Camera.open(0);
}
return camera;
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/camera/open/GingerbreadOpenCameraInterface.java
|
Java
|
epl
| 1,902
|
/*
* Copyright (C) 2012 ZXing authors
*
* 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 com.google.zxing.client.android.camera.open;
import android.hardware.Camera;
/**
* Default implementation for Android before API 9 / Gingerbread.
*/
final class DefaultOpenCameraInterface implements OpenCameraInterface {
/**
* Calls {@link Camera#open()}.
*/
@Override
public Camera open() {
return Camera.open();
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/camera/open/DefaultOpenCameraInterface.java
|
Java
|
epl
| 955
|
/*
* Copyright (C) 2012 ZXing authors
*
* 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 com.google.zxing.client.android.camera.open;
import android.hardware.Camera;
/**
* Provides an abstracted means to open a {@link Camera}. The API changes over Android API versions and
* this allows the app to use newer API methods while retaining backwards-compatible behavior.
*/
public interface OpenCameraInterface {
Camera open();
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/camera/open/OpenCameraInterface.java
|
Java
|
epl
| 957
|
/*
* Copyright (C) 2012 ZXing authors
*
* 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 com.google.zxing.client.android.camera.open;
import com.google.zxing.client.android.common.PlatformSupportManager;
/**
* Selects an appropriate implementation of {@link OpenCameraInterface} based on the device's
* API level.
*/
public final class OpenCameraManager extends PlatformSupportManager<OpenCameraInterface> {
public OpenCameraManager() {
super(OpenCameraInterface.class, new DefaultOpenCameraInterface());
addImplementationClass(9, "com.google.zxing.client.android.camera.open.GingerbreadOpenCameraInterface");
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/camera/open/OpenCameraManager.java
|
Java
|
epl
| 1,155
|
/*
* Copyright (C) 2012 ZXing authors
*
* 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 com.google.zxing.client.android.camera.exposure;
import android.hardware.Camera;
public final class DefaultExposureInterface implements ExposureInterface {
@Override
public void setExposure(Camera.Parameters parameters, boolean lightOn) {
// Do nothing
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/camera/exposure/DefaultExposureInterface.java
|
Java
|
epl
| 882
|
/*
* Copyright (C) 2012 ZXing authors
*
* 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 com.google.zxing.client.android.camera.exposure;
import android.hardware.Camera;
/**
* Implementations control auto-exposure settings of the camera, if available.
*
* @author Sean Owen
*/
public interface ExposureInterface {
void setExposure(Camera.Parameters parameters, boolean lightOn);
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/camera/exposure/ExposureInterface.java
|
Java
|
epl
| 914
|
/*
* Copyright (C) 2012 ZXing authors
*
* 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 com.google.zxing.client.android.camera.exposure;
import com.google.zxing.client.android.common.PlatformSupportManager;
public final class ExposureManager extends PlatformSupportManager<ExposureInterface> {
public ExposureManager() {
super(ExposureInterface.class, new DefaultExposureInterface());
addImplementationClass(8, "com.google.zxing.client.android.camera.exposure.FroyoExposureInterface");
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/camera/exposure/ExposureManager.java
|
Java
|
epl
| 1,029
|
/*
* Copyright (C) 2012 ZXing authors
*
* 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 com.google.zxing.client.android.camera.exposure;
import android.annotation.TargetApi;
import android.hardware.Camera;
import android.util.Log;
@TargetApi(8)
public final class FroyoExposureInterface implements ExposureInterface {
private static final String TAG = FroyoExposureInterface.class.getSimpleName();
private static final float MAX_EXPOSURE_COMPENSATION = 1.5f;
private static final float MIN_EXPOSURE_COMPENSATION = 0.0f;
@Override
public void setExposure(Camera.Parameters parameters, boolean lightOn) {
int minExposure = parameters.getMinExposureCompensation();
int maxExposure = parameters.getMaxExposureCompensation();
if (minExposure != 0 || maxExposure != 0) {
float step = parameters.getExposureCompensationStep();
int desiredCompensation;
if (lightOn) {
// Light on; set low exposue compensation
desiredCompensation = Math.max((int) (MIN_EXPOSURE_COMPENSATION / step), minExposure);
} else {
// Light off; set high compensation
desiredCompensation = Math.min((int) (MAX_EXPOSURE_COMPENSATION / step), maxExposure);
}
Log.i(TAG, "Setting exposure compensation to " + desiredCompensation + " / " + (step * desiredCompensation));
parameters.setExposureCompensation(desiredCompensation);
} else {
Log.i(TAG, "Camera does not support exposure compensation");
}
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/camera/exposure/FroyoExposureInterface.java
|
Java
|
epl
| 2,007
|
/*
* Copyright (C) 2012 ZXing authors
*
* 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 com.google.zxing.client.android.camera;
import android.annotation.SuppressLint;
import android.content.Context;
import android.hardware.Camera;
import android.os.AsyncTask;
import android.util.Log;
import java.util.ArrayList;
import java.util.Collection;
import com.google.zxing.client.android.common.executor.AsyncTaskExecInterface;
import com.google.zxing.client.android.common.executor.AsyncTaskExecManager;
final class AutoFocusManager implements Camera.AutoFocusCallback {
private static final String TAG = AutoFocusManager.class.getSimpleName();
private static final long AUTO_FOCUS_INTERVAL_MS = 2000L;
private static final Collection<String> FOCUS_MODES_CALLING_AF;
static {
FOCUS_MODES_CALLING_AF = new ArrayList<String>(2);
FOCUS_MODES_CALLING_AF.add(Camera.Parameters.FOCUS_MODE_AUTO);
FOCUS_MODES_CALLING_AF.add(Camera.Parameters.FOCUS_MODE_MACRO);
}
private boolean active;
private final boolean useAutoFocus;
private final Camera camera;
private AutoFocusTask outstandingTask;
private final AsyncTaskExecInterface taskExec;
@SuppressLint("NewApi")
AutoFocusManager(Context context, Camera camera) {
this.camera = camera;
taskExec = new AsyncTaskExecManager().build();
String currentFocusMode = camera.getParameters().getFocusMode();
useAutoFocus = FOCUS_MODES_CALLING_AF.contains(currentFocusMode);
Log.i(TAG, "Current focus mode '" + currentFocusMode + "'; use auto focus? " + useAutoFocus);
start();
}
@Override
public synchronized void onAutoFocus(boolean success, Camera theCamera) {
if (active) {
outstandingTask = new AutoFocusTask();
taskExec.execute(outstandingTask);
}
}
synchronized void start() {
if (useAutoFocus) {
active = true;
try {
camera.autoFocus(this);
} catch (RuntimeException re) {
// Have heard RuntimeException reported in Android 4.0.x+; continue?
Log.w(TAG, "Unexpected exception while focusing", re);
}
}
}
@SuppressLint("NewApi")
synchronized void stop() {
if (useAutoFocus) {
try {
camera.cancelAutoFocus();
} catch (RuntimeException re) {
// Have heard RuntimeException reported in Android 4.0.x+; continue?
Log.w(TAG, "Unexpected exception while cancelling focusing", re);
}
}
if (outstandingTask != null) {
outstandingTask.cancel(true);
outstandingTask = null;
}
active = false;
}
@SuppressLint("NewApi")
private final class AutoFocusTask extends AsyncTask<Object,Object,Object> {
@Override
protected Object doInBackground(Object... voids) {
try {
Thread.sleep(AUTO_FOCUS_INTERVAL_MS);
} catch (InterruptedException e) {
// continue
}
synchronized (AutoFocusManager.this) {
if (active) {
start();
}
}
return null;
}
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/camera/AutoFocusManager.java
|
Java
|
epl
| 3,509
|
/*
* Copyright (C) 2008 ZXing authors
*
* 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 com.google.zxing.client.android.camera;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Point;
import android.graphics.Rect;
import android.hardware.Camera;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.client.android.camera.open.OpenCameraManager;
import java.io.IOException;
/**
* This object wraps the Camera service object and expects to be the only one talking to it. The
* implementation encapsulates the steps needed to take preview-sized images, which are used for
* both preview and decoding.
*
* @author dswitkin@google.com (Daniel Switkin)
*/
@SuppressLint("NewApi")
public final class CameraManager {
private static final String TAG = CameraManager.class.getSimpleName();
private static final int MIN_FRAME_WIDTH = 240;
private static final int MIN_FRAME_HEIGHT = 240;
private static final int MAX_FRAME_HEIGHT = 960; // = 1920/2
private static final int MAX_FRAME_WIDTH = 540; // = 1080/2
private final Context context;
private final CameraConfigurationManager configManager;
private Camera camera;
private AutoFocusManager autoFocusManager;
private Rect framingRect;
private Rect framingRectInPreview;
private boolean initialized;
private boolean previewing;
private int requestedFramingRectWidth;
private int requestedFramingRectHeight;
/**
* Preview frames are delivered here, which we pass on to the registered handler. Make sure to
* clear the handler so it will only receive one message.
*/
private final PreviewCallback previewCallback;
public CameraManager(Context context) {
this.context = context;
this.configManager = new CameraConfigurationManager(context);
previewCallback = new PreviewCallback(configManager);
}
/**
* Opens the camera driver and initializes the hardware parameters.
*
* @param holder The surface object which the camera will draw preview frames into.
* @throws IOException Indicates the camera driver failed to open.
*/
public synchronized void openDriver(SurfaceHolder holder) throws IOException {
Camera theCamera = camera;
if (theCamera == null) {
theCamera = new OpenCameraManager().build().open();
if (theCamera == null) {
throw new IOException();
}
camera = theCamera;
}
theCamera.setPreviewDisplay(holder);
if (!initialized) {
initialized = true;
configManager.initFromCameraParameters(theCamera);
if (requestedFramingRectWidth > 0 && requestedFramingRectHeight > 0) {
setManualFramingRect(requestedFramingRectWidth, requestedFramingRectHeight);
requestedFramingRectWidth = 0;
requestedFramingRectHeight = 0;
}
}
Camera.Parameters parameters = theCamera.getParameters();
String parametersFlattened = parameters == null ? null : parameters.flatten(); // Save these, temporarily
try {
configManager.setDesiredCameraParameters(theCamera, false);
} catch (RuntimeException re) {
// Driver failed
Log.w(TAG, "Camera rejected parameters. Setting only minimal safe-mode parameters");
Log.i(TAG, "Resetting to saved camera params: " + parametersFlattened);
// Reset:
if (parametersFlattened != null) {
parameters = theCamera.getParameters();
parameters.unflatten(parametersFlattened);
try {
theCamera.setParameters(parameters);
configManager.setDesiredCameraParameters(theCamera, true);
} catch (RuntimeException re2) {
// Well, darn. Give up
Log.w(TAG, "Camera rejected even safe-mode parameters! No configuration");
}
}
}
}
public synchronized boolean isOpen() {
return camera != null;
}
/**
* Closes the camera driver if still in use.
*/
public synchronized void closeDriver() {
if (camera != null) {
camera.release();
camera = null;
// Make sure to clear these each time we close the camera, so that any scanning rect
// requested by intent is forgotten.
framingRect = null;
framingRectInPreview = null;
}
}
/**
* Asks the camera hardware to begin drawing preview frames to the screen.
*/
public synchronized void startPreview() {
Camera theCamera = camera;
if (theCamera != null && !previewing) {
theCamera.startPreview();
previewing = true;
autoFocusManager = new AutoFocusManager(context, camera);
}
}
/**
* Tells the camera to stop drawing preview frames.
*/
public synchronized void stopPreview() {
if (autoFocusManager != null) {
autoFocusManager.stop();
autoFocusManager = null;
}
if (camera != null && previewing) {
camera.stopPreview();
previewCallback.setHandler(null, 0);
previewing = false;
}
}
/**
* Convenience method for {@link com.google.zxing.client.android.CaptureActivity}
*/
public synchronized void setTorch(boolean newSetting) {
if (newSetting != configManager.getTorchState(camera)) {
if (camera != null) {
if (autoFocusManager != null) {
autoFocusManager.stop();
}
configManager.setTorch(camera, newSetting);
if (autoFocusManager != null) {
autoFocusManager.start();
}
}
}
}
/**
* A single preview frame will be returned to the handler supplied. The data will arrive as byte[]
* in the message.obj field, with width and height encoded as message.arg1 and message.arg2,
* respectively.
*
* @param handler The handler to send the message to.
* @param message The what field of the message to be sent.
*/
public synchronized void requestPreviewFrame(Handler handler, int message) {
Camera theCamera = camera;
if (theCamera != null && previewing) {
previewCallback.setHandler(handler, message);
theCamera.setOneShotPreviewCallback(previewCallback);
}
}
/**
* Calculates the framing rect which the UI should draw to show the user where to place the
* barcode. This target helps with alignment as well as forces the user to hold the device
* far enough away to ensure the image will be in focus.
*
* @return The rectangle to draw on screen in window coordinates.
*/
public synchronized Rect getFramingRect() {
if (framingRect == null) {
if (camera == null) {
return null;
}
Point screenResolution = configManager.getScreenResolution();
if (screenResolution == null) {
// Called early, before init even finished
return null;
}
// int width = findDesiredDimensionInRange(screenResolution.x, MIN_FRAME_WIDTH, MAX_FRAME_WIDTH);
// int height = findDesiredDimensionInRange(screenResolution.y, MIN_FRAME_HEIGHT, MAX_FRAME_HEIGHT);
Point cameraResolution = configManager.getCameraResolution();
int width = cameraResolution.x;
int height = cameraResolution.y;
if(width > height) {
width = width + height;
height = width - height;
width = width - height;
}
int leftOffset = (screenResolution.x - width) / 2;
int topOffset = (screenResolution.y - height) / 2;
framingRect = new Rect(leftOffset, topOffset, leftOffset + width, topOffset + height);
Log.d(TAG, "Calculated framing rect: " + framingRect);
}
return framingRect;
}
private static int findDesiredDimensionInRange(int resolution, int hardMin, int hardMax) {
int dim = resolution / 2; // Target 50% of each dimension
if (dim < hardMin) {
return hardMin;
}
if (dim > hardMax) {
return hardMax;
}
return dim;
}
/**
* Like {@link #getFramingRect} but coordinates are in terms of the preview frame,
* not UI / screen.
*/
public synchronized Rect getFramingRectInPreview() {
if (framingRectInPreview == null) {
Rect framingRect = getFramingRect();
if (framingRect == null) {
return null;
}
Rect rect = new Rect(framingRect);
Point cameraResolution = configManager.getCameraResolution();
Point screenResolution = configManager.getScreenResolution();
if (cameraResolution == null || screenResolution == null) {
// Called early, before init even finished
return null;
}
rect.left = rect.left * cameraResolution.x / screenResolution.x;
rect.right = rect.right * cameraResolution.x / screenResolution.x;
rect.top = rect.top * cameraResolution.y / screenResolution.y;
rect.bottom = rect.bottom * cameraResolution.y / screenResolution.y;
framingRectInPreview = rect;
}
return framingRectInPreview;
}
/**
* Allows third party apps to specify the scanning rectangle dimensions, rather than determine
* them automatically based on screen resolution.
*
* @param width The width in pixels to scan.
* @param height The height in pixels to scan.
*/
public synchronized void setManualFramingRect(int width, int height) {
if (initialized) {
Point screenResolution = configManager.getScreenResolution();
if (width > screenResolution.x) {
width = screenResolution.x;
}
if (height > screenResolution.y) {
height = screenResolution.y;
}
int leftOffset = (screenResolution.x - width) / 2;
int topOffset = (screenResolution.y - height) / 2;
framingRect = new Rect(leftOffset, topOffset, leftOffset + width, topOffset + height);
Log.d(TAG, "Calculated manual framing rect: " + framingRect);
framingRectInPreview = null;
} else {
requestedFramingRectWidth = width;
requestedFramingRectHeight = height;
}
}
/**
* A factory method to build the appropriate LuminanceSource object based on the format
* of the preview buffers, as described by Camera.Parameters.
*
* @param data A preview frame.
* @param width The width of the image.
* @param height The height of the image.
* @return A PlanarYUVLuminanceSource instance.
*/
public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) {
Rect rect = getFramingRectInPreview();
if (rect == null) {
return null;
}
// Go ahead and assume it's YUV rather than die.
return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,
rect.width(), rect.height(), false);
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/camera/CameraManager.java
|
Java
|
epl
| 11,148
|
/*
* Copyright (C) 2010 ZXing authors
*
* 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 com.google.zxing.client.android.camera;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Point;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Build;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* A class which deals with reading, parsing, and setting the camera parameters which are used to
* configure the camera hardware.
*/
@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.ECLAIR)
final class CameraConfigurationManager {
private static final String TAG = "CameraConfiguration";
// This is bigger than the size of a small screen, which is still supported. The routine
// below will still select the default (presumably 320x240) size for these. This prevents
// accidental selection of very low resolution on some devices.
private static final int MIN_PREVIEW_PIXELS = 470 * 320; // normal screen
private static final int MAX_PREVIEW_PIXELS = 1280 * 800;
private final Context context;
private Point screenResolution;
private Point cameraResolution;
CameraConfigurationManager(Context context) {
this.context = context;
}
/**
* Reads, one time, values from the camera that are needed by the app.
*/
void initFromCameraParameters(Camera camera) {
Camera.Parameters parameters = camera.getParameters();
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
// We're landscape-only, and have apparently seen issues with display thinking it's portrait
// when waking from sleep. If it's not landscape, assume it's mistaken and reverse them:
// if (width < height) {
if (width > height) {
Log.i(TAG, "Display reports portrait orientation; assuming this is incorrect");
int temp = width;
width = height;
height = temp;
}
screenResolution = new Point(width, height);
Log.i(TAG, "Screen resolution: " + screenResolution);
cameraResolution = findBestPreviewSizeValue(parameters, screenResolution);
Log.i(TAG, "Camera resolution: " + cameraResolution);
}
@SuppressLint("NewApi")
void setDesiredCameraParameters(Camera camera, boolean safeMode) {
Camera.Parameters parameters = camera.getParameters();
if (parameters == null) {
Log.w(TAG, "Device error: no camera parameters are available. Proceeding without configuration.");
return;
}
Log.i(TAG, "Initial camera parameters: " + parameters.flatten());
if (safeMode) {
Log.w(TAG, "In camera config safe mode -- most settings will not be honored");
}
// initializeTorch(parameters, safeMode);
String focusMode = null;
if (safeMode) {
focusMode = findSettableValue(parameters.getSupportedFocusModes(),
Camera.Parameters.FOCUS_MODE_AUTO);
} else {
focusMode = findSettableValue(parameters.getSupportedFocusModes(),
"continuous-picture", // Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE in 4.0+
"continuous-video", // Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO in 4.0+
Camera.Parameters.FOCUS_MODE_AUTO);
}
// Maybe selected auto-focus but not available, so fall through here:
if (!safeMode && focusMode == null) {
focusMode = findSettableValue(parameters.getSupportedFocusModes(),
Camera.Parameters.FOCUS_MODE_MACRO,
"edof"); // Camera.Parameters.FOCUS_MODE_EDOF in 2.2+
}
if (focusMode != null) {
parameters.setFocusMode(focusMode);
}
// String colorMode = findSettableValue(parameters.getSupportedColorEffects(),
// Camera.Parameters.EFFECT_NEGATIVE);
// if (colorMode != null) {
// parameters.setColorEffect(colorMode);
// }
parameters.setPreviewSize(cameraResolution.x, cameraResolution.y);
camera.setDisplayOrientation(90);
camera.setParameters(parameters);
}
Point getCameraResolution() {
return cameraResolution;
}
Point getScreenResolution() {
return screenResolution;
}
boolean getTorchState(Camera camera) {
if (camera != null) {
Camera.Parameters parameters = camera.getParameters();
if (parameters != null) {
String flashMode = camera.getParameters().getFlashMode();
return flashMode != null &&
(Camera.Parameters.FLASH_MODE_ON.equals(flashMode) ||
Camera.Parameters.FLASH_MODE_TORCH.equals(flashMode));
}
}
return false;
}
void setTorch(Camera camera, boolean newSetting) {
Camera.Parameters parameters = camera.getParameters();
doSetTorch(parameters, newSetting, false);
camera.setParameters(parameters);
}
private void initializeTorch(Camera.Parameters parameters, boolean safeMode) {
doSetTorch(parameters, true, safeMode);
}
private void doSetTorch(Camera.Parameters parameters, boolean newSetting, boolean safeMode) {
if(null != parameters) {
//
return;
}
String flashMode;
if (newSetting) {
flashMode = findSettableValue(parameters.getSupportedFlashModes(),
Camera.Parameters.FLASH_MODE_TORCH,
Camera.Parameters.FLASH_MODE_ON);
} else {
flashMode = findSettableValue(parameters.getSupportedFlashModes(),
Camera.Parameters.FLASH_MODE_OFF);
}
if (flashMode != null) {
parameters.setFlashMode(flashMode);
}
/*
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
if (!prefs.getBoolean(PreferencesActivity.KEY_DISABLE_EXPOSURE, false)) {
if (!safeMode) {
ExposureInterface exposure = new ExposureManager().build();
exposure.setExposure(parameters, newSetting);
}
}
*/
}
private Point findBestPreviewSizeValue(Camera.Parameters parameters, Point screenResolution) {
List<Camera.Size> rawSupportedSizes = parameters.getSupportedPreviewSizes();
if (rawSupportedSizes == null) {
Log.w(TAG, "Device returned no supported preview sizes; using default");
Camera.Size defaultSize = parameters.getPreviewSize();
return new Point(defaultSize.width, defaultSize.height);
}
// Sort by size, descending
List<Camera.Size> supportedPreviewSizes = new ArrayList<Camera.Size>(rawSupportedSizes);
Collections.sort(supportedPreviewSizes, new Comparator<Camera.Size>() {
@Override
public int compare(Camera.Size a, Camera.Size b) {
int aPixels = a.height * a.width;
int bPixels = b.height * b.width;
if (bPixels < aPixels) {
return -1;
}
if (bPixels > aPixels) {
return 1;
}
return 0;
}
});
if (Log.isLoggable(TAG, Log.INFO)) {
StringBuilder previewSizesString = new StringBuilder();
for (Camera.Size supportedPreviewSize : supportedPreviewSizes) {
previewSizesString.append(supportedPreviewSize.width).append('x')
.append(supportedPreviewSize.height).append(' ');
}
Log.i(TAG, "Supported preview sizes: " + previewSizesString);
}
Point bestSize = null;
float screenAspectRatio = (float) screenResolution.x / (float) screenResolution.y;
float diff = Float.POSITIVE_INFINITY;
for (Camera.Size supportedPreviewSize : supportedPreviewSizes) {
int realWidth = supportedPreviewSize.width;
int realHeight = supportedPreviewSize.height;
int pixels = realWidth * realHeight;
if (pixels < MIN_PREVIEW_PIXELS || pixels > MAX_PREVIEW_PIXELS) {
continue;
}
boolean isCandidatePortrait = realWidth < realHeight;
int maybeFlippedWidth = isCandidatePortrait ? realHeight : realWidth;
int maybeFlippedHeight = isCandidatePortrait ? realWidth : realHeight;
if (maybeFlippedWidth == screenResolution.x && maybeFlippedHeight == screenResolution.y) {
Point exactPoint = new Point(realWidth, realHeight);
Log.i(TAG, "Found preview size exactly matching screen size: " + exactPoint);
return exactPoint;
}
float aspectRatio = (float) maybeFlippedWidth / (float) maybeFlippedHeight;
float newDiff = Math.abs(aspectRatio - screenAspectRatio);
if (newDiff < diff) {
bestSize = new Point(realWidth, realHeight);
diff = newDiff;
}
}
if (bestSize == null) {
Camera.Size defaultSize = parameters.getPreviewSize();
bestSize = new Point(defaultSize.width, defaultSize.height);
Log.i(TAG, "No suitable preview sizes, using default: " + bestSize);
}
Log.i(TAG, "Found best approximate preview size: " + bestSize);
return bestSize;
}
private static String findSettableValue(Collection<String> supportedValues,
String... desiredValues) {
Log.i(TAG, "Supported values: " + supportedValues);
String result = null;
if (supportedValues != null) {
for (String desiredValue : desiredValues) {
if (supportedValues.contains(desiredValue)) {
result = desiredValue;
break;
}
}
}
Log.i(TAG, "Settable value: " + result);
return result;
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/camera/CameraConfigurationManager.java
|
Java
|
epl
| 10,321
|
/*
* Copyright 2011 ZXing authors
*
* 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 com.google.zxing.client.android;
import android.util.Log;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
/**
* Utility methods for retrieving content over HTTP using the more-supported {@code java.net} classes
* in Android.
*/
public final class HttpHelper {
private static final String TAG = HttpHelper.class.getSimpleName();
private static final Collection<String> REDIRECTOR_DOMAINS = new HashSet<String>(Arrays.asList(
"amzn.to", "bit.ly", "bitly.com", "fb.me", "goo.gl", "is.gd", "j.mp", "lnkd.in", "ow.ly",
"R.BEETAGG.COM", "r.beetagg.com", "SCN.BY", "su.pr", "t.co", "tinyurl.com", "tr.im"
));
private HttpHelper() {
}
public enum ContentType {
/** HTML-like content type, including HTML, XHTML, etc. */
HTML,
/** JSON content */
JSON,
/** XML */
XML,
/** Plain text content */
TEXT,
}
/**
* Downloads the entire resource instead of part.
*
* @see #downloadViaHttp(String, HttpHelper.ContentType, int)
*/
public static CharSequence downloadViaHttp(String uri, ContentType type) throws IOException {
return downloadViaHttp(uri, type, Integer.MAX_VALUE);
}
/**
* @param uri URI to retrieve
* @param type expected text-like MIME type of that content
* @param maxChars approximate maximum characters to read from the source
* @return content as a {@code String}
* @throws IOException if the content can't be retrieved because of a bad URI, network problem, etc.
*/
public static CharSequence downloadViaHttp(String uri, ContentType type, int maxChars) throws IOException {
String contentTypes;
switch (type) {
case HTML:
contentTypes = "application/xhtml+xml,text/html,text/*,*/*";
break;
case JSON:
contentTypes = "application/json,text/*,*/*";
break;
case XML:
contentTypes = "application/xml,text/*,*/*";
break;
case TEXT:
default:
contentTypes = "text/*,*/*";
}
return downloadViaHttp(uri, contentTypes, maxChars);
}
private static CharSequence downloadViaHttp(String uri, String contentTypes, int maxChars) throws IOException {
int redirects = 0;
while (redirects < 5) {
URL url = new URL(uri);
HttpURLConnection connection = safelyOpenConnection(url);
connection.setInstanceFollowRedirects(true); // Won't work HTTP -> HTTPS or vice versa
connection.setRequestProperty("Accept", contentTypes);
connection.setRequestProperty("Accept-Charset", "utf-8,*");
connection.setRequestProperty("User-Agent", "ZXing (Android)");
try {
int responseCode = safelyConnect(uri, connection);
switch (responseCode) {
case HttpURLConnection.HTTP_OK:
return consume(connection, maxChars);
case HttpURLConnection.HTTP_MOVED_TEMP:
String location = connection.getHeaderField("Location");
if (location != null) {
uri = location;
redirects++;
continue;
}
throw new IOException("No Location");
default:
throw new IOException("Bad HTTP response: " + responseCode);
}
} finally {
connection.disconnect();
}
}
throw new IOException("Too many redirects");
}
private static String getEncoding(URLConnection connection) {
String contentTypeHeader = connection.getHeaderField("Content-Type");
if (contentTypeHeader != null) {
int charsetStart = contentTypeHeader.indexOf("charset=");
if (charsetStart >= 0) {
return contentTypeHeader.substring(charsetStart + "charset=".length());
}
}
return "UTF-8";
}
private static CharSequence consume(URLConnection connection, int maxChars) throws IOException {
String encoding = getEncoding(connection);
StringBuilder out = new StringBuilder();
Reader in = null;
try {
in = new InputStreamReader(connection.getInputStream(), encoding);
char[] buffer = new char[1024];
int charsRead;
while (out.length() < maxChars && (charsRead = in.read(buffer)) > 0) {
out.append(buffer, 0, charsRead);
}
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ioe) {
// continue
} catch (NullPointerException npe) {
// another apparent Android / Harmony bug; continue
}
}
}
return out;
}
public static URI unredirect(URI uri) throws IOException {
if (!REDIRECTOR_DOMAINS.contains(uri.getHost())) {
return uri;
}
URL url = uri.toURL();
HttpURLConnection connection = safelyOpenConnection(url);
connection.setInstanceFollowRedirects(false);
connection.setDoInput(false);
connection.setRequestMethod("HEAD");
connection.setRequestProperty("User-Agent", "ZXing (Android)");
try {
int responseCode = safelyConnect(uri.toString(), connection);
switch (responseCode) {
case HttpURLConnection.HTTP_MULT_CHOICE:
case HttpURLConnection.HTTP_MOVED_PERM:
case HttpURLConnection.HTTP_MOVED_TEMP:
case HttpURLConnection.HTTP_SEE_OTHER:
case 307: // No constant for 307 Temporary Redirect ?
String location = connection.getHeaderField("Location");
if (location != null) {
try {
return new URI(location);
} catch (URISyntaxException e) {
// nevermind
}
}
}
return uri;
} finally {
connection.disconnect();
}
}
private static HttpURLConnection safelyOpenConnection(URL url) throws IOException {
URLConnection conn;
try {
conn = url.openConnection();
} catch (NullPointerException npe) {
// Another strange bug in Android?
Log.w(TAG, "Bad URI? " + url);
throw new IOException(npe.toString());
}
if (!(conn instanceof HttpURLConnection)) {
throw new IOException();
}
return (HttpURLConnection) conn;
}
private static int safelyConnect(String uri, HttpURLConnection connection) throws IOException {
try {
connection.connect();
} catch (NullPointerException npe) {
// this is an Android bug: http://code.google.com/p/android/issues/detail?id=16895
Log.w(TAG, "Bad URI? " + uri);
throw new IOException(npe.toString());
} catch (IllegalArgumentException iae) {
// Also seen this in the wild, not sure what to make of it. Probably a bad URL
Log.w(TAG, "Bad URI? " + uri);
throw new IOException(iae.toString());
} catch (SecurityException se) {
// due to bad VPN settings?
Log.w(TAG, "Restricted URI? " + uri);
throw new IOException(se.toString());
} catch (IndexOutOfBoundsException ioobe) {
// Another Android problem? https://groups.google.com/forum/?fromgroups#!topic/google-admob-ads-sdk/U-WfmYa9or0
Log.w(TAG, "Bad URI? " + uri);
throw new IOException(ioobe.toString());
}
try {
return connection.getResponseCode();
} catch (NullPointerException npe) {
// this is maybe this Android bug: http://code.google.com/p/android/issues/detail?id=15554
Log.w(TAG, "Bad URI? " + uri);
throw new IOException(npe.toString());
} catch (IllegalArgumentException iae) {
// Again seen this in the wild for bad header fields in the server response! or bad reads
Log.w(TAG, "Bad server status? " + uri);
throw new IOException(iae.toString());
}
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/HttpHelper.java
|
Java
|
epl
| 8,405
|
/*
* Copyright (C) 2010 ZXing authors
*
* 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 com.google.zxing.client.android;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.util.Log;
import java.io.IOException;
/**
* Manages beeps and vibrations for {@link CaptureActivity}.
*/
public final class BeepManager {
private static final String TAG = BeepManager.class.getSimpleName();
private static final float BEEP_VOLUME = 0.10f;
private static final long VIBRATE_DURATION = 200L;
private final Activity activity;
private MediaPlayer mediaPlayer;
private boolean playBeep;
private boolean vibrate;
private int beepId /* = R.raw.beep */;
public BeepManager(Activity activity, int beep) {
this.activity = activity;
this.mediaPlayer = null;
setBeepId(beepId);
updateConfig();
}
void setBeepId(int beep) {
this.beepId = beep;
}
public void updateConfig() {
playBeep = shouldBeep(activity);
vibrate = true;
if (playBeep && mediaPlayer == null) {
// The volume on STREAM_SYSTEM is not adjustable, and users found it too loud,
// so we now play on the music stream.
activity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
mediaPlayer = buildMediaPlayer(activity, beepId);
}
}
public void playBeepSoundAndVibrate() {
if (playBeep && mediaPlayer != null) {
mediaPlayer.start();
}
if (vibrate) {
Vibrator vibrator = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(VIBRATE_DURATION);
}
}
private static boolean shouldBeep(Context activity) {
boolean shouldPlayBeep = true;
// See if sound settings overrides this
AudioManager audioService = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);
if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
shouldPlayBeep = false;
}
return shouldPlayBeep;
}
private static MediaPlayer buildMediaPlayer(Context activity, int beepId) {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// When the beep has finished playing, rewind to queue up another one.
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer player) {
player.seekTo(0);
}
});
AssetFileDescriptor file = activity.getResources().openRawResourceFd(beepId);
try {
mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
file.close();
mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
mediaPlayer.prepare();
} catch (IOException ioe) {
Log.w(TAG, ioe);
mediaPlayer = null;
}
return mediaPlayer;
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/BeepManager.java
|
Java
|
epl
| 3,590
|
/*
* Copyright (C) 2008 ZXing authors
*
* 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 com.google.zxing.client.android;
/**
* This class provides the constants to use when sending an Intent to Barcode Scanner.
* These strings are effectively API and cannot be changed.
*
* @author dswitkin@google.com (Daniel Switkin)
*/
public final class Intents {
private Intents() {
}
public static final class Scan {
/**
* Send this intent to open the Barcodes app in scanning mode, find a barcode, and return
* the results.
*/
public static final String ACTION = "com.google.zxing.client.android.SCAN";
/**
* By default, sending this will decode all barcodes that we understand. However it
* may be useful to limit scanning to certain formats. Use
* {@link android.content.Intent#putExtra(String, String)} with one of the values below.
*
* Setting this is effectively shorthand for setting explicit formats with {@link #FORMATS}.
* It is overridden by that setting.
*/
public static final String MODE = "SCAN_MODE";
/**
* Decode only UPC and EAN barcodes. This is the right choice for shopping apps which get
* prices, reviews, etc. for products.
*/
public static final String PRODUCT_MODE = "PRODUCT_MODE";
/**
* Decode only 1D barcodes.
*/
public static final String ONE_D_MODE = "ONE_D_MODE";
/**
* Decode only QR codes.
*/
public static final String QR_CODE_MODE = "QR_CODE_MODE";
/**
* Decode only Data Matrix codes.
*/
public static final String DATA_MATRIX_MODE = "DATA_MATRIX_MODE";
/**
* Comma-separated list of formats to scan for. The values must match the names of
* {@link com.google.zxing.BarcodeFormat}s, e.g. {@link com.google.zxing.BarcodeFormat#EAN_13}.
* Example: "EAN_13,EAN_8,QR_CODE". This overrides {@link #MODE}.
*/
public static final String FORMATS = "SCAN_FORMATS";
/**
* @see com.google.zxing.DecodeHintType#CHARACTER_SET
*/
public static final String CHARACTER_SET = "CHARACTER_SET";
/**
* Optional parameters to specify the width and height of the scanning rectangle in pixels.
* The app will try to honor these, but will clamp them to the size of the preview frame.
* You should specify both or neither, and pass the size as an int.
*/
public static final String WIDTH = "SCAN_WIDTH";
public static final String HEIGHT = "SCAN_HEIGHT";
/**
* Desired duration in milliseconds for which to pause after a successful scan before
* returning to the calling intent. Specified as a long, not an integer!
* For example: 1000L, not 1000.
*/
public static final String RESULT_DISPLAY_DURATION_MS = "RESULT_DISPLAY_DURATION_MS";
/**
* Prompt to show on-screen when scanning by intent. Specified as a {@link String}.
*/
public static final String PROMPT_MESSAGE = "PROMPT_MESSAGE";
/**
* If a barcode is found, Barcodes returns {@link android.app.Activity#RESULT_OK} to
* {@link android.app.Activity#onActivityResult(int, int, android.content.Intent)}
* of the app which requested the scan via
* {@link android.app.Activity#startActivityForResult(android.content.Intent, int)}
* The barcodes contents can be retrieved with
* {@link android.content.Intent#getStringExtra(String)}.
* If the user presses Back, the result code will be {@link android.app.Activity#RESULT_CANCELED}.
*/
public static final String RESULT = "SCAN_RESULT";
/**
* Call {@link android.content.Intent#getStringExtra(String)} with {@link #RESULT_FORMAT}
* to determine which barcode format was found.
* See {@link com.google.zxing.BarcodeFormat} for possible values.
*/
public static final String RESULT_FORMAT = "SCAN_RESULT_FORMAT";
/**
* Call {@link android.content.Intent#getStringExtra(String)} with {@link #RESULT_UPC_EAN_EXTENSION}
* to return the content of any UPC extension barcode that was also found. Only applicable
* to {@link com.google.zxing.BarcodeFormat#UPC_A} and {@link com.google.zxing.BarcodeFormat#EAN_13}
* formats.
*/
public static final String RESULT_UPC_EAN_EXTENSION = "SCAN_RESULT_UPC_EAN_EXTENSION";
/**
* Call {@link android.content.Intent#getByteArrayExtra(String)} with {@link #RESULT_BYTES}
* to get a {@code byte[]} of raw bytes in the barcode, if available.
*/
public static final String RESULT_BYTES = "SCAN_RESULT_BYTES";
/**
* Key for the value of {@link com.google.zxing.ResultMetadataType#ORIENTATION}, if available.
* Call {@link android.content.Intent#getIntArrayExtra(String)} with {@link #RESULT_ORIENTATION}.
*/
public static final String RESULT_ORIENTATION = "SCAN_RESULT_ORIENTATION";
/**
* Key for the value of {@link com.google.zxing.ResultMetadataType#ERROR_CORRECTION_LEVEL}, if available.
* Call {@link android.content.Intent#getStringExtra(String)} with {@link #RESULT_ERROR_CORRECTION_LEVEL}.
*/
public static final String RESULT_ERROR_CORRECTION_LEVEL = "SCAN_RESULT_ERROR_CORRECTION_LEVEL";
/**
* Prefix for keys that map to the values of {@link com.google.zxing.ResultMetadataType#BYTE_SEGMENTS},
* if available. The actual values will be set under a series of keys formed by adding 0, 1, 2, ...
* to this prefix. So the first byte segment is under key "SCAN_RESULT_BYTE_SEGMENTS_0" for example.
* Call {@link android.content.Intent#getByteArrayExtra(String)} with these keys.
*/
public static final String RESULT_BYTE_SEGMENTS_PREFIX = "SCAN_RESULT_BYTE_SEGMENTS_";
/**
* Setting this to false will not save scanned codes in the history. Specified as a {@code boolean}.
*/
public static final String SAVE_HISTORY = "SAVE_HISTORY";
private Scan() {
}
}
public static final class History {
public static final String ITEM_NUMBER = "ITEM_NUMBER";
private History() {
}
}
public static final class Encode {
/**
* Send this intent to encode a piece of data as a QR code and display it full screen, so
* that another person can scan the barcode from your screen.
*/
public static final String ACTION = "com.google.zxing.client.android.ENCODE";
/**
* The data to encode. Use {@link android.content.Intent#putExtra(String, String)} or
* {@link android.content.Intent#putExtra(String, android.os.Bundle)},
* depending on the type and format specified. Non-QR Code formats should
* just use a String here. For QR Code, see Contents for details.
*/
public static final String DATA = "ENCODE_DATA";
/**
* The type of data being supplied if the format is QR Code. Use
* {@link android.content.Intent#putExtra(String, String)} with one of {@link Contents.Type}.
*/
public static final String TYPE = "ENCODE_TYPE";
/**
* The barcode format to be displayed. If this isn't specified or is blank,
* it defaults to QR Code. Use {@link android.content.Intent#putExtra(String, String)}, where
* format is one of {@link com.google.zxing.BarcodeFormat}.
*/
public static final String FORMAT = "ENCODE_FORMAT";
/**
* Normally the contents of the barcode are displayed to the user in a TextView. Setting this
* boolean to false will hide that TextView, showing only the encode barcode.
*/
public static final String SHOW_CONTENTS = "ENCODE_SHOW_CONTENTS";
private Encode() {
}
}
public static final class SearchBookContents {
/**
* Use Google Book Search to search the contents of the book provided.
*/
public static final String ACTION = "com.google.zxing.client.android.SEARCH_BOOK_CONTENTS";
/**
* The book to search, identified by ISBN number.
*/
public static final String ISBN = "ISBN";
/**
* An optional field which is the text to search for.
*/
public static final String QUERY = "QUERY";
private SearchBookContents() {
}
}
public static final class WifiConnect {
/**
* Internal intent used to trigger connection to a wi-fi network.
*/
public static final String ACTION = "com.google.zxing.client.android.WIFI_CONNECT";
/**
* The network to connect to, all the configuration provided here.
*/
public static final String SSID = "SSID";
/**
* The network to connect to, all the configuration provided here.
*/
public static final String TYPE = "TYPE";
/**
* The network to connect to, all the configuration provided here.
*/
public static final String PASSWORD = "PASSWORD";
private WifiConnect() {
}
}
public static final class Share {
/**
* Give the user a choice of items to encode as a barcode, then render it as a QR Code and
* display onscreen for a friend to scan with their phone.
*/
public static final String ACTION = "com.google.zxing.client.android.SHARE";
private Share() {
}
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/Intents.java
|
Java
|
epl
| 9,639
|
/*
* Copyright (C) 2008 ZXing authors
*
* 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 com.google.zxing.client.android;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
import com.google.zxing.ResultPointCallback;
import com.google.zxing.client.android.DecodeHandler.IHandleDecoding;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.util.Log;
import java.util.Collection;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
/**
* This thread does all the heavy lifting of decoding the images.
*
* @author dswitkin@google.com (Daniel Switkin)
*/
final class DecodeThread extends Thread {
public static final String BARCODE_BITMAP = "barcode_bitmap";
public static final String BARCODE_SCALED_FACTOR = "barcode_scaled_factor";
private final IHandleDecoding activity;
private final Map<DecodeHintType,Object> hints;
private Handler handler;
private final CountDownLatch handlerInitLatch;
DecodeThread(IHandleDecoding activity,
Collection<BarcodeFormat> decodeFormats,
Map<DecodeHintType,?> baseHints,
String characterSet,
ResultPointCallback resultPointCallback) {
this.activity = activity;
handlerInitLatch = new CountDownLatch(1);
hints = new EnumMap<DecodeHintType,Object>(DecodeHintType.class);
if (baseHints != null) {
hints.putAll(baseHints);
}
// The prefs can't change while the thread is running, so pick them up once here.
if (decodeFormats == null || decodeFormats.isEmpty()) {
decodeFormats = EnumSet.noneOf(BarcodeFormat.class);
decodeFormats.addAll(DecodeFormatManager.QR_CODE_FORMATS);
}
hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
if (characterSet != null) {
hints.put(DecodeHintType.CHARACTER_SET, characterSet);
}
hints.put(DecodeHintType.NEED_RESULT_POINT_CALLBACK, resultPointCallback);
Log.i("DecodeThread", "Hints: " + hints);
}
Handler getHandler() {
try {
handlerInitLatch.await();
} catch (InterruptedException ie) {
// continue?
}
return handler;
}
@Override
public void run() {
Looper.prepare();
handler = new DecodeHandler(activity, hints);
handlerInitLatch.countDown();
Looper.loop();
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/DecodeThread.java
|
Java
|
epl
| 2,982
|
/*
* Copyright (C) 2008 ZXing authors
*
* 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 com.google.zxing.client.android;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
import com.google.zxing.Result;
import com.google.zxing.ResultMetadataType;
import com.google.zxing.ResultPoint;
import com.google.zxing.client.android.camera.CameraManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.ClipboardManager;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.EnumSet;
import java.util.Map;
import java.util.Set;
/**
* This activity opens the camera and does the actual scanning on a background thread. It draws a
* viewfinder to help the user place the barcode correctly, shows feedback as the image processing
* is happening, and then overlays the results when a scan is successful.
*
* @author dswitkin@google.com (Daniel Switkin)
* @author Sean Owen
*/
public final class CaptureActivity extends Activity implements SurfaceHolder.Callback, DecodeActivityHandler.IHandleActivity {
private static final String TAG = CaptureActivity.class.getSimpleName();
private static final long DEFAULT_INTENT_RESULT_DURATION_MS = 1500L;
private static final long BULK_MODE_SCAN_DELAY_MS = 1000L;
private static final String PACKAGE_NAME = "com.google.zxing.client.android";
private static final String PRODUCT_SEARCH_URL_PREFIX = "http://www.google";
private static final String PRODUCT_SEARCH_URL_SUFFIX = "/m/products/scan";
private static final String[] ZXING_URLS = { "http://zxing.appspot.com/scan", "zxing://scan/" };
public static final int HISTORY_REQUEST_CODE = 0x0000bacc;
private static final Set<ResultMetadataType> DISPLAYABLE_METADATA_TYPES =
EnumSet.of(ResultMetadataType.ISSUE_NUMBER,
ResultMetadataType.SUGGESTED_PRICE,
ResultMetadataType.ERROR_CORRECTION_LEVEL,
ResultMetadataType.POSSIBLE_COUNTRY);
private CameraManager cameraManager;
private DecodeActivityHandler handler;
private Result savedResultToShow;
private ViewfinderView viewfinderView;
private TextView statusView;
private View resultView;
private Result lastResult;
private boolean hasSurface;
private IntentSource source;
private String sourceUrl;
private Collection<BarcodeFormat> decodeFormats;
private Map<DecodeHintType,?> decodeHints;
private String characterSet;
private InactivityTimer inactivityTimer;
private BeepManager beepManager;
private AmbientLightManager ambientLightManager;
@Override
public ViewfinderView getViewfinderView() {
return viewfinderView;
}
public Handler getHandler() {
return handler;
}
@Override
public CameraManager getCameraManager() {
return cameraManager;
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
hasSurface = false;
inactivityTimer = new InactivityTimer(this);
beepManager = new BeepManager(this, getBeepId());
ambientLightManager = new AmbientLightManager(this);
}
protected int getBeepId() {
return 0;
}
protected int getViewFinderViewId() {
return 0;
}
protected int getResultViewId() {
return 0;
}
protected int getStatusViewId() {
return 0;
}
protected int getSurfaceViewId() {
return 0;
}
@Override
protected void onResume() {
super.onResume();
// CameraManager must be initialized here, not in onCreate(). This is necessary because we don't
// want to open the camera driver and measure the screen size if we're going to show the help on
// first launch. That led to bugs where the scanning rectangle was the wrong size and partially
// off screen.
cameraManager = new CameraManager(getApplication());
viewfinderView = (ViewfinderView) findViewById(getViewFinderViewId());
viewfinderView.setCameraManager(cameraManager);
resultView = findViewById(getResultViewId());
statusView = (TextView) findViewById(getStatusViewId());
handler = null;
lastResult = null;
resetStatusView();
SurfaceView surfaceView = (SurfaceView) findViewById(getSurfaceViewId());
SurfaceHolder surfaceHolder = surfaceView.getHolder();
if (hasSurface) {
// The activity was paused but not stopped, so the surface still exists. Therefore
// surfaceCreated() won't be called, so init the camera here.
initCamera(surfaceHolder);
} else {
// Install the callback and wait for surfaceCreated() to init the camera.
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
beepManager.updateConfig();
ambientLightManager.start(cameraManager);
inactivityTimer.onResume();
Intent intent = getIntent();
source = IntentSource.NONE;
decodeFormats = null;
characterSet = null;
if (intent != null) {
String action = intent.getAction();
String dataString = intent.getDataString();
if (Intents.Scan.ACTION.equals(action)) {
// Scan the formats the intent requested, and return the result to the calling activity.
source = IntentSource.NATIVE_APP_INTENT;
decodeFormats = DecodeFormatManager.parseDecodeFormats(intent);
decodeHints = DecodeHintManager.parseDecodeHints(intent);
if (intent.hasExtra(Intents.Scan.WIDTH) && intent.hasExtra(Intents.Scan.HEIGHT)) {
int width = intent.getIntExtra(Intents.Scan.WIDTH, 0);
int height = intent.getIntExtra(Intents.Scan.HEIGHT, 0);
if (width > 0 && height > 0) {
cameraManager.setManualFramingRect(width, height);
}
}
String customPromptMessage = intent.getStringExtra(Intents.Scan.PROMPT_MESSAGE);
if (customPromptMessage != null) {
statusView.setText(customPromptMessage);
}
} else if (dataString != null &&
dataString.contains(PRODUCT_SEARCH_URL_PREFIX) &&
dataString.contains(PRODUCT_SEARCH_URL_SUFFIX)) {
// Scan only products and send the result to mobile Product Search.
source = IntentSource.PRODUCT_SEARCH_LINK;
sourceUrl = dataString;
decodeFormats = DecodeFormatManager.PRODUCT_FORMATS;
} else if (isZXingURL(dataString)) {
// Scan formats requested in query string (all formats if none specified).
// If a return URL is specified, send the results there. Otherwise, handle it ourselves.
source = IntentSource.ZXING_LINK;
sourceUrl = dataString;
Uri inputUri = Uri.parse(dataString);
decodeFormats = DecodeFormatManager.parseDecodeFormats(inputUri);
// Allow a sub-set of the hints to be specified by the caller.
decodeHints = DecodeHintManager.parseDecodeHints(inputUri);
}
characterSet = intent.getStringExtra(Intents.Scan.CHARACTER_SET);
}
}
private static boolean isZXingURL(String dataString) {
if (dataString == null) {
return false;
}
for (String url : ZXING_URLS) {
if (dataString.startsWith(url)) {
return true;
}
}
return false;
}
@Override
protected void onPause() {
if (handler != null) {
handler.quitSynchronously();
handler = null;
}
inactivityTimer.onPause();
ambientLightManager.stop();
cameraManager.closeDriver();
if (!hasSurface) {
SurfaceView surfaceView = (SurfaceView) findViewById(getSurfaceViewId());
SurfaceHolder surfaceHolder = surfaceView.getHolder();
surfaceHolder.removeCallback(this);
}
super.onPause();
}
@Override
protected void onDestroy() {
inactivityTimer.shutdown();
super.onDestroy();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (source == IntentSource.NATIVE_APP_INTENT) {
setResult(RESULT_CANCELED);
finish();
return true;
}
if ((source == IntentSource.NONE || source == IntentSource.ZXING_LINK) && lastResult != null) {
restartPreviewAfterDelay(0L);
return true;
}
break;
case KeyEvent.KEYCODE_FOCUS:
case KeyEvent.KEYCODE_CAMERA:
// Handle these events so they don't launch the Camera app
return true;
// Use volume up/down to turn on light
case KeyEvent.KEYCODE_VOLUME_DOWN:
cameraManager.setTorch(false);
return true;
case KeyEvent.KEYCODE_VOLUME_UP:
cameraManager.setTorch(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
}
private void decodeOrStoreSavedBitmap(Bitmap bitmap, Result result) {
// Bitmap isn't used yet -- will be used soon
if (handler == null) {
savedResultToShow = result;
} else {
if (result != null) {
savedResultToShow = result;
}
if (savedResultToShow != null) {
Message message = Message.obtain(handler, Action.ACTION_DECODE, savedResultToShow);
handler.sendMessage(message);
}
savedResultToShow = null;
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (holder == null) {
Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!");
}
if (!hasSurface) {
hasSurface = true;
initCamera(holder);
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
hasSurface = false;
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
/**
* A valid barcode has been found, so give an indication of success and show the results.
*
* @param rawResult The contents of the barcode.
* @param scaleFactor amount by which thumbnail was scaled
* @param barcode A greyscale bitmap of the camera data which was decoded.
*/
@Override
public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) {
inactivityTimer.onActivity();
lastResult = rawResult;
boolean fromLiveScan = barcode != null;
if (fromLiveScan) {
// Then not from history, so beep/vibrate and we have an image to draw on
beepManager.playBeepSoundAndVibrate();
drawResultPoints(barcode, scaleFactor, rawResult);
}
switch (source) {
case NATIVE_APP_INTENT:
case PRODUCT_SEARCH_LINK:
handleDecodeExternally(rawResult, lastResult, barcode);
break;
case ZXING_LINK:
handleDecodeExternally(rawResult, lastResult, barcode);
break;
case NONE:
if (fromLiveScan) {
// Wait a moment or else it will scan the same barcode continuously about 3 times
restartPreviewAfterDelay(BULK_MODE_SCAN_DELAY_MS);
} else {
handleDecodeInternally(rawResult, lastResult, barcode);
}
break;
}
}
/**
* Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
*
* @param barcode A bitmap of the captured image.
* @param scaleFactor amount by which thumbnail was scaled
* @param rawResult The decoded results which contains the points to draw.
*/
private void drawResultPoints(Bitmap barcode, float scaleFactor, Result rawResult) {
ResultPoint[] points = rawResult.getResultPoints();
if (points != null && points.length > 0) {
Canvas canvas = new Canvas(barcode);
Paint paint = new Paint();
paint.setColor(Color.RED);
if (points.length == 2) {
paint.setStrokeWidth(4.0f);
drawLine(canvas, paint, points[0], points[1], scaleFactor);
} else if (points.length == 4 &&
(rawResult.getBarcodeFormat() == BarcodeFormat.UPC_A ||
rawResult.getBarcodeFormat() == BarcodeFormat.EAN_13)) {
// Hacky special case -- draw two lines, for the barcode and metadata
drawLine(canvas, paint, points[0], points[1], scaleFactor);
drawLine(canvas, paint, points[2], points[3], scaleFactor);
} else {
paint.setStrokeWidth(10.0f);
for (ResultPoint point : points) {
canvas.drawPoint(scaleFactor * point.getX(), scaleFactor * point.getY(), paint);
}
}
}
}
private static void drawLine(Canvas canvas, Paint paint, ResultPoint a, ResultPoint b, float scaleFactor) {
if (a != null && b != null) {
canvas.drawLine(scaleFactor * a.getX(),
scaleFactor * a.getY(),
scaleFactor * b.getX(),
scaleFactor * b.getY(),
paint);
}
}
// Put up our own UI for how to handle the decoded contents.
private void handleDecodeInternally(Result rawResult, Result result, Bitmap barcode) {
//TODO Success!
}
// Briefly show the contents of the barcode, then handle the result outside Barcode Scanner.
private void handleDecodeExternally(Result rawResult, Result result, Bitmap barcode) {
//TODO Success!
}
private void sendReplyMessage(int id, Object arg, long delayMS) {
Message message = Message.obtain(handler, id, arg);
if (delayMS > 0L) {
handler.sendMessageDelayed(message, delayMS);
} else {
handler.sendMessage(message);
}
}
private void initCamera(SurfaceHolder surfaceHolder) {
if (surfaceHolder == null) {
throw new IllegalStateException("No SurfaceHolder provided");
}
if (cameraManager.isOpen()) {
Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?");
return;
}
try {
cameraManager.openDriver(surfaceHolder);
// Creating the handler starts the preview, which can also throw a RuntimeException.
if (handler == null) {
handler = new DecodeActivityHandler(this, decodeFormats, decodeHints, characterSet, cameraManager);
}
decodeOrStoreSavedBitmap(null, null);
} catch (IOException ioe) {
Log.w(TAG, ioe);
finish();
} catch (RuntimeException e) {
// Barcode Scanner has seen crashes in the wild of this variety:
// java.?lang.?RuntimeException: Fail to connect to camera service
Log.w(TAG, "Unexpected error initializing camera", e);
finish();
}
}
public void restartPreviewAfterDelay(long delayMS) {
if (handler != null) {
handler.sendEmptyMessageDelayed(Action.ACTION_RESTART_PREVIEW, delayMS);
}
resetStatusView();
}
private void resetStatusView() {
resultView.setVisibility(View.GONE);
statusView.setVisibility(View.VISIBLE);
viewfinderView.setVisibility(View.VISIBLE);
lastResult = null;
}
@Override
public void drawViewfinder() {
viewfinderView.drawViewfinder();
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/CaptureActivity.java
|
Java
|
epl
| 16,533
|
/*
* Copyright (C) 2012 ZXing authors
*
* 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 com.google.zxing.client.android.common.executor;
import android.os.AsyncTask;
public interface AsyncTaskExecInterface {
<T> void execute(AsyncTask<T,?,?> task, T... args);
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/common/executor/AsyncTaskExecInterface.java
|
Java
|
epl
| 791
|
/*
* Copyright (C) 2012 ZXing authors
*
* 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 com.google.zxing.client.android.common.executor;
import android.os.AsyncTask;
/**
* Before Honeycomb, {@link AsyncTask} uses parallel execution by default, which is desired. Good thing
* too since there is no API to request otherwise.
*/
public final class DefaultAsyncTaskExecInterface implements AsyncTaskExecInterface {
@Override
public <T> void execute(AsyncTask<T,?,?> task, T... args) {
task.execute(args);
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/common/executor/DefaultAsyncTaskExecInterface.java
|
Java
|
epl
| 1,045
|
/*
* Copyright (C) 2012 ZXing authors
*
* 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 com.google.zxing.client.android.common.executor;
import com.google.zxing.client.android.common.PlatformSupportManager;
public final class AsyncTaskExecManager extends PlatformSupportManager<AsyncTaskExecInterface> {
public AsyncTaskExecManager() {
super(AsyncTaskExecInterface.class, new DefaultAsyncTaskExecInterface());
addImplementationClass(11, "com.google.zxing.client.android.common.executor.HoneycombAsyncTaskExecInterface");
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/common/executor/AsyncTaskExecManager.java
|
Java
|
epl
| 1,064
|
/*
* Copyright (C) 2012 ZXing authors
*
* 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 com.google.zxing.client.android.common.executor;
import android.annotation.TargetApi;
import android.os.AsyncTask;
/**
* On Honeycomb and later, {@link AsyncTask} returns to serial execution by default which is undesirable.
* This calls Honeycomb-only APIs to request parallel execution.
*/
@TargetApi(11)
public final class HoneycombAsyncTaskExecInterface implements AsyncTaskExecInterface {
@Override
public <T> void execute(AsyncTask<T,?,?> task, T... args) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, args);
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/common/executor/HoneycombAsyncTaskExecInterface.java
|
Java
|
epl
| 1,157
|
/*
* Copyright (C) 2012 ZXing authors
*
* 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 com.google.zxing.client.android.common;
import android.os.Build;
import android.util.Log;
import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* <p>Sometimes the application wants to access advanced functionality exposed by Android APIs that are only available
* in later versions of the platform. While {@code Build.VERSION} can be used to determine the device's API level
* and alter behavior accordingly, and it is possible to write code that uses both old and new APIs selectively,
* such code would fail to load on older devices that do not have the new API methods.</p>
*
* <p>It is necessary to only load classes that use newer APIs than the device may support after the app
* has checked the API level. This requires reflection, loading one of several implementations based on the
* API level.</p>
*
* <p>This class manages that process. Subclasses of this class manage access to implementations of a given interface
* in an API-level-aware way. Subclasses implementation classes <em>by name</em>, and the minimum API level that
* the implementation is compatible with. They also provide a default implementation.</p>
*
* <p>At runtime an appropriate implementation is then chosen, instantiated and returned from {@link #build()}.</p>
*
* @param <T> the interface which managed implementations implement
*/
public abstract class PlatformSupportManager<T> {
private static final String TAG = PlatformSupportManager.class.getSimpleName();
private final Class<T> managedInterface;
private final T defaultImplementation;
private final SortedMap<Integer,String> implementations;
protected PlatformSupportManager(Class<T> managedInterface, T defaultImplementation) {
if (!managedInterface.isInterface()) {
throw new IllegalArgumentException();
}
if (!managedInterface.isInstance(defaultImplementation)) {
throw new IllegalArgumentException();
}
this.managedInterface = managedInterface;
this.defaultImplementation = defaultImplementation;
this.implementations = new TreeMap<Integer,String>(Collections.reverseOrder());
}
protected final void addImplementationClass(int minVersion, String className) {
implementations.put(minVersion, className);
}
public final T build() {
for (Integer minVersion : implementations.keySet()) {
if (Build.VERSION.SDK_INT >= minVersion) {
String className = implementations.get(minVersion);
try {
Class<? extends T> clazz = Class.forName(className).asSubclass(managedInterface);
Log.i(TAG, "Using implementation " + clazz + " of " + managedInterface + " for SDK " + minVersion);
return clazz.getConstructor().newInstance();
} catch (ClassNotFoundException cnfe) {
Log.w(TAG, cnfe);
} catch (IllegalAccessException iae) {
Log.w(TAG, iae);
} catch (InstantiationException ie) {
Log.w(TAG, ie);
} catch (NoSuchMethodException nsme) {
Log.w(TAG, nsme);
} catch (InvocationTargetException ite) {
Log.w(TAG, ite);
}
}
}
Log.i(TAG, "Using default implementation " + defaultImplementation.getClass() + " of " + managedInterface);
return defaultImplementation;
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/android/common/PlatformSupportManager.java
|
Java
|
epl
| 3,954
|
/*
* Copyright 2008 ZXing authors
*
* 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 com.google.zxing.client.result;
import com.google.zxing.Result;
/**
* Parses a "tel:" URI result, which specifies a phone number.
*
* @author Sean Owen
*/
public final class TelResultParser extends ResultParser {
@Override
public TelParsedResult parse(Result result) {
String rawText = getMassagedText(result);
if (!rawText.startsWith("tel:") && !rawText.startsWith("TEL:")) {
return null;
}
// Normalize "TEL:" to "tel:"
String telURI = rawText.startsWith("TEL:") ? "tel:" + rawText.substring(4) : rawText;
// Drop tel, query portion
int queryStart = rawText.indexOf('?', 4);
String number = queryStart < 0 ? rawText.substring(4) : rawText.substring(4, queryStart);
return new TelParsedResult(number, telURI, null);
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/result/TelResultParser.java
|
Java
|
epl
| 1,383
|
/*
* Copyright 2008 ZXing authors
*
* 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 com.google.zxing.client.result;
/**
* @author Sean Owen
*/
public final class TelParsedResult extends ParsedResult {
private final String number;
private final String telURI;
private final String title;
public TelParsedResult(String number, String telURI, String title) {
super(ParsedResultType.TEL);
this.number = number;
this.telURI = telURI;
this.title = title;
}
public String getNumber() {
return number;
}
public String getTelURI() {
return telURI;
}
public String getTitle() {
return title;
}
@Override
public String getDisplayResult() {
StringBuilder result = new StringBuilder(20);
maybeAppend(number, result);
maybeAppend(title, result);
return result.toString();
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/result/TelParsedResult.java
|
Java
|
epl
| 1,366
|
/*
* Copyright 2007 ZXing authors
*
* 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 com.google.zxing.client.result;
/**
* A simple result type encapsulating a string that has no further
* interpretation.
*
* @author Sean Owen
*/
public final class TextParsedResult extends ParsedResult {
private final String text;
private final String language;
public TextParsedResult(String text, String language) {
super(ParsedResultType.TEXT);
this.text = text;
this.language = language;
}
public String getText() {
return text;
}
public String getLanguage() {
return language;
}
@Override
public String getDisplayResult() {
return text;
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/result/TextParsedResult.java
|
Java
|
epl
| 1,212
|
/*
* Copyright (C) 2010 ZXing authors
*
* 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.
*/
/*
* These authors would like to acknowledge the Spanish Ministry of Industry,
* Tourism and Trade, for the support in the project TSI020301-2008-2
* "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled
* Mobile Dynamic Environments", led by Treelogic
* ( http://www.treelogic.com/ ):
*
* http://www.piramidepse.com/
*/
package com.google.zxing.client.result;
import java.util.HashMap;
import java.util.Map;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
/**
* Parses strings of digits that represent a RSS Extended code.
*
* @author Antonio Manuel Benjumea Conde, Servinform, S.A.
* @author Agustín Delgado, Servinform, S.A.
*/
public final class ExpandedProductResultParser extends ResultParser {
@Override
public ExpandedProductParsedResult parse(Result result) {
BarcodeFormat format = result.getBarcodeFormat();
if (format != BarcodeFormat.RSS_EXPANDED) {
// ExtendedProductParsedResult NOT created. Not a RSS Expanded barcode
return null;
}
// Really neither of these should happen:
String rawText = getMassagedText(result);
if (rawText == null) {
// ExtendedProductParsedResult NOT created. Input text is NULL
return null;
}
String productID = null;
String sscc = null;
String lotNumber = null;
String productionDate = null;
String packagingDate = null;
String bestBeforeDate = null;
String expirationDate = null;
String weight = null;
String weightType = null;
String weightIncrement = null;
String price = null;
String priceIncrement = null;
String priceCurrency = null;
Map<String,String> uncommonAIs = new HashMap<String,String>();
int i = 0;
while (i < rawText.length()) {
String ai = findAIvalue(i, rawText);
if (ai == null) {
// Error. Code doesn't match with RSS expanded pattern
// ExtendedProductParsedResult NOT created. Not match with RSS Expanded pattern
return null;
}
i += ai.length() + 2;
String value = findValue(i, rawText);
i += value.length();
if ("00".equals(ai)) {
sscc = value;
} else if ("01".equals(ai)) {
productID = value;
} else if ("10".equals(ai)) {
lotNumber = value;
} else if ("11".equals(ai)) {
productionDate = value;
} else if ("13".equals(ai)) {
packagingDate = value;
} else if ("15".equals(ai)) {
bestBeforeDate = value;
} else if ("17".equals(ai)) {
expirationDate = value;
} else if ("3100".equals(ai) || "3101".equals(ai)
|| "3102".equals(ai) || "3103".equals(ai)
|| "3104".equals(ai) || "3105".equals(ai)
|| "3106".equals(ai) || "3107".equals(ai)
|| "3108".equals(ai) || "3109".equals(ai)) {
weight = value;
weightType = ExpandedProductParsedResult.KILOGRAM;
weightIncrement = ai.substring(3);
} else if ("3200".equals(ai) || "3201".equals(ai)
|| "3202".equals(ai) || "3203".equals(ai)
|| "3204".equals(ai) || "3205".equals(ai)
|| "3206".equals(ai) || "3207".equals(ai)
|| "3208".equals(ai) || "3209".equals(ai)) {
weight = value;
weightType = ExpandedProductParsedResult.POUND;
weightIncrement = ai.substring(3);
} else if ("3920".equals(ai) || "3921".equals(ai)
|| "3922".equals(ai) || "3923".equals(ai)) {
price = value;
priceIncrement = ai.substring(3);
} else if ("3930".equals(ai) || "3931".equals(ai)
|| "3932".equals(ai) || "3933".equals(ai)) {
if (value.length() < 4) {
// The value must have more of 3 symbols (3 for currency and
// 1 at least for the price)
// ExtendedProductParsedResult NOT created. Not match with RSS Expanded pattern
return null;
}
price = value.substring(3);
priceCurrency = value.substring(0, 3);
priceIncrement = ai.substring(3);
} else {
// No match with common AIs
uncommonAIs.put(ai, value);
}
}
return new ExpandedProductParsedResult(rawText,
productID,
sscc,
lotNumber,
productionDate,
packagingDate,
bestBeforeDate,
expirationDate,
weight,
weightType,
weightIncrement,
price,
priceIncrement,
priceCurrency,
uncommonAIs);
}
private static String findAIvalue(int i, String rawText) {
char c = rawText.charAt(i);
// First character must be a open parenthesis.If not, ERROR
if (c != '(') {
return null;
}
String rawTextAux = rawText.substring(i + 1);
StringBuilder buf = new StringBuilder();
for (int index = 0; index < rawTextAux.length(); index++) {
char currentChar = rawTextAux.charAt(index);
if (currentChar == ')') {
return buf.toString();
} else if (currentChar >= '0' && currentChar <= '9') {
buf.append(currentChar);
} else {
return null;
}
}
return buf.toString();
}
private static String findValue(int i, String rawText) {
StringBuilder buf = new StringBuilder();
String rawTextAux = rawText.substring(i);
for (int index = 0; index < rawTextAux.length(); index++) {
char c = rawTextAux.charAt(index);
if (c == '(') {
// We look for a new AI. If it doesn't exist (ERROR), we coninue
// with the iteration
if (findAIvalue(index, rawTextAux) == null) {
buf.append('(');
} else {
break;
}
} else {
buf.append(c);
}
}
return buf.toString();
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/result/ExpandedProductResultParser.java
|
Java
|
epl
| 6,815
|
/*
* Copyright 2007 ZXing authors
*
* 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 com.google.zxing.client.result;
/**
* <p>Abstract class representing the result of decoding a barcode, as more than
* a String -- as some type of structured data. This might be a subclass which represents
* a URL, or an e-mail address. {@link ResultParser#parseResult(com.google.zxing.Result)} will turn a raw
* decoded string into the most appropriate type of structured representation.</p>
*
* <p>Thanks to Jeff Griffin for proposing rewrite of these classes that relies less
* on exception-based mechanisms during parsing.</p>
*
* @author Sean Owen
*/
public abstract class ParsedResult {
private final ParsedResultType type;
protected ParsedResult(ParsedResultType type) {
this.type = type;
}
public final ParsedResultType getType() {
return type;
}
public abstract String getDisplayResult();
@Override
public final String toString() {
return getDisplayResult();
}
public static void maybeAppend(String value, StringBuilder result) {
if (value != null && value.length() > 0) {
// Don't add a newline before the first value
if (result.length() > 0) {
result.append('\n');
}
result.append(value);
}
}
public static void maybeAppend(String[] values, StringBuilder result) {
if (values != null) {
for (String value : values) {
maybeAppend(value, result);
}
}
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/result/ParsedResult.java
|
Java
|
epl
| 1,995
|
/*
* Copyright 2007 ZXing authors
*
* 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 com.google.zxing.client.result;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.google.zxing.oned.UPCEReader;
/**
* Parses strings of digits that represent a UPC code.
*
* @author dswitkin@google.com (Daniel Switkin)
*/
public final class ProductResultParser extends ResultParser {
// Treat all UPC and EAN variants as UPCs, in the sense that they are all product barcodes.
@Override
public ProductParsedResult parse(Result result) {
BarcodeFormat format = result.getBarcodeFormat();
if (!(format == BarcodeFormat.UPC_A || format == BarcodeFormat.UPC_E ||
format == BarcodeFormat.EAN_8 || format == BarcodeFormat.EAN_13)) {
return null;
}
String rawText = getMassagedText(result);
int length = rawText.length();
for (int x = 0; x < length; x++) {
char c = rawText.charAt(x);
if (c < '0' || c > '9') {
return null;
}
}
// Not actually checking the checksum again here
String normalizedProductID;
// Expand UPC-E for purposes of searching
if (format == BarcodeFormat.UPC_E) {
normalizedProductID = UPCEReader.convertUPCEtoUPCA(rawText);
} else {
normalizedProductID = rawText;
}
return new ProductParsedResult(rawText, normalizedProductID);
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/result/ProductResultParser.java
|
Java
|
epl
| 1,916
|
/*
* Copyright 2007 ZXing authors
*
* 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 com.google.zxing.client.result;
/**
* @author Sean Owen
*/
public final class AddressBookParsedResult extends ParsedResult {
private final String[] names;
private final String[] nicknames;
private final String pronunciation;
private final String[] phoneNumbers;
private final String[] phoneTypes;
private final String[] emails;
private final String[] emailTypes;
private final String instantMessenger;
private final String note;
private final String[] addresses;
private final String[] addressTypes;
private final String org;
private final String birthday;
private final String title;
private final String[] urls;
private final String[] geo;
public AddressBookParsedResult(String[] names,
String[] phoneNumbers,
String[] phoneTypes,
String[] emails,
String[] emailTypes,
String[] addresses,
String[] addressTypes) {
this(names,
null,
null,
phoneNumbers,
phoneTypes,
emails,
emailTypes,
null,
null,
addresses,
addressTypes,
null,
null,
null,
null,
null);
}
public AddressBookParsedResult(String[] names,
String[] nicknames,
String pronunciation,
String[] phoneNumbers,
String[] phoneTypes,
String[] emails,
String[] emailTypes,
String instantMessenger,
String note,
String[] addresses,
String[] addressTypes,
String org,
String birthday,
String title,
String[] urls,
String[] geo) {
super(ParsedResultType.ADDRESSBOOK);
this.names = names;
this.nicknames = nicknames;
this.pronunciation = pronunciation;
this.phoneNumbers = phoneNumbers;
this.phoneTypes = phoneTypes;
this.emails = emails;
this.emailTypes = emailTypes;
this.instantMessenger = instantMessenger;
this.note = note;
this.addresses = addresses;
this.addressTypes = addressTypes;
this.org = org;
this.birthday = birthday;
this.title = title;
this.urls = urls;
this.geo = geo;
}
public String[] getNames() {
return names;
}
public String[] getNicknames() {
return nicknames;
}
/**
* In Japanese, the name is written in kanji, which can have multiple readings. Therefore a hint
* is often provided, called furigana, which spells the name phonetically.
*
* @return The pronunciation of the getNames() field, often in hiragana or katakana.
*/
public String getPronunciation() {
return pronunciation;
}
public String[] getPhoneNumbers() {
return phoneNumbers;
}
/**
* @return optional descriptions of the type of each phone number. It could be like "HOME", but,
* there is no guaranteed or standard format.
*/
public String[] getPhoneTypes() {
return phoneTypes;
}
public String[] getEmails() {
return emails;
}
/**
* @return optional descriptions of the type of each e-mail. It could be like "WORK", but,
* there is no guaranteed or standard format.
*/
public String[] getEmailTypes() {
return emailTypes;
}
public String getInstantMessenger() {
return instantMessenger;
}
public String getNote() {
return note;
}
public String[] getAddresses() {
return addresses;
}
/**
* @return optional descriptions of the type of each e-mail. It could be like "WORK", but,
* there is no guaranteed or standard format.
*/
public String[] getAddressTypes() {
return addressTypes;
}
public String getTitle() {
return title;
}
public String getOrg() {
return org;
}
public String[] getURLs() {
return urls;
}
/**
* @return birthday formatted as yyyyMMdd (e.g. 19780917)
*/
public String getBirthday() {
return birthday;
}
/**
* @return a location as a latitude/longitude pair
*/
public String[] getGeo() {
return geo;
}
@Override
public String getDisplayResult() {
StringBuilder result = new StringBuilder(100);
maybeAppend(names, result);
maybeAppend(nicknames, result);
maybeAppend(pronunciation, result);
maybeAppend(title, result);
maybeAppend(org, result);
maybeAppend(addresses, result);
maybeAppend(phoneNumbers, result);
maybeAppend(emails, result);
maybeAppend(instantMessenger, result);
maybeAppend(urls, result);
maybeAppend(birthday, result);
maybeAppend(geo, result);
maybeAppend(note, result);
return result.toString();
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/result/AddressBookParsedResult.java
|
Java
|
epl
| 5,715
|
/*
* Copyright 2007 ZXing authors
*
* 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 com.google.zxing.client.result;
/**
* @author dswitkin@google.com (Daniel Switkin)
*/
public final class ProductParsedResult extends ParsedResult {
private final String productID;
private final String normalizedProductID;
ProductParsedResult(String productID) {
this(productID, productID);
}
ProductParsedResult(String productID, String normalizedProductID) {
super(ParsedResultType.PRODUCT);
this.productID = productID;
this.normalizedProductID = normalizedProductID;
}
public String getProductID() {
return productID;
}
public String getNormalizedProductID() {
return normalizedProductID;
}
@Override
public String getDisplayResult() {
return productID;
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/result/ProductParsedResult.java
|
Java
|
epl
| 1,331
|
/*
* Copyright 2008 ZXing authors
*
* 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 com.google.zxing.client.result;
import com.google.zxing.Result;
import java.util.ArrayList;
import java.util.List;
/**
* Implements KDDI AU's address book format. See
* <a href="http://www.au.kddi.com/ezfactory/tec/two_dimensions/index.html">
* http://www.au.kddi.com/ezfactory/tec/two_dimensions/index.html</a>.
* (Thanks to Yuzo for translating!)
*
* @author Sean Owen
*/
public final class AddressBookAUResultParser extends ResultParser {
@Override
public AddressBookParsedResult parse(Result result) {
String rawText = getMassagedText(result);
// MEMORY is mandatory; seems like a decent indicator, as does end-of-record separator CR/LF
if (!rawText.contains("MEMORY") || !rawText.contains("\r\n")) {
return null;
}
// NAME1 and NAME2 have specific uses, namely written name and pronunciation, respectively.
// Therefore we treat them specially instead of as an array of names.
String name = matchSinglePrefixedField("NAME1:", rawText, '\r', true);
String pronunciation = matchSinglePrefixedField("NAME2:", rawText, '\r', true);
String[] phoneNumbers = matchMultipleValuePrefix("TEL", 3, rawText, true);
String[] emails = matchMultipleValuePrefix("MAIL", 3, rawText, true);
String note = matchSinglePrefixedField("MEMORY:", rawText, '\r', false);
String address = matchSinglePrefixedField("ADD:", rawText, '\r', true);
String[] addresses = address == null ? null : new String[] {address};
return new AddressBookParsedResult(maybeWrap(name),
null,
pronunciation,
phoneNumbers,
null,
emails,
null,
null,
note,
addresses,
null,
null,
null,
null,
null,
null);
}
private static String[] matchMultipleValuePrefix(String prefix,
int max,
String rawText,
boolean trim) {
List<String> values = null;
for (int i = 1; i <= max; i++) {
String value = matchSinglePrefixedField(prefix + i + ':', rawText, '\r', trim);
if (value == null) {
break;
}
if (values == null) {
values = new ArrayList<String>(max); // lazy init
}
values.add(value);
}
if (values == null) {
return null;
}
return values.toArray(new String[values.size()]);
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/result/AddressBookAUResultParser.java
|
Java
|
epl
| 3,538
|
/*
* Copyright 2007 ZXing authors
*
* 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 com.google.zxing.client.result;
import com.google.zxing.Result;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Tries to parse results that are a URI of some kind.
*
* @author Sean Owen
*/
public final class URIResultParser extends ResultParser {
private static final String ALPHANUM_PART = "[a-zA-Z0-9\\-]";
private static final Pattern URL_WITH_PROTOCOL_PATTERN = Pattern.compile("[a-zA-Z0-9]{2,}:");
private static final Pattern URL_WITHOUT_PROTOCOL_PATTERN = Pattern.compile(
'(' + ALPHANUM_PART + "+\\.)+" + ALPHANUM_PART + "{2,}" + // host name elements
"(:\\d{1,5})?" + // maybe port
"(/|\\?|$)"); // query, path or nothing
@Override
public URIParsedResult parse(Result result) {
String rawText = getMassagedText(result);
// We specifically handle the odd "URL" scheme here for simplicity and add "URI" for fun
// Assume anything starting this way really means to be a URI
if (rawText.startsWith("URL:") || rawText.startsWith("URI:")) {
return new URIParsedResult(rawText.substring(4).trim(), null);
}
rawText = rawText.trim();
return isBasicallyValidURI(rawText) ? new URIParsedResult(rawText, null) : null;
}
static boolean isBasicallyValidURI(String uri) {
if (uri.contains(" ")) {
// Quick hack check for a common case
return false;
}
Matcher m = URL_WITH_PROTOCOL_PATTERN.matcher(uri);
if (m.find() && m.start() == 0) { // match at start only
return true;
}
m = URL_WITHOUT_PROTOCOL_PATTERN.matcher(uri);
return m.find() && m.start() == 0;
}
}
|
zzdache
|
trunk/android/cc/CcCommon/sdk/com/google/zxing/client/result/URIResultParser.java
|
Java
|
epl
| 2,210
|