code
stringlengths
3
1.18M
language
stringclasses
1 value
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; public class PtpPropertyListItem { private String mTitle; private int mImage; private Object mValue; private int mNameId; public String getTitle() { return mTitle; } public void setTitle(String title) { mTitle = title; } public int getImage() { return mImage; } public void setImage(int image) { this.mImage = image; } public Object getValue(){ return mValue; } public void setValue(Object value){ mValue = value; } public int getNameId(){ return mNameId; } public void setNameId(int value){ mNameId = value; } public PtpPropertyListItem(){ } public PtpPropertyListItem(Object propValue, int propNameId, int propImgId){ mValue = propValue; mNameId = propNameId; mImage = propImgId; } public PtpPropertyListItem(String title) { mTitle = title; } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import java.util.Hashtable; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.PorterDuffColorFilter; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; public class BottomFragment extends DslrFragmentBase { private static final String TAG = "BottomFragment"; private RelativeLayout mBottomLayout; private ImageView mFullScreen, mFlashIndicator, mEvCompensationIndicator, mFlashCompensationIndicator, mLvLayoutSwitch; private TextView txtAperture, txtShutter, mSdcard1, mSdcard2, mAeLockStatus; private PorterDuffColorFilter mColorFilterGreen, mColorFilterRed; private ExposureIndicatorDisplay mExposureIndicator; private View.OnClickListener mSdcardClickListener = new View.OnClickListener() { public void onClick(View v) { Intent ipIntent = new Intent(getActivity(), DslrImageBrowserActivity.class); ipIntent.setAction(Intent.ACTION_VIEW); ipIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getActivity().startActivity(ipIntent); } }; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_bottom, container, false); mBottomLayout = (RelativeLayout)view.findViewById(R.id.bottom_layout); txtAperture = (TextView)view.findViewById(R.id.txt_aperture); txtAperture.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Log.d(TAG, "Aperture click"); DslrHelper.getInstance().showApertureDialog(getActivity()); //showApertureDialog(); } }); txtShutter = (TextView)view.findViewById(R.id.txt_shutter); txtShutter.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().showExposureTimeDialog(getActivity()); //showExposureTimeDialog(); } }); // mFlexibleProgram = (TextView)view.findViewById(R.id.flexibleprogram); // mExposureIndicateStatus = (TextView)view.findViewById(R.id.exposureindicatestatus); mFullScreen = (ImageView)view.findViewById(R.id.fullscreen); mLvLayoutSwitch = (ImageView)view.findViewById(R.id.lvlayoutswitch); mFlashIndicator = (ImageView)view.findViewById(R.id.flashindicator); mEvCompensationIndicator = (ImageView)view.findViewById(R.id.evcompensationindicator); mFlashCompensationIndicator = (ImageView)view.findViewById(R.id.flashcompensationindicator); mExposureIndicator = (ExposureIndicatorDisplay)view.findViewById(R.id.exposureindicator); mColorFilterGreen = new PorterDuffColorFilter(getResources().getColor(R.color.HoloGreenLight), android.graphics.PorterDuff.Mode.SRC_ATOP); mColorFilterRed = new PorterDuffColorFilter(getResources().getColor(R.color.Red), android.graphics.PorterDuff.Mode.SRC_ATOP); mFullScreen.setColorFilter(mColorFilterGreen); mFlashIndicator.setColorFilter(mColorFilterGreen); mEvCompensationIndicator.setColorFilter(mColorFilterGreen); mFlashCompensationIndicator.setColorFilter(mColorFilterGreen); mLvLayoutSwitch.setColorFilter(mColorFilterGreen); mFullScreen.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { IDslrActivity activity = getDslrActivity(); if (activity != null) { activity.toggleFullScreen(); if (activity.getIsFullScreen()) { mFullScreen.setImageResource(R.drawable.full_screen_return); mLvLayoutSwitch.setVisibility(View.INVISIBLE); } else { mFullScreen.setImageResource(R.drawable.full_screen); mLvLayoutSwitch.setVisibility(View.VISIBLE); } } } }); mLvLayoutSwitch.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { IDslrActivity activity = getDslrActivity(); if (activity != null) { activity.toggleLvLayout(); if (activity.getIsLvLayoutEnabled()) mLvLayoutSwitch.setImageResource(R.drawable.initiate_capture); else mLvLayoutSwitch.setImageResource(R.drawable.i0xd1a20x0000); } } }); mSdcard1 = (TextView)view.findViewById(R.id.txt_sdcard1); mSdcard2 = (TextView)view.findViewById(R.id.txt_sdcard2); mSdcard1.setOnClickListener(mSdcardClickListener); mSdcard2.setOnClickListener(mSdcardClickListener); mAeLockStatus = (TextView)view.findViewById(R.id.txt_aelockstatus); return view; } public void initFragment() { Log.d(TAG, "initFragment"); } @Override public void onAttach(Activity activity) { super.onAttach(activity); Log.d(TAG, "onAttach"); } @Override public void onStart() { Log.d(TAG, "onStart"); super.onStart(); } @Override public void onResume() { Log.d(TAG, "onResume"); super.onResume(); } @Override public void onPause() { Log.d(TAG, "onPause"); super.onPause(); } @Override public void onStop() { Log.d(TAG, "onStop"); super.onStop(); } @Override public void onDestroy() { Log.d(TAG, "onDestroy"); super.onDestroy(); } @Override public void onDetach() { Log.d(TAG, "onDetach"); super.onDetach(); } @Override protected void internalInitFragment() { try { if (getIsPtpDeviceInitialized()) { IDslrActivity activity = getDslrActivity(); internalPtpPropertyChanged(getPtpDevice().getPtpProperty(PtpProperty.FStop)); internalPtpPropertyChanged(getPtpDevice().getPtpProperty(PtpProperty.ExposureTime)); internalPtpPropertyChanged(getPtpDevice().getPtpProperty(PtpProperty.AeLockStatus)); internalPtpPropertyChanged(getPtpDevice().getPtpProperty(PtpProperty.InternalFlashPopup)); internalPtpPropertyChanged(getPtpDevice().getPtpProperty(PtpProperty.InternalFlashStatus)); internalPtpPropertyChanged(getPtpDevice().getPtpProperty(PtpProperty.ExposureBiasCompensation)); internalPtpPropertyChanged(getPtpDevice().getPtpProperty(PtpProperty.InternalFlashCompensation)); internalPtpPropertyChanged(getPtpDevice().getPtpProperty(PtpProperty.FlexibleProgram)); mExposureIndicator.invalidate(); internalPtpPropertyChanged(getPtpDevice().getPtpProperty(PtpProperty.ExposureIndicateStatus)); Hashtable<Integer, PtpStorageInfo> tmp = getPtpDevice().getPtpStorages(); PtpStorageInfo[] storages = tmp.values().toArray(new PtpStorageInfo[tmp.values().size()]); mSdcard1.setText("[E]"); mSdcard2.setVisibility(View.INVISIBLE); if (storages.length > 0) { if (storages.length > 1) { mSdcard2.setVisibility(View.VISIBLE); mSdcard2.setText(String.format("[%d]", storages[1].freeSpaceInImages)); } mSdcard1.setText(String.format("[%d]", storages[0].freeSpaceInImages)); } mFullScreen.setVisibility(getPtpDevice().getIsLiveViewEnabled() ? View.VISIBLE : View.INVISIBLE); if (activity != null) { if (activity.getIsFullScreen()) mLvLayoutSwitch.setVisibility(View.INVISIBLE); else mLvLayoutSwitch.setVisibility(mFullScreen.getVisibility()); } } } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); } } @Override protected void internalPtpPropertyChanged(PtpProperty property) { if (property != null) { switch (property.getPropertyCode()) { case PtpProperty.FStop: updateAperture(property); break; case PtpProperty.ExposureTime: updateExposureTime(property); break; case PtpProperty.AeLockStatus: if ((Integer)property.getValue() == 1) mAeLockStatus.setVisibility(View.VISIBLE); else mAeLockStatus.setVisibility(View.INVISIBLE); break; case PtpProperty.InternalFlashPopup: if ((Integer)property.getValue() == 1) { mFlashIndicator.setVisibility(View.VISIBLE); } else mFlashIndicator.setVisibility(View.INVISIBLE); break; case PtpProperty.InternalFlashStatus: Integer flashStatus = (Integer)property.getValue(); Log.d(TAG, "Flash status " + flashStatus); if (flashStatus == 1) // flash ready mFlashIndicator.setColorFilter(mColorFilterGreen); else // flash charging mFlashIndicator.setColorFilter(mColorFilterRed); break; case PtpProperty.ExposureBiasCompensation: if ((Integer)property.getValue() != 0) mEvCompensationIndicator.setVisibility(View.VISIBLE); else mEvCompensationIndicator.setVisibility(View.INVISIBLE); break; case PtpProperty.InternalFlashCompensation: if ((Integer)property.getValue() != 0) mFlashCompensationIndicator.setVisibility(View.VISIBLE); else mFlashCompensationIndicator.setVisibility(View.INVISIBLE); break; case PtpProperty.FlexibleProgram: Integer val = (Integer)property.getValue(); //mFlexibleProgram.setText(val.toString()); mExposureIndicator.processValue((float)val / 6); break; case PtpProperty.ExposureIndicateStatus: Integer eval = (Integer)property.getValue(); //mExposureIndicateStatus.setText(eval.toString()); mExposureIndicator.processValue((float)eval / 6); break; default: break; } } } private void updateAperture(PtpProperty property) { int fStop = (Integer)property.getValue(); txtAperture.setVisibility(View.VISIBLE); txtAperture.setText("F" + (double)fStop / 100); txtAperture.setEnabled(property.getIsWritable()); } private void updateExposureTime(PtpProperty property) { Long nesto = (Long)property.getValue(); Log.i(TAG, "Exposure " + nesto); //double value = 1 / ((double)nesto / 10000); if (nesto == 4294967295L) txtShutter.setText("Bulb"); else { if (nesto >= 10000) txtShutter.setText(String.format("%.1f \"", (double)nesto / 10000)); else txtShutter.setText(String.format("1/%.1f" , 10000 / (double)nesto)); } txtShutter.setEnabled(property.getIsWritable()); } @Override protected void ptpDeviceEvent(PtpDeviceEvent event, Object data) { int card; TextView txtCard = null; switch(event) { case LiveviewStart: mFullScreen.setVisibility(View.VISIBLE); mLvLayoutSwitch.setVisibility(View.VISIBLE); break; case LiveviewStop: mFullScreen.setVisibility(View.INVISIBLE); mLvLayoutSwitch.setVisibility(View.INVISIBLE); break; case SdCardInserted: case SdCardRemoved: card = (Integer)data; txtCard = card == 1 ? mSdcard1 : mSdcard2; if (txtCard != null) { txtCard.setVisibility(View.VISIBLE); if (event == PtpDeviceEvent.SdCardRemoved) { txtCard.setText(" [E] "); } } break; case SdCardInfoUpdated: PtpStorageInfo sInfo = (PtpStorageInfo)data; card = sInfo.storageId >> 16; txtCard = card == 1 ? mSdcard1 : mSdcard2; if (txtCard != null) txtCard.setText(String.format("[%d]", sInfo.freeSpaceInImages)); break; case BusyBegin: Log.d(TAG, "BusyBegin"); DslrHelper.getInstance().enableDisableControls(mBottomLayout, false, false); break; case BusyEnd: Log.d(TAG, "BusyEnd"); DslrHelper.getInstance().enableDisableControls(mBottomLayout, true, false); break; } } @Override protected void internalSharedPrefsChanged(SharedPreferences prefs, String key) { // TODO Auto-generated method stub } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import java.util.ArrayList; import android.app.Application; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.Log; public class NativeMethods { private final static String TAG = "NativeMethods"; static { System.loadLibrary("dslrdashboard"); } public native Object loadRawImage(String imgPath); public native boolean loadRawImageThumb(String imgPath, String thumbPath); //public native String[] getExifInfo(String imgPath); public native int getExifData(String path, int count, Object obj); public native int setGPSExifData(String path, double latitude, double longitude, double altitude); public native int copyExifData(String source, String target); public native int getRGBHistogram(Bitmap lvImage, int[] rArray, int[] gArray, int[] bArray, int[] lumaArray); private static NativeMethods _instance = null; public static NativeMethods getInstance() { if (_instance == null) _instance = new NativeMethods(); return _instance; } private NativeMethods() { mPaintBlack = new Paint(); mPaintBlack.setStyle(Paint.Style.FILL); mPaintBlack.setColor(Color.BLACK); mPaintBlack.setTextSize(25); mPaintBlack.setAlpha(100); mPaintWhite = new Paint(); mPaintWhite.setStyle(Paint.Style.STROKE); mPaintWhite.setColor(Color.WHITE); mPaintWhite.setTextSize(25); mPaintYellow = new Paint(); mPaintYellow.setStyle(Paint.Style.FILL); mPaintYellow.setColor(Color.YELLOW); mPaintYellow.setTextSize(25); mPaintRed = new Paint(); mPaintRed.setStyle(Paint.Style.FILL); mPaintRed.setColor(Color.RED); mPaintRed.setTextSize(25); mPaintRed.setAlpha(180); mPaintGreen = new Paint(); mPaintGreen.setStyle(Paint.Style.FILL); mPaintGreen.setColor(Color.GREEN); mPaintGreen.setTextSize(25); mPaintGreen.setAlpha(180); mPaintBlue = new Paint(); mPaintBlue.setStyle(Paint.Style.FILL); mPaintBlue.setColor(Color.BLUE); mPaintBlue.setTextSize(25); mPaintBlue.setAlpha(180); } public ArrayList<ExifDataHelper> getImageExif(String[] exifNames, String path){ ArrayList<ExifDataHelper> helper = new ArrayList<ExifDataHelper>(); for(String name : exifNames) { String[] tmp = name.split("@"); helper.add(new ExifDataHelper(tmp[0], tmp[1])); } getExifData(path, helper.size(), helper); return helper; } public void exifValueCallback(String test, int index, Object obj) { ArrayList<ExifDataHelper> helper = (ArrayList<ExifDataHelper>)obj; //Log.d(TAG, "Exif value callback " + test + " index: " + index + " helper test: " + helper.size()); helper.get(index).mExifValue = test; } public String exifNameCallback(int index, Object obj) { ArrayList<ExifDataHelper> helper = (ArrayList<ExifDataHelper>)obj; //Log.d(TAG, "Name callback " + helper.get(index).mExifName + " index: " + index + " helper test: " + helper.size()); return helper.get(index).mExifName; } private Paint mPaintWhite; private Paint mPaintBlack; private Paint mPaintYellow; private Paint mPaintRed; private Paint mPaintGreen; private Paint mPaintBlue; private int[] mrArray = new int[257]; private int[] mgArray = new int[257]; private int[] mbArray = new int[257]; private int[] mlumaArray = new int[257]; private float mHistogramWidth = 450; private float mHistogramHeight = 150; private float dx = (float)mHistogramWidth / (float)256; public Bitmap createHistogramBitmap(Bitmap source, boolean separate) { getRGBHistogram(source, mrArray, mgArray, mbArray, mlumaArray); if (source != null) { Log.d(TAG, "drawHistogram"); Bitmap.Config conf = Bitmap.Config.ARGB_8888; int cHeight = separate ? (int)mHistogramHeight * 4 : (int)mHistogramHeight * 2; Bitmap hist = Bitmap.createBitmap((int)mHistogramWidth, cHeight, conf); Canvas canvas = new Canvas(hist); canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), mPaintBlack); //canvas.drawRect(1, 1, canvas.getWidth()-1, canvas.getHeight()-1, mPaintWhite); int count = separate ? 4 : 2; for (int i = 0; i < count ; i++) { int hpos = (int)mHistogramHeight * i; canvas.drawRect(1, hpos + 1, canvas.getWidth() - 1, hpos + (int)mHistogramHeight - 1, mPaintWhite); } int maxVal = Math.max(mrArray[256], mbArray[256]); maxVal = Math.max(maxVal, mgArray[256]); for (int i =0; i < 256; i++ ){ float left = (float)i * dx;// + canvas.getWidth() - mHistogramWidth; if (!separate) { canvas.drawRect(left, mHistogramHeight -1, left + dx, mHistogramHeight - (((float)mlumaArray[i] * mHistogramHeight)/ (float)mlumaArray[256]) +1, mPaintYellow); canvas.drawRect(left, (mHistogramHeight * 2) -1, left + dx, (mHistogramHeight * 2) - (((float)mrArray[i] * mHistogramHeight)/ (float)mrArray[256]) +1, mPaintRed); canvas.drawRect(left, (mHistogramHeight * 2) -1, left + dx, (mHistogramHeight * 2) - (((float)mbArray[i] * mHistogramHeight)/ (float)mbArray[256]) +1, mPaintBlue); canvas.drawRect(left, (mHistogramHeight * 2) -1, left + dx, (mHistogramHeight * 2) - (((float)mgArray[i] * mHistogramHeight)/ (float)mgArray[256]) +1 , mPaintGreen); } else { canvas.drawRect(left, mHistogramHeight -1, left + dx, mHistogramHeight - (((float)mlumaArray[i] * mHistogramHeight)/ (float)mlumaArray[256]) +1, mPaintYellow); canvas.drawRect(left, (mHistogramHeight * 2) -1, left + dx, (mHistogramHeight * 2) - (((float)mrArray[i] * mHistogramHeight)/ (float)mrArray[256]) +1, mPaintRed); canvas.drawRect(left, (mHistogramHeight * 4) -1, left + dx, (mHistogramHeight * 4 ) - (((float)mbArray[i] * mHistogramHeight)/ (float)mbArray[256]) +1, mPaintBlue); canvas.drawRect(left, (mHistogramHeight * 3) -1, left + dx, (mHistogramHeight * 3 )- (((float)mgArray[i] * mHistogramHeight)/ (float)mgArray[256]) +1 , mPaintGreen); } } return hist; } else return null; } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import java.io.File; import java.io.FileOutputStream; import java.util.Hashtable; import java.util.Vector; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.hardware.usb.UsbDeviceConnection; import android.hardware.usb.UsbEndpoint; import android.net.Uri; import android.os.Environment; import android.os.Handler; import android.util.Log; public class PtpDevice { private static final String TAG = "PtpDevice"; public final static String PREF_KEY_LV_AT_START = "pref_key_lv_at_start"; public final static String PREF_KEY_LV_RETURN = "pref_key_lv_return"; public final static String PREF_KEY_SHOOTING_AF = "pref_key_shooting_af"; public final static String PREF_KEY_GENERAL_SCREEN_ON = "pref_key_general_screen_on"; public final static String PREF_KEY_GENERAL_INTERNAL_VIEWER = "pref_key_general_internal_viewer"; public final static String PREF_KEY_SDRAM_LOCATION = "pref_key_sdram_saving_location"; public final static String PREF_KEY_SDRAM_PREFIX = "pref_key_sdram_prefix"; public final static String PREF_KEY_SDRAM_NUMBERING = "pref_key_sdram_numbering"; public final static String PREF_KEY_BKT_ENABLED = "pref_key_bkt_enabled"; public final static String PREF_KEY_BKT_COUNT = "pref_key_bkt_count"; public final static String PREF_KEY_BKT_DIRECTION = "pref_key_bkt_direction"; public final static String PREF_KEY_BKT_STEP = "pref_key_bkt_step"; public final static String PREF_KEY_BKT_FOCUS_FIRST = "pref_key_bkt_focus_first"; public final static String PREF_KEY_TIMELAPSE_INTERVAL = "pref_key_timelapse_interval"; public final static String PREF_KEY_TIMELAPSE_ITERATIONS = "pref_key_timelapse_iterations"; public final static String PREF_KEY_FOCUS_IMAGES = "pref_key_focus_images"; public final static String PREF_KEY_FOCUS_STEPS = "pref_key_focus_steps"; public final static String PREF_KEY_FOCUS_DIRECTION_DOWN = "pref_key_focus_direction_down"; public final static String PREF_KEY_FOCUS_FOCUS_FIRST = "pref_key_focus_focus_first"; public final static String PREF_KEY_GPS_ENABLED = "pref_key_gps_enabled"; public final static String PREF_KEY_GPS_SAMPLES = "pref_key_gps_samples"; public final static String PREF_KEY_GPS_INTERVAL = "pref_key_gps_interval"; public interface OnPtpDeviceEventListener { public void sendEvent(PtpDeviceEvent event, Object data); } private OnPtpDeviceEventListener mOnPtpDeviceEventListener = null; public void setOnPtpDeviceEventListener(OnPtpDeviceEventListener listener) { mOnPtpDeviceEventListener = listener; } public void removeOnPtpDeviceEventListener() { mOnPtpDeviceEventListener = null; } private void sendPtpDeviceEvent(PtpDeviceEvent event) { sendPtpDeviceEvent(event, null); } private void sendPtpDeviceEvent(PtpDeviceEvent event, Object data) { if (mOnPtpDeviceEventListener != null) mOnPtpDeviceEventListener.sendEvent(event, data); } public interface OnPtpPropertyChangedListener { public void sendPtpPropertyChanged(PtpProperty property); } private OnPtpPropertyChangedListener mPtpPropertyChangedListener = null; public void setOnPtpPropertyChangedListener( OnPtpPropertyChangedListener listener) { mPtpPropertyChangedListener = listener; } public void removePtpPropertyChangedListener() { mPtpPropertyChangedListener = null; } private void sendPtpPropertyChanged(PtpProperty property) { if (mPtpPropertyChangedListener != null) mPtpPropertyChangedListener.sendPtpPropertyChanged(property); } private SharedPreferences.OnSharedPreferenceChangeListener mPrefListener = null; public void setOnSharedPreferenceChangeListener( SharedPreferences.OnSharedPreferenceChangeListener listener) { mPrefListener = listener; } public void removeSharedPreferenceChangeListener() { mPrefListener = null; } public boolean getIsCommandSupported(int ptpCommand) { if (!mIsPtpDeviceInitialized) return false; return mDeviceInfo.supportsOperation(ptpCommand); } public boolean getIsMovieRecordingStarted() { return mIsMovieRecordingStarted; } public boolean getCaptureToSdram() { return mCaptureToSdram; } public void setCaptureToSdram(boolean value) { mCaptureToSdram = value; sendPtpDeviceEvent(PtpDeviceEvent.RecordingDestinationChanged, mCaptureToSdram); } private int mVendorId = 0; private int mProductId = 0; private PtpService mPtpService = null; private SharedPreferences mPrefs = null; private PtpCommunicatorBase mCommunicator = null; private boolean mIsInitialized = false; private ExecutorService mExecutor; private boolean mIsExecutorRunning = false; private boolean mIsPtpDeviceInitialized = false; private PtpDeviceInfo mDeviceInfo = null; private Hashtable<Integer, PtpProperty> mPtpProperties; private Hashtable<Integer, PtpStorageInfo> mPtpStorages; private boolean mIsLiveViewEnabled = false; private boolean mIsPtpObjectsLoaded = false; private ThreadBase mEventThread = null; // private LiveviewThread mLiveviewThread = null; private boolean mIsMovieRecordingStarted = false; private PtpLiveViewObject mLvo = null; private boolean mCaptureToSdram = false; // internal bracketing backup private Object mInternalBracketingShootingMode = null; private Object mInternalBracketingBurstNumber = null; // preferences private private boolean mLiveViewAtStart = false; private boolean mLiveViewReturn = false; private boolean mAFBeforeCapture = true; private boolean mGeneralScreenOn = true; private boolean mGeneralInternalViewer = true; // custom bracketing preferences private boolean mIsCustomBracketingEnabled = false; private int mBktStep = 1; private int mBktDirection = 2; private int mBktCount = 3; private boolean mBktFocusFirst = true; // sdram image saving preferences private String mSdramSavingLocation = new File( Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "DSLR").getAbsolutePath(); private String mSdramPrefix = "dslr"; private int mSdramPictureNumbering = 1; // time lapse preferences private long mTimelapseInterval = 10000; // interval in seconds private int mTimelapseIterations = 10; // gps location preferences private boolean mGpsInfoEnabled = true; private int mGpsSamples = 3; private int mGpsInterval = 2; // preferences public public boolean getLiveViewAtStart() { return mLiveViewAtStart; } public boolean getLiveViewReturn() { return mLiveViewReturn; } public boolean getAFBeforeCapture() { return mAFBeforeCapture; } public void setAFBeforeCapture(boolean value) { if (value != mAFBeforeCapture) { mAFBeforeCapture = value; Editor editor = mPrefs.edit(); editor.putBoolean(PREF_KEY_SHOOTING_AF, value); editor.commit(); } } public boolean getGeneralScreenOn() { return mGeneralScreenOn; } public boolean getGeneralInternalViewer() { return mGeneralInternalViewer; } // custom bracketing public properties public boolean getIsCustomBracketingEnabled() { return mIsCustomBracketingEnabled; } public void setIsCustomBracketingEnabled(boolean value) { mIsCustomBracketingEnabled = value; mPrefs .edit() .putBoolean(PREF_KEY_BKT_ENABLED, mIsCustomBracketingEnabled) .commit(); } public int getCustomBracketingCount() { return mBktCount; } public void setCustomBracketingCount(int value) { mBktCount = value; mPrefs .edit() .putString(PREF_KEY_BKT_COUNT, Integer.toString(mBktCount)) .commit(); } public int getCustomBracketingDirection() { return mBktDirection; } public void setCustomBracketingDirection(int value) { mBktDirection = value; mPrefs .edit() .putString(PREF_KEY_BKT_DIRECTION, Integer.toString(mBktDirection)) .commit(); } public int getCustomBracketingStep() { return mBktStep; } public void setCustomBracketingStep(int value) { mBktStep = value; mPrefs .edit() .putString(PREF_KEY_BKT_STEP, Integer.toString(mBktStep)) .commit(); } public boolean getCustomBracketingFocusFirst(){ return mBktFocusFirst; } public void setCustomBracketingFocusFirst(boolean value) { mBktFocusFirst = value; mPrefs .edit() .putBoolean(PREF_KEY_BKT_FOCUS_FIRST, mBktFocusFirst) .commit(); } // sdram image saving public preferences public void setSdramPictureNumbering(int value) { mSdramPictureNumbering = value; mPrefs .edit() .putString(PREF_KEY_SDRAM_NUMBERING, Integer.toString(mSdramPictureNumbering)) .commit(); } // timelapse public preferences public long getTimelapseInterval(){ return mTimelapseInterval; } public void setTimelapseInterval(long value){ mTimelapseInterval = value; mPrefs .edit() .putString(PREF_KEY_TIMELAPSE_INTERVAL, Long.toString(mTimelapseInterval)) .commit(); } public int getTimelapseIterations(){ return mTimelapseIterations; } public void setTimelapseIterations(int value){ mTimelapseIterations = value; mPrefs .edit() .putString(PREF_KEY_TIMELAPSE_ITERATIONS, Integer.toString(mTimelapseIterations)) .commit(); } public PtpDevice(PtpService ptpService) { mPtpService = ptpService; mPrefs = mPtpService.getPreferences(); loadPreferences(); mDeviceInfo = new PtpDeviceInfo(); mPtpProperties = new Hashtable<Integer, PtpProperty>(); mPtpStorages = new Hashtable<Integer, PtpStorageInfo>(); } private SharedPreferences.OnSharedPreferenceChangeListener mPrefChangedListener = new SharedPreferences.OnSharedPreferenceChangeListener() { public void onSharedPreferenceChanged( SharedPreferences sharedPreferences, String key) { Log.d(TAG, "Preference changed: " + key); loadPreferences(); if (mPrefListener != null) mPrefListener.onSharedPreferenceChanged(sharedPreferences, key); } }; private void loadPreferences() { Log.d(TAG, "Loading preferences"); mLiveViewAtStart = mPrefs.getBoolean(PREF_KEY_LV_AT_START, false); mLiveViewReturn = mPrefs.getBoolean(PREF_KEY_LV_RETURN, false); mAFBeforeCapture = mPrefs.getBoolean(PREF_KEY_SHOOTING_AF, true); mGeneralScreenOn = mPrefs.getBoolean(PREF_KEY_GENERAL_SCREEN_ON, true); mGeneralInternalViewer = mPrefs.getBoolean(PREF_KEY_GENERAL_INTERNAL_VIEWER, true); String tmp = mPrefs.getString(PREF_KEY_SDRAM_LOCATION, ""); if (tmp.equals("")) { Editor editor = mPrefs.edit(); editor.putString(PREF_KEY_SDRAM_LOCATION, mSdramSavingLocation); editor.commit(); } else mSdramSavingLocation = tmp; mSdramPrefix = mPrefs.getString(PREF_KEY_SDRAM_PREFIX, "dslr"); mSdramPictureNumbering = Integer.valueOf(mPrefs.getString( PREF_KEY_SDRAM_NUMBERING, "1")); mIsCustomBracketingEnabled = mPrefs.getBoolean(PREF_KEY_BKT_ENABLED, false); mBktCount = Integer.valueOf(mPrefs.getString(PREF_KEY_BKT_COUNT, "3")); mBktDirection = Integer.valueOf(mPrefs.getString(PREF_KEY_BKT_DIRECTION, "2")); mBktStep = Integer.valueOf(mPrefs.getString(PREF_KEY_BKT_STEP, "1")); mBktFocusFirst = mPrefs.getBoolean(PREF_KEY_BKT_FOCUS_FIRST, true); mTimelapseInterval = Long.valueOf(mPrefs.getString(PREF_KEY_TIMELAPSE_INTERVAL, "10000")); mTimelapseIterations = Integer.valueOf(mPrefs.getString(PREF_KEY_TIMELAPSE_ITERATIONS, "10")); mFocusImages = Integer.valueOf(mPrefs.getString(PREF_KEY_FOCUS_IMAGES, "5")); mFocusStep = Integer.valueOf(mPrefs.getString(PREF_KEY_FOCUS_STEPS, "10")); mFocusDirectionDown = mPrefs.getBoolean(PREF_KEY_FOCUS_DIRECTION_DOWN, true); mFocusFocusFirst = mPrefs.getBoolean(PREF_KEY_FOCUS_FOCUS_FIRST, false); mGpsInfoEnabled = mPrefs.getBoolean(PREF_KEY_GPS_ENABLED, false); mGpsSamples = Integer.valueOf(mPrefs.getString(PREF_KEY_GPS_SAMPLES, "3")); mGpsInterval = Integer.valueOf(mPrefs.getString(PREF_KEY_GPS_INTERVAL, "2")); mPtpService.getGpsLocationHelper().setGpsSampleCount(mGpsSamples); mPtpService.getGpsLocationHelper().setGpsSampleInterval(mGpsInterval); sendPtpDeviceEvent(PtpDeviceEvent.PrefsLoaded, null); } public void initialize(int vendorId, int productId, PtpCommunicatorBase communicator) { if (!mIsInitialized) { mExecutor = Executors.newSingleThreadExecutor(); mIsExecutorRunning = true; mCommunicator = communicator; mIsInitialized = true; mVendorId = vendorId; mProductId = productId; mLvo = new PtpLiveViewObject(vendorId, productId); mPrefs.registerOnSharedPreferenceChangeListener(mPrefChangedListener); initializePtpDevice(); } } public void stop(boolean isUsbUnpluged) { Log.d(TAG, "stop PTP device"); if (!isUsbUnpluged) normalStop(); else usbUnplugedStop(); mPrefs.unregisterOnSharedPreferenceChangeListener(mPrefChangedListener); } private void normalStop() { // stop live view if running Log.i(TAG, "ending live view"); endLiveViewDisplay(true); // return to camera mode Log.i(TAG, "switching to camera mode"); changeCameraModeCmd(true); // return to sdcard mode Log.i(TAG, "switching to sdcard mode"); setDevicePropValue(PtpProperty.RecordingMedia, 0x0000, true); Log.d(TAG, "stoping PTPDevice threads"); usbUnplugedStop(); } private void usbUnplugedStop() { stopTimelapseExecutor(); mCommunicator.closeCommunicator(); if (mIsExecutorRunning) { Log.d(TAG, "stoping communicator thread"); stopExecutor(mExecutor); mIsExecutorRunning = false; } // if (mLiveviewThread != null) // mLiveviewThread.interrupt(); if (mEventThread != null) mEventThread.interrupt(); sendPtpDeviceEvent(PtpDeviceEvent.PtpDeviceStoped); mIsInitialized = false; mIsPtpDeviceInitialized = false; mIsLiveViewEnabled = false; mIsPtpObjectsLoaded = false; mPtpProperties.clear(); mPtpStorages.clear(); } public boolean getIsInitialized() { return mIsInitialized; } public boolean getIsPtpDeviceInitialized() { return mIsPtpDeviceInitialized; } public PtpService getPtpService() { return mPtpService; } public int getVendorId() { return mVendorId; } public int getProductId() { return mProductId; } public PtpDeviceInfo getPtpDeviceInfo() { return mDeviceInfo; } public boolean getIsLiveViewEnabled() { return mIsLiveViewEnabled; } public boolean getIsPtpObjectsLoaded() { return mIsPtpObjectsLoaded; } public Hashtable<Integer, PtpStorageInfo> getPtpStorages() { return mPtpStorages; } public synchronized PtpProperty getPtpProperty(final int propertyCode) { PtpProperty property = (PtpProperty) mPtpProperties.get(propertyCode); return property; } private void stopExecutor(ExecutorService executor) { if (executor != null) { Log.d(TAG, "Shuting down executor"); executor.shutdown(); try { // Wait a while for existing tasks to terminate if (!executor.awaitTermination(500, TimeUnit.MICROSECONDS)) { executor.shutdownNow(); // Cancel currently executing tasks // Wait a while for tasks to respond to being cancelled if (!executor.awaitTermination(500, TimeUnit.MILLISECONDS)) System.err.println("Pool did not terminate"); } } catch (InterruptedException ie) { // (Re-)Cancel if current thread also interrupted executor.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } } } protected synchronized PtpCommand sendCommand(PtpCommand cmd) { try { if (cmd.getCommandCode() != PtpCommand.GetDeviceInfo && cmd.getCommandCode() != PtpCommand.OpenSession) { if (!mDeviceInfo.supportsOperation(cmd.getCommandCode())) return null; } // Log.d(MainActivity.TAG, "Before get task"); FutureTask<PtpCommand> fCmd = cmd.getTask(mCommunicator); // Log.d(MainActivity.TAG, "Before executing"); mExecutor.execute(fCmd); // Log.d(MainActivity.TAG, "After executing"); PtpCommand result = fCmd.get(); return result; } catch (Exception e) { Log.e(TAG, "SendPtpCommand: ");// + e.getMessage()); return null; } } private void initializePtpDevice() { new Thread(new Runnable() { public void run() { // get the device info PtpCommand cmd = sendCommand(getDeviceInfoCmd()); if ((cmd == null) || (cmd != null && !cmd.isDataOk())) return; mDeviceInfo.parse(cmd.incomingData()); // open the session cmd = sendCommand(openSessionCmd()); if (cmd == null) return; if (cmd.isResponseOk() || (cmd.hasResponse() && cmd.incomingResponse() .getPacketCode() == PtpResponse.SessionAlreadyOpen)) { // we have a session // load the supported properties for (int i = 0; i < mDeviceInfo.getPropertiesSupported().length; i++) { updateDevicePropDescCmd(mDeviceInfo .getPropertiesSupported()[i]); } loadVendorProperties(); getStorageIds(); mIsPtpDeviceInitialized = true; startEventListener(); sendPtpDeviceEvent(PtpDeviceEvent.PtpDeviceInitialized); if (mIsLiveViewEnabled) { sendPtpDeviceEvent(PtpDeviceEvent.LiveviewStart); } else if (mLiveViewAtStart) enterLiveViewAtStart(); } } }).start(); } private void loadVendorProperties() { Log.i(TAG, "Load vendor properties"); // try to get the vendor properties PtpCommand cmd = sendCommand(getVendorPropCodesCmd()); // process the vendor properties if (cmd != null && cmd.isDataOk()) { cmd.incomingData().parse(); int[] vendorProps = cmd.incomingData().nextU16Array(); for (int i = 0; i < vendorProps.length; i++) { PtpCommand pCmd = sendCommand(getDevicePropDescCmd(vendorProps[i])); processLoadedProperty(pCmd); } } } private PtpCommand getDeviceInfoCmd() { return new PtpCommand(PtpCommand.GetDeviceInfo); } private PtpCommand openSessionCmd() { return new PtpCommand(PtpCommand.OpenSession).addParam(1); } private PtpCommand getDevicePropDescCmd(int propertyCode) { return new PtpCommand(PtpCommand.GetDevicePropDesc) .addParam(propertyCode); } private void updateDevicePropDescCmd(int propertyCode) { processLoadedProperty(sendCommand(getDevicePropDescCmd(propertyCode))); } private void processLoadedProperty(PtpCommand cmd) { if (cmd != null && cmd.isDataOk()) { cmd.incomingData().parse(); PtpProperty property; int propCode = cmd.incomingData().nextU16(); if (!mPtpProperties.containsKey(propCode)) { // Log.i(TAG, String.format("+++ Creating new property %#04x", // propCode)); property = new PtpProperty(); mPtpProperties.put(Integer.valueOf(propCode), property); } else { property = mPtpProperties.get(propCode); // Log.i(TAG, // String.format("+++ Property already in list %#04x", // propCode)); } property.parse(cmd.incomingData()); sendPtpPropertyChanged(property); switch (property.getPropertyCode()) { case PtpProperty.LiveViewStatus: mIsLiveViewEnabled = (Integer) property.getValue() == 1; break; } } } private PtpCommand getVendorPropCodesCmd() { return new PtpCommand(PtpCommand.GetVendorPropCodes); } private PtpCommand getEventCmd() { return new PtpCommand(PtpCommand.GetEvent); } private PtpCommand setDevicePropValueCommand(int propertyCode, Object value) { // Log.i(TAG, "setDevicePropValueCommand"); PtpProperty property = mPtpProperties.get(propertyCode); if (property != null) { PtpBuffer buf = new PtpBuffer( new byte[mCommunicator.getWriteEpMaxPacketSize()]); PtpPropertyValue.setNewPropertyValue(buf, property.getDataType(), value); return new PtpCommand(PtpCommand.SetDevicePropValue).addParam( propertyCode).setCommandData(buf.getOfssetArray()); } else return null; } protected void setDevicePropValue(int propertyCode, Object value, boolean updateProperty) { final PtpCommand cmd = setDevicePropValueCommand(propertyCode, value); if (cmd != null) { PtpCommand fCmd = sendCommand(cmd); if (fCmd != null && fCmd.isResponseOk()) { // Log.d(TAG, "setDevicePropValue finished"); if (updateProperty) updateDevicePropDescCmd(propertyCode); } } // else // Log.i(TAG, "property not found"); } public void setDevicePropValueCmd(final int propertyCode, final Object value) { setDevicePropValueCmd(propertyCode, value, true); } public void setDevicePropValueCmd(final int propertyCode, final Object value, final boolean updateProperty) { if (mIsPtpDeviceInitialized) { new Thread(new Runnable() { public void run() { setDevicePropValue(propertyCode, value, updateProperty); } }).start(); } } protected PtpCommand getThumbCmd(int objectId) { return new PtpCommand(PtpCommand.GetThumb).addParam(objectId); } protected PtpCommand getObjectInfoCmd(int objectId) { return new PtpCommand(PtpCommand.GetObjectInfo).addParam(objectId); } private PtpCommand getStorageIdsCommand() { return new PtpCommand(PtpCommand.GetStorageIDs); } private PtpCommand getStorageInfoCommand(int storageId) { return new PtpCommand(PtpCommand.GetStorageInfo).addParam(storageId); } private PtpCommand getObjectHandlesCommand(int storageId) { return new PtpCommand(PtpCommand.GetObjectHandles).addParam(storageId); } private int mSlot2Mode = 0; private int mActiveSlot = 1; public int getSlot2Mode() { return mSlot2Mode; } public int getActiveSlot() { return mActiveSlot; } private void getStorageIds() { PtpCommand cmd = sendCommand(getStorageIdsCommand()); if ((cmd == null) || (cmd != null && !cmd.isDataOk())) return; cmd.incomingData().parse(); int count = cmd.incomingData().nextS32(); Log.d(TAG, "Storage id count: " + count); PtpProperty prop = getPtpProperty(PtpProperty.Slot2ImageSaveMode); if (prop != null) { mSlot2Mode = (Integer) prop.getValue(); Log.d(TAG, "Slot2 mode: " + mSlot2Mode); } prop = getPtpProperty(PtpProperty.ActiveSlot); if (prop != null) { mActiveSlot = (Integer) prop.getValue(); Log.d(TAG, "Active slot: " + mActiveSlot); } for (int i = 1; i <= count; i++) { int storeId = cmd.incomingData().nextS32(); int storeNo = storeId >> 16; Log.d(TAG, "StoreID: " + storeId); Log.d(TAG, "Getting info for slot: " + storeNo); if ((storeId & 1) == 1) { Log.d(TAG, "Slot has card"); sendPtpDeviceEvent(PtpDeviceEvent.SdCardInserted, storeId >> 16); getStorageInfo(storeId); // getObjectHandles(storeId); } else { Log.d(TAG, "Slot is empty"); sendPtpDeviceEvent(PtpDeviceEvent.SdCardRemoved, storeId >> 16); } } } private void getStorageIdsCmd() { new Thread(new Runnable() { public void run() { getStorageIds(); } }).start(); } private void getStorageInfo(final int storageId) { Log.d(TAG, String.format("Get storage info: %#04x", storageId)); PtpCommand cmd = sendCommand(getStorageInfoCommand(storageId)); if ((cmd == null) || (cmd != null && !cmd.isDataOk())) return; PtpStorageInfo storage; if (mPtpStorages.containsKey(storageId)) { storage = mPtpStorages.get(storageId); storage.updateInfo(cmd.incomingData()); } else { storage = new PtpStorageInfo(storageId, cmd.incomingData()); mPtpStorages.put(storageId, storage); } sendPtpDeviceEvent(PtpDeviceEvent.SdCardInfoUpdated, storage); } private void getObjectHandles(final int storageId) { Log.d(TAG, String.format("load object handles: %#04x", storageId)); PtpCommand cmd = sendCommand(getObjectHandlesCommand(storageId)); if ((cmd == null) || (cmd != null && !cmd.isDataOk())) return; cmd.incomingData().parse(); int count = cmd.incomingData().nextS32(); for (int i = 1; i <= count; i++) { getObjectInfo(cmd.incomingData().nextS32()); } } private PtpObjectInfo getObjectInfo(final int objectId) { Log.d(TAG, String.format("Get object info: %#04x", objectId)); PtpObjectInfo obj = null; PtpCommand cmd = sendCommand(getObjectInfoCmd(objectId)); if ((cmd == null) || (cmd != null && !cmd.isDataOk())) return null; cmd.incomingData().parse(); int storageId = cmd.incomingData().nextS32(); PtpStorageInfo storage = mPtpStorages.get(storageId); if (storage.objects.containsKey(objectId)) { obj = storage.objects.get(objectId); obj.parse(cmd.incomingData()); } else { obj = new PtpObjectInfo(objectId, cmd.incomingData()); storage.objects.put(objectId, obj); } loadObjectThumb(obj); // sendPtpServiceEvent(PtpServiceEventType.ObjectAdded, obj); return obj; } private void loadObjectThumb(PtpObjectInfo obj) { switch (obj.objectFormatCode) { case 0x3000: case 0x3801: File file = new File(mSdramSavingLocation + "/.dslrthumbs"); if (!file.exists()) file.mkdir(); file = new File(file, obj.filename + ".jpg"); if (!file.exists()) { PtpCommand cmd = sendCommand(getThumbCmd(obj.objectId)); if ((cmd == null) || (cmd != null && !cmd.isDataOk())) return; obj.thumb = BitmapFactory.decodeByteArray(cmd.incomingData() .data(), 12, cmd.incomingData().data().length - 12); FileOutputStream fOut; try { fOut = new FileOutputStream(file); obj.thumb.compress(Bitmap.CompressFormat.JPEG, 85, fOut); fOut.flush(); fOut.close(); obj.thumb.recycle(); } catch (Exception e) { } } break; } } private PtpCommand getLargeThumbCommand(int objectId) { return new PtpCommand(PtpCommand.GetLargeThumb).addParam(objectId); } public byte[] getLargeThumb(int objectId) { PtpCommand cmd = sendCommand(getLargeThumbCommand(objectId)); if (cmd != null && cmd.isResponseOk()) return cmd.incomingData().data(); else return null; } public void loadObjectInfos() { Log.d(TAG, "load object infos"); if (!mIsPtpObjectsLoaded) { for (PtpStorageInfo info : mPtpStorages.values()) { getObjectHandles(info.storageId); } mIsPtpObjectsLoaded = true; // sendPtpServiceEvent(PtpServiceEventType.ObjectInfosLoaded, null); } } protected PtpCommand getPartialObjectCmd(PtpObjectInfo objectInfo, int maxSize, File file) { return getPartialObjectCmd(objectInfo, maxSize, file, null); } protected PtpCommand getPartialObjectCmd( PtpObjectInfo objectInfo, int maxSize, File file, PtpPartialObjectProccessor.PtpPartialObjectProgressListener progressListener) { PtpPartialObjectProccessor processor = new PtpPartialObjectProccessor( objectInfo, file); processor.setProgressListener(progressListener); return new PtpCommand(PtpCommand.GetPartialObject) .addParam(objectInfo.objectId) .addParam(0) .addParam(maxSize) .setFinalProcessor(processor); } public PtpCommand getPreviewImageCmd( PtpObjectInfo objectInfo, int maxSize, File file, PtpPartialObjectProccessor.PtpPartialObjectProgressListener progressListener) { return sendCommand(getPreviewImage(objectInfo, maxSize, file, progressListener)); } private PtpCommand getPreviewImage( PtpObjectInfo objectInfo, int maxSize, File file, PtpPartialObjectProccessor.PtpPartialObjectProgressListener progressListener) { PtpGetPreviewImageProcessor processor = new PtpGetPreviewImageProcessor(objectInfo, file); processor.setProgressListener(progressListener); return new PtpCommand(PtpCommand.GetPreviewImage) .addParam(objectInfo.objectId) .addParam(1) .addParam(maxSize) .setFinalProcessor(processor); } private PtpCommand deleteObject(int objectId) { return new PtpCommand(PtpCommand.DeleteObject) .addParam(objectId); } public void deleteObjectCmd(ImageObjectHelper obj) { if (obj != null && obj.objectInfo != null) { PtpCommand cmd = sendCommand(deleteObject(obj.objectInfo.objectId)); if (cmd != null && cmd.isResponseOk()) { PtpStorageInfo storage = mPtpStorages.get(obj.objectInfo.storageId); if (storage != null) storage.deleteObject(obj.objectInfo.objectId); } } } public void changeCameraMode() { if (mIsPtpDeviceInitialized) { PtpProperty property = getPtpProperty(PtpProperty.ExposureProgramMode); if (property != null) changeCameraMode(property.getIsWritable()); } } private void changeCameraModeCmd(boolean cameraMode) { if (mIsPtpDeviceInitialized) { int mode = cameraMode ? 0 : 1; PtpCommand cmd = sendCommand(new PtpCommand( PtpCommand.ChangeCameraMode).addParam(mode)); if (cmd != null && cmd.isResponseOk()) updateDevicePropDescCmd(PtpProperty.ExposureProgramMode); } } public void changeCameraMode(final boolean cameraMode) { new Thread(new Runnable() { public void run() { changeCameraModeCmd(cameraMode); } }).start(); } private boolean mNeedReturnToLiveview = false; private void checkReturnToLiveView() { Log.i(TAG, "Check return to live view: " + mNeedReturnToLiveview); if (mNeedReturnToLiveview) { Log.i(TAG, "Need return to live view"); startLiveViewDisplay(true); mNeedReturnToLiveview = false; } } private void checkNeedReturnToLiveView(boolean captureToSdram) { mNeedReturnToLiveview = false; Log.i(TAG, "Check if we need to return to live view after capture"); PtpProperty property = getPtpProperty(PtpProperty.LiveViewStatus); if (property != null) { mNeedReturnToLiveview = (Integer) property.getValue() != 0; Log.i(TAG, "Need to return to live view: " + mNeedReturnToLiveview); if (mNeedReturnToLiveview) { endLiveViewDisplay(true); // only return to live view if it is set in preferences mNeedReturnToLiveview = mLiveViewReturn; } } } public void changeAfAreaCmd(final int x, final int y) { new Thread(new Runnable() { public void run() { PtpCommand cmd = sendCommand(new PtpCommand( PtpCommand.ChangeAfArea).addParam(x).addParam(y)); if (cmd != null && cmd.isDataOk()) { } } }).start(); } public PtpLiveViewObject getLiveViewImage() { PtpCommand cmd = sendCommand(new PtpCommand(PtpCommand.GetLiveViewImage)); if (cmd != null && cmd.isDataOk()) { mLvo.setBuffer(cmd.incomingData()); return mLvo; } return null; } public void toggleInternalBracketing() { PtpProperty property = getPtpProperty(PtpProperty.EnableBracketing); if (property != null) { if ((Integer)property.getValue() == 0) { setDevicePropValueCmd(PtpProperty.EnableBracketing, 1); property = getPtpProperty(PtpProperty.StillCaptureMode); if (property != null) { mInternalBracketingShootingMode = property.getValue(); setDevicePropValueCmd(PtpProperty.StillCaptureMode, 1); } property = getPtpProperty(PtpProperty.BurstNumber); if (property != null) { mInternalBracketingBurstNumber = property.getValue(); setDevicePropValueCmd(PtpProperty.BurstNumber, 3); } } else { setDevicePropValueCmd(PtpProperty.EnableBracketing, 0); if (mInternalBracketingShootingMode != null) { setDevicePropValueCmd(PtpProperty.StillCaptureMode, mInternalBracketingShootingMode); mInternalBracketingShootingMode = null; } if (mInternalBracketingBurstNumber != null) { setDevicePropValueCmd(PtpProperty.BurstNumber, mInternalBracketingBurstNumber); mInternalBracketingBurstNumber = null; } } } } private int mOldAFMode = 0; private boolean mAfModeChanged = false; private PtpCommand initiateCaptureCommand(boolean captureToSdram) { return initiateCaptureCommand(captureToSdram, mAFBeforeCapture); } private PtpCommand initiateCaptureCommand(boolean captureToSdram, boolean performAf) { PtpCommand cmd = null; if (getIsCommandSupported(PtpCommand.InitiateCaptureRecInMedia)) { cmd = new PtpCommand(PtpCommand.InitiateCaptureRecInMedia); if (performAf) cmd.addParam(0xfffffffe); // perform AF before capture else cmd.addParam(0xffffffff); // no AF before capture if (captureToSdram) cmd.addParam(0x0001); else cmd.addParam(0x0000); } else { // check if need AF before capture cmd = new PtpCommand(PtpCommand.InitiateCapture); if (captureToSdram) { if (performAf) { if (getIsCommandSupported(PtpCommand.AfAndCaptureRecInSdram)) cmd = new PtpCommand(PtpCommand.AfAndCaptureRecInSdram); } else if (getIsCommandSupported(PtpCommand.InitiateCaptureRecInSdram)) cmd = new PtpCommand(PtpCommand.InitiateCaptureRecInSdram) .addParam(0xffffffff); } if (!performAf) { PtpProperty property = getPtpProperty(PtpProperty.AfModeSelect); if (property != null) { Integer oldAfMode = (Integer) property.getValue(); if (oldAfMode != 4) { setDevicePropValue(PtpProperty.AfModeSelect, 4, true); mOldAFMode = oldAfMode; mAfModeChanged = true; } } } } return cmd; } public void initiateCaptureCmd() { initiateCaptureCmd(true); } private boolean mIsInCapture = false; private void initiateCapture(boolean checkNeedReturnToLV, boolean captureToSdram, boolean performAf) { if (checkNeedReturnToLV) checkNeedReturnToLiveView(captureToSdram); Log.d(TAG, "Initiate capture"); sendPtpDeviceEvent(PtpDeviceEvent.CaptureInitiated, null); PtpCommand cmd = sendCommand(initiateCaptureCommand(captureToSdram, performAf)); if (cmd != null && cmd.isResponseOk()) { boolean again = false; do { again = false; cmd = sendCommand(new PtpCommand(PtpCommand.DeviceReady)); if (cmd != null) { switch (cmd.getResponseCode()) { case PtpResponse.OK: Log.i(TAG, "Initiate capture ok"); break; case PtpResponse.DeviceBusy: Log.i(TAG, "Initiate capture busy"); try { Thread.sleep(20); } catch (InterruptedException e) { } again = true; break; default: Log.i(TAG, "Initiate capture error: " + String.format("%04X", cmd.getResponseCode())); break; } } } while (again); mIsInCapture = true; sendPtpDeviceEvent(PtpDeviceEvent.CaptureStart, null); if (mAfModeChanged) { setDevicePropValue(PtpProperty.AfModeSelect, mOldAFMode, true); mAfModeChanged = false; } } else sendPtpDeviceEvent(PtpDeviceEvent.BusyEnd, null); } public void initiateCaptureCmd(final boolean checkNeedReturnToLV) { initiateCaptureCmd(checkNeedReturnToLV, mCaptureToSdram); } public void initiateCaptureCmd(final boolean checkNeedReturnToLV, final boolean captureToSdram) { sendPtpDeviceEvent(PtpDeviceEvent.BusyBegin, null); new Thread(new Runnable() { public void run() { if (mIsCustomBracketingEnabled) initCustomBracketing(); else initiateCapture(checkNeedReturnToLV, captureToSdram, mAFBeforeCapture); } }).start(); } private void captureComplete() { if (mNeedBracketing) nextBracketingImage(); if (mIsInFocusStacking) nextFocusStackingImage(); if (!mNeedBracketing && !mTimelapseRunning && !mIsInFocusStacking) { sendPtpDeviceEvent(PtpDeviceEvent.BusyEnd, null); checkReturnToLiveView(); } } public void startAfDriveCmd() { new Thread(new Runnable() { public void run() { sendCommand(new PtpCommand(PtpCommand.AfDrive)); } }).start(); } private void startEventListener() { if (!mCommunicator.getIsNetworkCommunicator()) { if (!mDeviceInfo.supportsOperation(PtpCommand.GetEvent)) { PtpUsbCommunicator communicator = (PtpUsbCommunicator) mCommunicator; if (communicator != null) { Log.d(TAG, "----- Using interrupt endpoint for events"); mEventThread = new InterruptEventThread( communicator.getUsbDeviceConnection(), communicator.getInterrupEp()); mEventThread.start(); } } else { Log.d(TAG, "----- Using the GetEvent command for events"); mEventThread = new EventThread(); mEventThread.start(); } } } private synchronized void processEvent(int eventCode, int eventParam) { // Log.d(MainActivity.TAG, "+*+*+*+* event code: " + // Integer.toHexString(eventCode) + " param: " + // Integer.toHexString(eventParam)); switch (eventCode) { case PtpEvent.CancelTransaction: Log.d(TAG, "CancelTransaction: " + String.format("%#x", eventParam)); break; case PtpEvent.ObjectAdded: Log.d(TAG, "ObjectAdded: " + String.format("%#x", eventParam)); PtpObjectInfo info = getObjectInfo(eventParam); sendPtpDeviceEvent(PtpDeviceEvent.ObjectAdded, info); break; case PtpEvent.StoreAdded: Log.d(TAG, "StoreAdded: " + String.format("%#x", eventParam)); getStorageInfo(eventParam); sendPtpDeviceEvent(PtpDeviceEvent.SdCardInserted, eventParam >> 16); break; case PtpEvent.StoreRemoved: Log.d(TAG, "StoreRemoved: " + String.format("%#x", eventParam)); // remove the store mPtpStorages.remove(eventParam); sendPtpDeviceEvent(PtpDeviceEvent.SdCardRemoved, eventParam >> 16); break; case PtpEvent.DevicePropChanged: Log.d(TAG, "DevicePropChanged: " + String.format("%#x", eventParam)); updateDevicePropDescCmd(eventParam); // getDevicePropDescCommand(eventParam); break; case PtpEvent.DeviceInfoChanged: Log.d(TAG, "DeviceInfoChanged: " + String.format("%#x", eventParam)); break; case PtpEvent.RequestObjectTransfer: Log.d(TAG, "RequestObjectTransfer: " + String.format("%#x", eventParam)); break; case PtpEvent.StoreFull: Log.d(TAG, "StoreFull: " + String.format("%#x", eventParam)); break; case PtpEvent.StorageInfoChanged: Log.d(TAG, "StorageInfoChanged: " + String.format("%#x", eventParam)); getStorageInfo(eventParam); // execute when the capture was executed on camera // mIsInImageAqusition = false; // sendPtpServiceEvent(PtpServiceEventType.CaptureCompleteInSdcard, // null); break; case PtpEvent.CaptureComplete: Log.d(TAG, "CaptureComplete: " + String.format("%#x", eventParam)); mIsInCapture = false; sendPtpDeviceEvent(PtpDeviceEvent.CaptureComplete, null); captureComplete(); break; case PtpEvent.ObjectAddedInSdram: Log.d(TAG, "ObjectAddedInSdram: " + String.format("%#x", eventParam)); sendPtpDeviceEvent(PtpDeviceEvent.ObjectAddedInSdram, null); // mIsInImageAqusition = true; // if (mEventThread != null) // mEventThread.setPauseEventListener(true); // sendPtpServiceEvent(PtpServiceEventType.GetObjectFromSdramStart, // null); if (mProductId == 0x0412) getPictureFromSdram(0xFFFF0001, true); else getPictureFromSdram(eventParam, true); break; case PtpEvent.CaptureCompleteRecInSdram: Log.d(TAG, "CaptureCompleteRecInSdram: " + String.format("%#x", eventParam)); mIsInCapture = false; sendPtpDeviceEvent(PtpDeviceEvent.CaptureCompleteInSdram, null); captureComplete(); break; case PtpEvent.PreviewImageAdded: Log.d(TAG, "PreviewImageAdded: " + String.format("%#x", eventParam)); break; } } private class EventThread extends ThreadBase { public EventThread() { mSleepTime = 100; } @Override public void codeToExecute() { // Log.d(TAG, "get DSLR events"); PtpCommand cmd = sendCommand(getEventCmd()); if (cmd != null) { if (cmd.isDataOk()) { cmd.incomingData().parse(); int numEvents = cmd.incomingData().nextU16(); int eventCode, eventParam; for (int i = 1; i <= numEvents; i++) { eventCode = cmd.incomingData().nextU16(); eventParam = cmd.incomingData().nextS32(); processEvent(eventCode, eventParam); } } } else this.interrupt(); } } private class InterruptEventThread extends ThreadBase { private UsbDeviceConnection mUsbDeviceConnection = null; private UsbEndpoint mInterruptEp = null; public InterruptEventThread(UsbDeviceConnection usbDeviceConnection, UsbEndpoint interruptEp) { mUsbDeviceConnection = usbDeviceConnection; mInterruptEp = interruptEp; mSleepTime = 400; } private void processInterrupPacket(byte[] data) throws ExecutionException { PtpBuffer buf = new PtpBuffer(data); int eventCode = buf.getPacketCode(); buf.parse(); int eventParam = buf.nextS32(); Log.d(TAG, "++=====++ New interrupt packet: " + buf.getPacketLength() + " type: " + buf.getPacketType() + " code:" + String.format("%#x", buf.getPacketCode())); processEvent(eventCode, eventParam); } @Override public void codeToExecute() { PtpBuffer buf = new PtpBuffer(); byte[] tmpData = new byte[4096]; byte[] data = null; boolean needMore = false; int counter = 0, size = 0, bytesRead = 0; try { if (needMore) { bytesRead = mUsbDeviceConnection.bulkTransfer(mInterruptEp, tmpData, tmpData.length, 200); if (bytesRead > 0) { Log.d(TAG, "bytes read: " + bytesRead); System.arraycopy(tmpData, 0, data, counter, bytesRead); counter += bytesRead; if (counter >= size) { needMore = false; processInterrupPacket(data); } } } else { bytesRead = mUsbDeviceConnection.bulkTransfer(mInterruptEp, tmpData, tmpData.length, 200); if (bytesRead > 0) { Log.d(TAG, "bytes read: " + bytesRead); buf.wrap(tmpData); size = buf.getPacketLength(); Log.d(TAG, "packet size " + size); data = new byte[size]; System.arraycopy(tmpData, 0, data, 0, bytesRead); if (buf.getPacketLength() > bytesRead) { needMore = true; counter = bytesRead; } else processInterrupPacket(data); } } } catch (ExecutionException e) { this.interrupt(); } } } public void enterLiveViewAtStart() { new Thread(new Runnable() { public void run() { Log.i(TAG, "Entering live view at start"); Log.i(TAG, "Setting recording media to sdram"); setDevicePropValue(PtpProperty.RecordingMedia, 0x0001, true); Log.i(TAG, "Starting live view"); startLiveViewDisplay(true); } }).start(); } protected int startLiveView() { setDevicePropValue(PtpProperty.RecordingMedia, 0x0001, true); PtpCommand cmd = sendCommand(new PtpCommand(PtpCommand.StartLiveView)); if (cmd != null) { boolean again = false; do { cmd = sendCommand(new PtpCommand(PtpCommand.DeviceReady)); if (cmd != null) { switch (cmd.getResponseCode()) { case PtpResponse.OK: Log.i(TAG, "Live view start ok"); return PtpResponse.OK; case PtpResponse.DeviceBusy: Log.i(TAG, "Live view start busy"); try { Thread.sleep(20); } catch (InterruptedException e) { } again = true; break; default: Log.i(TAG, "Live view start error"); return 0; } } } while (again); } else Log.i(TAG, "Live view start error"); return 0; } protected void startLiveViewDisplay(boolean notiftyUI) { switch (startLiveView()) { case PtpResponse.OK: if (notiftyUI) sendPtpDeviceEvent(PtpDeviceEvent.LiveviewStart); break; } } public void startLiveViewCmd() { if (mIsPtpDeviceInitialized) { new Thread(new Runnable() { public void run() { startLiveViewDisplay(true); } }).start(); } } protected int endLiveView() { // it's a bit hard to stop so try it 3 times Log.d(TAG, "Stop live view"); PtpCommand cmd = sendCommand(new PtpCommand(PtpCommand.EndLiveView)); if (cmd != null) { Log.d(TAG, "Stop live view response " + cmd.isResponseOk()); if (cmd.isResponseOk()) return PtpResponse.OK; boolean again = false; do { Log.d(TAG, "Stop live view deviceready"); cmd = sendCommand(new PtpCommand(PtpCommand.DeviceReady)); if (cmd != null) { switch (cmd.getResponseCode()) { case PtpResponse.OK: Log.i(TAG, "Live view end ok"); setDevicePropValue(PtpProperty.RecordingMedia, 0x0000, true); return PtpResponse.OK; case PtpResponse.DeviceBusy: Log.i(TAG, "Live view end busy"); try { Thread.sleep(20); } catch (InterruptedException e) { } again = true; break; default: Log.i(TAG, "Live view end error"); return 0; } } } while (again); } else { Log.i(TAG, "Live view end error "); } return 0; } protected void endLiveViewDisplay(boolean notifyUI) { // if (mLiveviewThread != null) // mLiveviewThread.setIsLiveviewEnabled(false); switch (endLiveView()) { case PtpResponse.OK: if (notifyUI) { sendPtpDeviceEvent(PtpDeviceEvent.LiveviewStop); sendPtpDeviceEvent(PtpDeviceEvent.MovieRecordingEnd); mIsMovieRecordingStarted = false; } break; } } public void endLiveViewCmd(final boolean notifyUI) { if (mIsPtpDeviceInitialized) { new Thread(new Runnable() { public void run() { endLiveViewDisplay(notifyUI); } }).start(); } } public void startMovieRecCmd() { if (!mIsMovieRecordingStarted) { PtpCommand cmd = sendCommand(new PtpCommand( PtpCommand.StartMovieRecInCard)); if (cmd != null && cmd.isResponseOk()) { mIsMovieRecordingStarted = true; sendPtpDeviceEvent(PtpDeviceEvent.MovieRecordingStart, null); } } } public void stopMovieRecCmd() { PtpCommand cmd = sendCommand(new PtpCommand(PtpCommand.EndMovieRec)); if (cmd != null && cmd.isResponseOk()) { mIsMovieRecordingStarted = false; sendPtpDeviceEvent(PtpDeviceEvent.MovieRecordingEnd, null); } } public File getObjectSaveFile(String objectName, boolean copyFileName) { File folder = new File(mSdramSavingLocation); if (!folder.exists()) { Log.d(TAG, "Make dir: " + folder.mkdir()); } File f; if (!copyFileName) { int dotposition = objectName.lastIndexOf("."); String ext = objectName.substring(dotposition + 1, objectName.length()); f = new File(folder, String.format("%s%04d.%s", mSdramPrefix, mSdramPictureNumbering, ext)); setSdramPictureNumbering(mSdramPictureNumbering + 1); } else f = new File(folder,objectName); Log.d(TAG, "File name: " + f); return f; } private void runMediaScanner(File file) { Uri contentUri = Uri.fromFile(file); Intent mediaScanIntent = new Intent( "android.intent.action.MEDIA_SCANNER_SCAN_FILE"); mediaScanIntent.setData(contentUri); mPtpService.sendBroadcast(mediaScanIntent); } public void getObjectFromCamera(final ImageObjectHelper obj, PtpPartialObjectProccessor.PtpPartialObjectProgressListener listener) { PtpPartialObjectProccessor.PtpPartialObjectProgressListener mListener = new PtpPartialObjectProccessor.PtpPartialObjectProgressListener() { public void onProgress(int offset) { Log.d(TAG, "Progress"); obj.progress = offset; sendPtpDeviceEvent( PtpDeviceEvent.GetObjectFromCameraProgress, obj); } }; if (listener != null) mListener = listener; if (obj != null && obj.objectInfo != null) { sendPtpDeviceEvent(PtpDeviceEvent.GetObjectFromCamera, obj); obj.file = getObjectSaveFile(obj.objectInfo.filename, true); int maxSize = 0x200000; if (obj.objectInfo.objectCompressedSize < maxSize) maxSize = (int) (obj.objectInfo.objectCompressedSize / 2); PtpCommand cmd = sendCommand(getPartialObjectCmd( obj.objectInfo, maxSize, obj.file, mListener )); if (cmd != null && cmd.isDataOk()) { runMediaScanner(obj.file); sendPtpDeviceEvent(PtpDeviceEvent.GetObjectFromCameraFinished, obj); } } } private void getPictureFromSdram(int objectId, boolean fromSdram) { if (mEventThread != null) mEventThread.setIsThreadPaused(true); try { final ImageObjectHelper helper = new ImageObjectHelper(); helper.galleryItemType = ImageObjectHelper.PHONE_PICTURE; PtpCommand cmd = sendCommand(getObjectInfoCmd(objectId)); if (cmd != null && cmd.isDataOk()) { helper.objectInfo = new PtpObjectInfo(objectId, cmd.incomingData()); helper.file = getObjectSaveFile(helper.objectInfo.filename, false); sendPtpDeviceEvent(PtpDeviceEvent.GetObjectFromSdramInfo, helper); cmd = sendCommand(getThumbCmd(objectId)); if (cmd != null && cmd.isDataOk()) { helper.saveThumb(cmd.incomingData(), fromSdram); sendPtpDeviceEvent(PtpDeviceEvent.GetObjectFromSdramThumb, helper); int maxSize = 0x200000; if (helper.objectInfo.objectCompressedSize < maxSize) maxSize = (int) (helper.objectInfo.objectCompressedSize / 2); cmd = sendCommand(getPartialObjectCmd( helper.objectInfo, maxSize, helper.file, new PtpPartialObjectProccessor.PtpPartialObjectProgressListener() { public void onProgress(int offset) { Log.d(TAG, "Progress"); helper.progress = offset; sendPtpDeviceEvent( PtpDeviceEvent.GetObjectFromSdramProgress, helper); } })); if (cmd != null && cmd.isDataOk()) { // TODO : gps // if (mPreferencesHelper.mAddGpsLocation) { // addGpsLocation(helper.file); // } // else if (mGpsInfoEnabled) { GpsLocationHelper gpsHelper = mPtpService.getGpsLocationHelper(); gpsHelper.addGpsLocation(helper.file); } else { runMediaScanner(helper.file); sendPtpDeviceEvent( PtpDeviceEvent.GetObjectFromSdramFinished, helper); } } } } } finally { if (mEventThread != null) { mEventThread.setIsThreadPaused(false); } } } private Object mCurrentEv = null; private Object[] mEvValues; public int mBracketingCount = 0; public int mCurrentBracketing = 0; public boolean mNeedBracketing = false; public boolean getNeedBracketing() { return mNeedBracketing; } public int getBracketingCount() { return mBracketingCount; } public int getCurrentBracketing() { return mCurrentBracketing; } private void initCustomBracketing() { PtpProperty prop = getPtpProperty(PtpProperty.ExposureBiasCompensation); // PtpProperty afProp = getPtpProperty(PtpProperty.AfModeSelect); // if (afProp != null){ // mAfValue = afProp.getValue(); // } // else // mAfValue = null; mCurrentBracketing = 0; mBracketingCount = 0; if (prop != null){ mCurrentEv = prop.getValue(); mEvValues = new Object[mBktCount]; final Vector<?> enums = prop.getEnumeration(); int currentEv = enums.indexOf(prop.getValue()); int evIndex = currentEv; int evCounter = 0; switch(mBktDirection) { case 0: // negative do { mEvValues[evCounter] = enums.get(evIndex); evCounter++; evIndex -= mBktStep; mBracketingCount++; } while (evIndex >= 0 && evCounter < mBktCount); break; case 1: // positive do { mEvValues[evCounter] = enums.get(evIndex); evCounter++; evIndex += mBktStep; mBracketingCount++; } while (evIndex < enums.size() && evCounter < mBktCount); break; case 2: // both mEvValues[evCounter] = enums.get(evIndex); mBracketingCount = 1; evCounter++; int counter = 1; do { evIndex = counter * mBktStep; if ((currentEv - evIndex) >= 0 && (currentEv + evIndex) <= enums.size()){ mEvValues[evCounter] = enums.get(currentEv + evIndex); mEvValues[evCounter + 1] = enums.get(currentEv - evIndex); mBracketingCount += 2; } counter++; evCounter += 2; } while (evCounter < mBktCount); break; } mNeedBracketing = mBracketingCount > 0; // set focus to manual // mService.setDevicePropValue(PtpProperty.AfModeSelect, 0x0004, true); nextBracketingImage(); } } private void nextBracketingImage() { Log.d(TAG, "Custom bracketing image: " + mCurrentBracketing); Log.d(TAG, "Custom bracketing focus first: " + mBktFocusFirst); if (mCurrentBracketing < mBracketingCount) { setDevicePropValue(PtpProperty.ExposureBiasCompensation, mEvValues[mCurrentBracketing], true); if (mCurrentBracketing == 0) initiateCapture(true, mCaptureToSdram, mBktFocusFirst); else initiateCapture(false, mCaptureToSdram, false); //mService.sendCommandNew(mService.getShootCommand(mToSdram)); mCurrentBracketing++; } else { mNeedBracketing = false; // if (mAfValue != null) // mService.setDevicePropValue(PtpProperty.AfModeSelect, mAfValue, true); if (mCurrentEv != null) setDevicePropValue(PtpProperty.ExposureBiasCompensation, mCurrentEv, true); } } private boolean mTimelapseRunning = false; private int mTimelapseRemainingIterations = 10; public boolean getIsTimelapseRunning(){ return mTimelapseRunning; } public int getTimelapseRemainingIterations(){ return mTimelapseRemainingIterations; } private Runnable timelapseTask = new Runnable() { public void run() { if (!mIsInCapture) { Log.d(TAG, "Timelapse image capture"); if (mTimelapseRemainingIterations == mTimelapseIterations) initiateCaptureCmd(true); else initiateCaptureCmd(false); } mTimelapseRemainingIterations -= 1; sendPtpDeviceEvent(PtpDeviceEvent.TimelapseEvent, mTimelapseRemainingIterations); if (mTimelapseRemainingIterations == 0){ stopTimelapseExecutor(); return; } Log.d(TAG, "----- Timelapse event ----- iterations remain: " + mTimelapseRemainingIterations); } }; ScheduledExecutorService mTimelapseScheduler; public void startTimelapse(long interval, int frameCount){ Log.d(TAG, "---- Timelapse started ----"); mTimelapseRunning = true; setTimelapseIterations(frameCount); setTimelapseInterval(interval); mTimelapseRemainingIterations = frameCount; mTimelapseScheduler = Executors.newSingleThreadScheduledExecutor(); mTimelapseScheduler.scheduleAtFixedRate(timelapseTask, 100, mTimelapseInterval, TimeUnit.MILLISECONDS); sendPtpDeviceEvent(PtpDeviceEvent.TimelapseStarted, null); } public void stopTimelapse() { stopTimelapseExecutor(); if (!mIsInCapture && mNeedBracketing) captureComplete(); } private void stopTimelapseExecutor(){ Log.d(TAG, "---- Timelapse stoped ----"); stopExecutor(mTimelapseScheduler); mTimelapseScheduler = null; mTimelapseRunning = false; sendPtpDeviceEvent(PtpDeviceEvent.TimelapseStoped, null); } private int mFocusImages = 5; private int mFocusStep = 10; private boolean mFocusDirectionDown = true; private boolean mFocusFocusFirst = false; private boolean mIsInFocusStacking = false; private int mFocusStackingCurrentImage = 1; private boolean mStopFocusStacking = false; public int getFocusImages() { return mFocusImages; } public void setFocusImages(int value) { mFocusImages = value; mPrefs .edit() .putString(PREF_KEY_FOCUS_IMAGES, Integer.toString(mFocusImages)) .commit(); } public int getFocusStep(){ return mFocusStep; } public void setFocusStep(int value) { mFocusStep = value; mPrefs .edit() .putString(PREF_KEY_FOCUS_STEPS, Integer.toString(mFocusStep)) .commit(); } public boolean getFocusDirectionDown(){ return mFocusDirectionDown; } public void setFocusDirectionDown(boolean value){ mFocusDirectionDown = value; mPrefs .edit() .putBoolean(PREF_KEY_FOCUS_DIRECTION_DOWN, mFocusDirectionDown) .commit(); } public boolean getFocusFocusFirst(){ return mFocusFocusFirst; } public void setFocusFocusFirst(boolean value) { mFocusFocusFirst = value; mPrefs .edit() .putBoolean(PREF_KEY_FOCUS_FOCUS_FIRST, mFocusFocusFirst) .commit(); } public int getCurrentFocusStackingImage() { return mFocusStackingCurrentImage; } public boolean getIsInFocusStacking() { return mIsInFocusStacking; } public void stopFocusStacking() { mStopFocusStacking = true; } public boolean getStopFocusStacking() { return mStopFocusStacking; } public void startFocusStacking(int imagesToTake, int focusSteps, boolean directionDown, boolean focusFirst) { setFocusImages(imagesToTake); setFocusStep(focusSteps); setFocusDirectionDown(directionDown); setFocusFocusFirst(focusFirst); mStopFocusStacking = false; mIsInFocusStacking = true; mFocusStackingCurrentImage = 1; new Thread(new Runnable() { public void run() { sendPtpDeviceEvent(PtpDeviceEvent.BusyBegin, null); nextFocusStackingImage(); } }).start(); //nextFocusStackingImage(); } private void nextFocusStackingImage() { Log.d(TAG, "Focus stacking image: " + mFocusStackingCurrentImage); if (mStopFocusStacking) { mIsInFocusStacking = false; mStopFocusStacking = false; captureComplete(); return; } if (mFocusStackingCurrentImage == 1) { initiateCapture(true, mCaptureToSdram, mFocusFocusFirst); mFocusStackingCurrentImage++; } else { if (mFocusStackingCurrentImage <= mFocusImages) { // start live startLiveView(); // get the afmode Object afMode = null; PtpProperty property = getPtpProperty(PtpProperty.AfModeSelect); if (property != null) afMode = property.getValue(); // set afmode to af-s setDevicePropValue(PtpProperty.AfModeSelect, 0, true); // move the focus seekFocus(mFocusDirectionDown ? 1 : 2, mFocusStep); // set back the afmode setDevicePropValue(PtpProperty.AfModeSelect, afMode, true); // stop live view endLiveView(); initiateCapture(false, mCaptureToSdram, false); mFocusStackingCurrentImage++; } else mIsInFocusStacking = false; } } public void seekFocusMin() { boolean repeat = true; while(repeat) { repeat = seekFocus(1, 32767) == PtpResponse.OK; } } public void seekFocusMax() { boolean repeat = true; while(repeat) { repeat = seekFocus(2, 32767) == PtpResponse.OK; } } public int seekFocus(int direction, int amount) { Log.i(TAG, "Seek focus direction: " + direction + " step: " + amount); boolean again = false; int retry = 0; int res = 0; do { res = driveFocusToEnd(direction, amount); switch(res) { case PtpResponse.OK: Log.i(TAG, "Seek focus OK"); again = false; break; case PtpResponse.MfDriveStepEnd: retry += 1; Log.i(TAG, "Seek focus MfDriveStepEnd retry: " + retry); if (retry < 5) again = true; else again = false; break; case PtpResponse.MfDriveStepInsufficiency: Log.i(TAG, "Seek focus MfDriveStepInsufficiency retry: " + retry); if (retry > 0) { again = false; } else { retry += 1; again = true; } break; default: Log.i(TAG, "Seek focus other: " + res); again = false; break; } } while (again) ; return res; } private int driveFocusToEnd(int direction, int step) { boolean again = true; PtpCommand cmd; cmd = sendCommand(getMfDriveCommand(direction, step)); if (cmd != null) { switch(cmd.getResponseCode()) { case PtpResponse.OK: // do a deviceready command again = true; while(again) { cmd = sendCommand(new PtpCommand(PtpCommand.DeviceReady)); if (cmd != null) { switch (cmd.getResponseCode()){ case PtpResponse.DeviceBusy: // we do another deviceready // do some pause try { Thread.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); } break; default: // for all other cases assume there is an error return cmd.getResponseCode(); } } else return 0; } break; default: return cmd.getResponseCode(); } } else return 0; return 0; } private PtpCommand getMfDriveCommand(int direction, int amount) { return new PtpCommand(PtpCommand.MfDrive) .addParam(direction) .addParam(amount); } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Comparator; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; public class ImageObjectHelper { public final static int DSLR_PICTURE = 0; public final static int PHONE_PICTURE = 1; private static String TAG = "ImageObjectHelper"; public PtpObjectInfo objectInfo = null; public File file = null; public int progress = 0; public boolean isChecked = false; public int galleryItemType = 0; public ImageObjectHelper(){ } public String getFileExt(String FileName) { String ext = FileName.substring((FileName.lastIndexOf(".") + 1), FileName.length()); return ext.toLowerCase(); } public boolean tryLoadThumb(String ext) { File thumbFile = getThumbFilePath(ext); if (thumbFile.exists()){ if (!ext.equals("ppm")) { return true; } else return true; } return false; } public File getThumbFilePath( String ext){ File f = new File(file.getParent() + "/.thumb"); if (!f.exists()) f.mkdir(); String fname = file.getName(); if (!ext.isEmpty()) return new File(f, fname + "." + ext); else return new File(f, fname); } public void saveThumb(PtpBuffer data, boolean fromSdram){ Bitmap bmp = null; switch(objectInfo.objectFormatCode){ case PtpObjectInfo.EXIF_JPEG: bmp = BitmapFactory.decodeByteArray(data.data(), 12, data.data().length - 12); break; case PtpObjectInfo.Undefined: if (fromSdram) // if from sdram the the thumb is in raw format bmp = createThumbFromRaw(data); else bmp = BitmapFactory.decodeByteArray(data.data(), 12, data.data().length - 12); break; } if (bmp != null) { FileOutputStream fOut; try { fOut = new FileOutputStream(getThumbFilePath("jpg")); bmp.compress(Bitmap.CompressFormat.JPEG, 85, fOut); fOut.flush(); fOut.close(); bmp.recycle(); } catch (Exception e) { } } } public void deleteImage(){ if (file.exists()) file.delete(); File tf = getThumbFilePath("png"); if (tf.exists()) tf.delete(); tf = getThumbFilePath("jpg"); if (tf.exists()) tf.delete(); } private Bitmap createThumbFromRaw(PtpBuffer data){ int stride = ((160 * 24 + 25) & ~25) / 8; int[] colors = createColors(160,120,stride, data); return Bitmap.createBitmap(colors, 0, stride, 160, 120, Bitmap.Config.ARGB_8888); } private static int[] createColors(int width, int height, int stride, PtpBuffer data) { data.parse(); int[] colors = new int[stride * height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int r = data.nextU8(); int g = data.nextU8(); int b = data.nextU8(); int a = 255; colors[y * stride + x] = (a << 24) | (r << 16) | (g << 8) | b; } } return colors; } // public boolean savePictureData(byte[] data){ // if (file != null){ // OutputStream out = null; // try { // out = new BufferedOutputStream(new FileOutputStream(file, false)); // out.write(data); // return true; // } catch (Exception e) { // Log.d(TAG, "File open error"); // return false; // } // finally { // if (out != null) // try { // out.close(); // } catch (IOException e) { // Log.d(TAG, "Error closing stream"); // } // } // } // else { // Log.d(TAG, "Error file name not set!"); // return false; // } // } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import android.app.Activity; import android.app.Fragment; import android.content.SharedPreferences; import android.graphics.PorterDuffColorFilter; import android.os.Bundle; import android.os.Handler; import android.os.Vibrator; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; public class LiveViewFragment extends DslrFragmentBase { private LvSurfaceBase mLvSurface; private boolean mIsAttached = false; private final static String TAG = "LiveViewFragment"; private LiveviewThread mLvThread = null; private ImageView mLvHistgoram, mOsdToggle; private int mHistogramMode = 0; //0 - no histogram, 1 - separate, 2 - one private PorterDuffColorFilter mColorFilterRed; private ImageView mFocsuToggle; private RelativeLayout mFocusLayout; private CheckableImageView mFocusMin, mFocusMax; private AutoRepeatImageView mFocusLeft, mFocusRight; private TextView mFocusStepDisplay; private SeekBar mFocusStepSeekBar; private int mFocusStep = 10; private int mOsdMode = 3; private boolean mFocusLayoutVisible = false; @Override public void onAttach(Activity activity) { mIsAttached = true; super.onAttach(activity); } @Override public void onDetach() { mIsAttached = false; super.onDetach(); } @Override public void onStart() { Log.d(TAG, "onStart"); super.onStart(); } @Override public void onResume() { Log.d(TAG, "onResume"); mLvThread = new LiveviewThread(); mLvThread.start(); super.onResume(); } @Override public void onPause() { Log.d(TAG, "onPause"); stopLvThread(); super.onPause(); } @Override public void onStop() { Log.d(TAG, "onStop"); super.onStop(); } @Override public void onDestroy() { Log.d(TAG, "onDestroy"); super.onDestroy(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.liveview_fragment, container, false); mColorFilterRed = new PorterDuffColorFilter(getResources().getColor(R.color.Red), android.graphics.PorterDuff.Mode.SRC_ATOP); mLongPressTimeout = ViewConfiguration.getLongPressTimeout(); mScaledTouchSlop = ViewConfiguration.get(getActivity()).getScaledTouchSlop(); mVibrator = (Vibrator)getActivity().getSystemService("vibrator"); mScaledMaximumFlingVelocity = ViewConfiguration.get(getActivity()).getScaledMaximumFlingVelocity(); mOsdToggle = (ImageView)view.findViewById(R.id.lvosdtoggle); mFocsuToggle = (ImageView)view.findViewById(R.id.lvfocustoggle); mFocusLayout = (RelativeLayout)view.findViewById(R.id.lvfocuslayout); mFocusMin = (CheckableImageView)view.findViewById(R.id.lvfocusmin); mFocusMax = (CheckableImageView)view.findViewById(R.id.lvfocusmax); mFocusLeft = (AutoRepeatImageView)view.findViewById(R.id.lvfocusleft); mFocusRight = (AutoRepeatImageView)view.findViewById(R.id.lvfocusright); mFocusStepDisplay = (TextView)view.findViewById(R.id.lvfocusstep); mFocusStepSeekBar = (SeekBar)view.findViewById(R.id.lvfocusstepseekbar); mFocusLayout.setVisibility(View.GONE); mFocusStepSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { public void onStopTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { mFocusStep = progress; mFocusStepDisplay.setText(Integer.toString(mFocusStep)); } } }); mFocusMin.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { getPtpDevice().seekFocusMin(); } }); mFocusMax.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { getPtpDevice().seekFocusMax(); } }); mFocusLeft.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { getPtpDevice().seekFocus(1, mFocusStep); } }); mFocusRight.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { getPtpDevice().seekFocus(2, mFocusStep); } }); mFocsuToggle.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mFocusLayoutVisible = !mFocusLayoutVisible; mFocusLayout.setVisibility(mFocusLayoutVisible ? View.VISIBLE : View.GONE); mFocsuToggle.setColorFilter(mFocusLayoutVisible ? mColorFilterRed : null); } }); mOsdToggle.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (mOsdMode == 0) mOsdMode = 3; else mOsdMode--; } }); mLvHistgoram = (ImageView)view.findViewById(R.id.lv_histogram); mLvHistgoram.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (mHistogramMode == 2) mHistogramMode = 0; else mHistogramMode++; if (mHistogramMode > 0) mLvHistgoram.setColorFilter(mColorFilterRed); else mLvHistgoram.setColorFilter(null); } }); mLvSurface = (LvSurfaceBase)view.findViewById(R.id.lvsurface); mLvSurface.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { if (getIsPtpDeviceInitialized()){ final int action = event.getAction(); final float x = event.getX(); final float y = event.getY(); if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(event); switch (action) { case MotionEvent.ACTION_DOWN: v.postDelayed(mLongPressRunnable, mLongPressTimeout); mDownX = x; mDownY = y; calculateMfDriveStep(v.getHeight(), y); break; case MotionEvent.ACTION_MOVE: { switch(mMode) { case TOUCH: final float scrollX = mDownX - x; final float scrollY = mDownY - y; final float dist = (float)Math.sqrt(scrollX * scrollX + scrollY * scrollY); if (dist >= mScaledTouchSlop) { v.removeCallbacks(mLongPressRunnable); mMode = TouchMode.PAN; } break; case PAN: break; case LVZOOM: int mdy = Math.round(((x - mDownX) / v.getWidth()) * 10); if (mdy > mZoomY){ zoomLiveView(true); } else if (mdy < mZoomY){ zoomLiveView(false); } mZoomY = mdy; break; case LVFOCUSSTART: Log.d(TAG, "Focus start"); getPtpDevice().seekFocusMin(); mMode = TouchMode.LVFOCUS; break; case LVFOCUSEND: Log.d(TAG, "Focus end"); getPtpDevice().seekFocusMax(); mMode = TouchMode.LVFOCUS; break; case LVFOCUS: // int focusValue = Math.round((_dslrHelper.getPtpService().getPreferences().mFocusMax * x) / v.getWidth()); // _dslrHelper.getPtpService().seekFocus(focusValue); break; } break; } case MotionEvent.ACTION_UP: switch(mMode) { case LVZOOM: break; case LVFOCUS: break; case PAN: if ((x - mDownX) > 200){ getPtpDevice().initiateCaptureCmd(); Log.d(TAG, "Pan left to right"); } // else if ((mDownX - x) > 200) { // _dslrHelper.getPtpService().initiateCaptureRecInSdramCmd(); // Log.d(TAG, "Pan right to lef"); // } else if ((y - mDownY) > 200) { if (getPtpDevice().getIsMovieRecordingStarted()) getPtpDevice().stopMovieRecCmd(); else getPtpDevice().startMovieRecCmd(); Log.d(TAG, "Pan top to bottom"); } // else if ((mDownY - y) > 200) { // Log.d(TAG, "Pan bottom to top"); // } // // mVelocityTracker.computeCurrentVelocity(1000, mScaledMaximumFlingVelocity); break; case TOUCH: lvAfx = x; lvAfy = y; long currentTime = System.currentTimeMillis(); if ((currentTime - lastTime) < 200) { lastTime = -1; v.removeCallbacks(mSingleTapRunnable); // lvSurfaceDoubleTap(); } else { lastTime = currentTime; v.postDelayed(mSingleTapRunnable, 200); } break; } mVelocityTracker.recycle(); mVelocityTracker = null; v.removeCallbacks(mLongPressRunnable); mMode = TouchMode.TOUCH; break; default: mVelocityTracker.recycle(); mVelocityTracker = null; v.removeCallbacks(mLongPressRunnable); mMode = TouchMode.TOUCH; break; } } return true; } }); return view; } public enum TouchMode { TOUCH, PAN, LVZOOM, LVFOCUS, LVFOCUSSTART, LVFOCUSEND } private long lastTime = -1; private int mfDriveStep = 200; /** Time of tactile feedback vibration when entering zoom mode */ private static final long VIBRATE_TIME = 50; /** Current listener mode */ private TouchMode mMode = TouchMode.TOUCH; /** X-coordinate of latest down event */ private float mDownX; /** Y-coordinate of latest down event */ private float mDownY; private int mZoomY; private float focusX; /** Velocity tracker for touch events */ private VelocityTracker mVelocityTracker; /** Distance touch can wander before we think it's scrolling */ private int mScaledTouchSlop; /** Duration in ms before a press turns into a long press */ private int mLongPressTimeout; /** Vibrator for tactile feedback */ private Vibrator mVibrator; /** Maximum velocity for fling */ private int mScaledMaximumFlingVelocity; private boolean mLiveViewNeedFocusChanged = false; private Object _syncRoot = new Object(); private float lvAfx, lvAfy; private final Runnable mLongPressRunnable = new Runnable() { public void run() { if (mDownY < 100) { mMode = TouchMode.LVZOOM; mZoomY = 0; mVibrator.vibrate(VIBRATE_TIME); } else { if (mDownX < 150) mMode = TouchMode.LVFOCUSSTART; else if (mDownX > (mLvSurface.getWidth() - 150)) mMode = TouchMode.LVFOCUSEND; else mMode = TouchMode.LVFOCUS; focusX = mDownX; mVibrator.vibrate(VIBRATE_TIME); } } }; private final Runnable mSingleTapRunnable = new Runnable() { public void run() { synchronized (_syncRoot) { mLiveViewNeedFocusChanged = true; } } }; private void calculateMfDriveStep(int height, float y){ float inv = height - y; float step = inv * 0.205f; int testy = Math.round(inv * step); if (testy < 1) testy = 1; else if (testy > 32767) testy = 32767; mfDriveStep = testy; } private void zoomLiveView(boolean up){ IDslrActivity activity = (IDslrActivity)getActivity(); if (activity != null) activity.zoomLiveView(up); } public synchronized void updateLiveViewImage(PtpLiveViewObject lvo) { lvo.parse(mLvSurface.getFrameWidth(), mLvSurface.getFrameHeight()); if (mLiveViewNeedFocusChanged){ mLiveViewNeedFocusChanged = false; float x = ((lvAfx / lvo.sDw) / lvo.ox) + lvo.dLeft; float y = ((lvAfy / lvo.sDh) / lvo.oy) + lvo.dTop; getPtpDevice().changeAfAreaCmd((int)x, (int)y); } LvSurfaceHelper helper = new LvSurfaceHelper(lvo, getPtpDevice().getPtpProperty(PtpProperty.LiveViewImageZoomRatio), mOsdMode); helper.mHistogramEnabled = mHistogramMode > 0; helper.mHistogramSeparate = mHistogramMode == 1; mLvSurface.processLvObject(helper); } @Override protected void internalInitFragment() { // TODO Auto-generated method stub } @Override protected void internalPtpPropertyChanged(PtpProperty property) { // TODO Auto-generated method stub } @Override protected void ptpDeviceEvent(PtpDeviceEvent event, Object data) { switch(event) { case LiveviewStop: if (mLvThread != null) mLvThread.interrupt(); break; } } private void stopLvThread() { Log.d(TAG, "Stop LV thread"); if (mLvThread != null) { mLvThread.setIsEnabled(false); mLvThread.interrupt(); } } private class LiveviewThread extends ThreadBase { private Boolean mIsEnabled = true; public synchronized void setIsEnabled(boolean isEnabled) { mIsEnabled = true; } public LiveviewThread() { mSleepTime = 100; } @Override public void codeToExecute() { try{ if (!interrupted()) { if (mIsEnabled) { PtpLiveViewObject lvo = getPtpDevice().getLiveViewImage(); if (lvo != null) updateLiveViewImage(lvo); else { Log.d(TAG, "null lvo"); this.interrupt(); } } } } catch (Exception e) { Log.d(TAG, "Live view thread exception " + e.getMessage()); } } } @Override protected void internalSharedPrefsChanged(SharedPreferences prefs, String key) { // TODO Auto-generated method stub } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import android.content.Context; import android.util.AttributeSet; import android.widget.Checkable; import android.widget.RelativeLayout; /** * A special variation of RelativeLayout that can be used as a checkable object. * This allows it to be used as the top-level view of a list view item, which * also supports checking. Otherwise, it works identically to a RelativeLayout. */ public class CheckableRelativeLayout extends RelativeLayout implements Checkable { private boolean mChecked; private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked }; public CheckableRelativeLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected int[] onCreateDrawableState(int extraSpace) { final int[] drawableState = super.onCreateDrawableState(extraSpace + 1); if (isChecked()) { mergeDrawableStates(drawableState, CHECKED_STATE_SET); } return drawableState; } public void toggle() { setChecked(!mChecked); } public boolean isChecked() { return mChecked; } public void setChecked(boolean checked) { if (mChecked != checked) { mChecked = checked; refreshDrawableState(); } } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import java.util.HashMap; import java.util.Iterator; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.hardware.usb.UsbConstants; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbDeviceConnection; import android.hardware.usb.UsbEndpoint; import android.hardware.usb.UsbInterface; import android.hardware.usb.UsbManager; import android.os.IBinder; import android.preference.PreferenceManager; import android.support.v4.app.NotificationCompat; import android.support.v4.app.TaskStackBuilder; import android.util.Log; public class PtpService extends ServiceBase { public interface OnPtpServiceEventListener { public void ServiceEvent(PtpServiceEvent event); } private OnPtpServiceEventListener mOnPtpServiceEventListener = null; public void setOnPtpServiceEventListener(OnPtpServiceEventListener listener) { mOnPtpServiceEventListener = listener; } private static final String TAG = "PtpService"; private void sendPtpServiceEvent(PtpServiceEvent event) { if (mOnPtpServiceEventListener != null && mIsBind) { mOnPtpServiceEventListener.ServiceEvent(event); } } private UsbManager mUsbManager; private UsbDevice mUsbDevice; private UsbDeviceConnection mUsbConnection = null; private UsbInterface mUsbIntf = null; private UsbEndpoint mUsbWriteEp = null; private UsbEndpoint mUsbReadEp = null; private UsbEndpoint mUsbInterruptEp = null; private boolean mIsUsbDevicePresent = false; private boolean mIsUsbDeviceInitialized = false; private boolean mIsUsbInterfaceClaimed = false; private PtpDevice mPtpDevice = null; private GpsLocationHelper mGpsHelper = null; // preferences private SharedPreferences mPrefs = null; public boolean getIsUsbDevicePresent() { return mIsUsbDevicePresent; } public boolean getIsUsbDeviceInitialized() { return mIsUsbDeviceInitialized; } public PtpDevice getPtpDevice() { return mPtpDevice; } public GpsLocationHelper getGpsLocationHelper() { return mGpsHelper; } @Override public IBinder onBind(Intent intent) { cancelNotification(); return super.onBind(intent); } @Override public void onRebind(Intent intent) { Log.d(TAG, "onRebind"); super.onRebind(intent); } private static final String ACTION_USB_PERMISSION = "com.dslr.dashboard.USB_PERMISSION"; PendingIntent mPermissionIntent; private final BroadcastReceiver mUsbPermissionReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.d(TAG, "Intent received " + action); if (ACTION_USB_PERMISSION.equals(action)) { synchronized (this) { UsbDevice usbDevice = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { Log.d(TAG, "USB device permission granted"); mUsbDevice = usbDevice; mIsUsbDevicePresent = true; initUsbConnection(); } } } } }; private final BroadcastReceiver mUsbDeviceDetached = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) { UsbDevice usbDevice = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); if (mUsbDevice == usbDevice) { Log.d(PtpService.TAG, "DSLR USB device detached"); usbDeviceDetached(); } } } }; private void usbDeviceDetached() { Log.d(TAG, "Usb device removed, stoping the service"); sendPtpServiceEvent(PtpServiceEvent.UsbDeviceRemoved); closeUsbConnection(true); mIsUsbDevicePresent = false; if (!mIsBind) stopSelf(); } public void closeUsbConnection() { closeUsbConnection(false); } public void closeUsbConnection(boolean isUsbUnpluged){ Log.d(TAG, "closeUsbConnection"); mPtpDevice.stop(isUsbUnpluged); if (mUsbConnection != null) { if (mIsUsbInterfaceClaimed) { Log.d(TAG, "Releasing USB interface"); mUsbConnection.releaseInterface(mUsbIntf); } Log.d(TAG, "USB connection present, closing"); mUsbConnection.close(); } mIsUsbDevicePresent = false; mUsbIntf = null; mUsbReadEp = null; mUsbWriteEp = null; mUsbInterruptEp = null; mUsbConnection = null; mUsbDevice = null; mIsUsbInterfaceClaimed = false; mIsUsbDeviceInitialized = false; sendPtpServiceEvent(PtpServiceEvent.UsbDeviceRemoved); } @Override public void onCreate() { Log.d(TAG, "onCreate"); super.onCreate(); mGpsHelper = new GpsLocationHelper(this); IntentFilter usbDetachedFilter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED); registerReceiver(mUsbDeviceDetached, usbDetachedFilter); mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0); IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION); registerReceiver(mUsbPermissionReceiver, filter); // get the shared preferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this); // create the ptpdevice mPtpDevice = new PtpDevice(this); try { mUsbManager = (UsbManager)getSystemService(Context.USB_SERVICE); } catch(Exception e) { Log.d(TAG, "UsbManager not available: " + e.getMessage()); } } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "onStartCommand"); return START_STICKY; //super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { Log.d(TAG, "onDestroy"); if (mGpsHelper != null) { mGpsHelper.stopGpsLocator(); mGpsHelper = null; } unregisterReceiver(mUsbDeviceDetached); unregisterReceiver(mUsbPermissionReceiver); super.onDestroy(); } @Override public void onLowMemory() { Log.d(TAG, "onLowMemory"); super.onLowMemory(); } public void stopPtpService(boolean keepAliveIfUsbConnected){ Log.d(TAG, "stopPtpService"); cancelNotification(); if (mIsUsbDeviceInitialized){ if (!keepAliveIfUsbConnected) { closeUsbConnection(); stopSelf(); } else { createNotification(); } } else { stopSelf(); } } private static int mId = 0x0001; private void cancelNotification() { NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.cancel(mId); } private void createNotification() { NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.dslrlauncher) .setContentTitle("DslrDashboard") .setContentText("Running in background"); // Creates an explicit intent for an Activity in your app Intent resultIntent = new Intent(this, MainActivity.class); // The stack builder object will contain an artificial back stack for the // started Activity. // This ensures that navigating backward from the Activity leads out of // your application to the Home screen. TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); // Adds the back stack for the Intent (but not the Intent itself) stackBuilder.addParentStack(MainActivity.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT ); mBuilder.setContentIntent(resultPendingIntent); NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // mId allows you to update the notification later on. mNotificationManager.notify(mId, mBuilder.build()); } public void searchForUsbCamera() { boolean deviceFound = false; try { if (mUsbDevice == null) { Log.d(TAG, "Ptp service usb device not initialized, search for one"); if (mUsbManager != null) { HashMap<String, UsbDevice> devices = mUsbManager.getDeviceList(); Log.d(TAG, "Found USB devices count: " + devices.size()); Iterator<UsbDevice> iterator = devices.values().iterator(); while(iterator.hasNext()) { UsbDevice usbDevice = iterator.next(); Log.d(TAG, "USB Device: " + usbDevice.getDeviceName() + " Product ID: " + usbDevice.getProductId() + " Vendor ID: " + usbDevice.getVendorId() + " Interface count: " + usbDevice.getInterfaceCount()); for(int i = 0; i < usbDevice.getInterfaceCount(); i++){ UsbInterface intf = usbDevice.getInterface(i); Log.d(TAG, "Interface class: " + intf.getInterfaceClass() ); if (intf.getInterfaceClass() == android.hardware.usb.UsbConstants.USB_CLASS_STILL_IMAGE) { //mUsbDevice = usbDevice; Log.d(TAG, "Ptp Service imaging usb device found requesting permission"); mUsbManager.requestPermission(usbDevice, mPermissionIntent); deviceFound = true; break; } } if (deviceFound) break; } } else Log.d(TAG, "USB Manager is unavailable"); } else { Log.d(TAG, "Ptp service usb imaging device already present"); //_usbManager.requestPermission(_usbDevice, mPermissionIntent); } } catch (Exception e) { Log.d(TAG, "PtpService search for USB camrea exception: " + e.getMessage()); } } private void initUsbConnection() { try { if (mUsbDevice != null) { if (mUsbIntf == null) { for(int i = 0; i < mUsbDevice.getInterfaceCount(); i++) { UsbInterface uintf = mUsbDevice.getInterface(i); if (uintf.getInterfaceClass() == UsbConstants.USB_CLASS_STILL_IMAGE){ // we have a still image interface // Log.d(MainActivity.TAG, "Imaging USB interface found"); mUsbIntf = uintf; break; } } if (mUsbIntf != null) { // get the endpoints for(int i =0; i< mUsbIntf.getEndpointCount(); i++) { UsbEndpoint ep = mUsbIntf.getEndpoint(i); if (ep.getDirection() == UsbConstants.USB_DIR_OUT) { if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) { mUsbWriteEp = ep; // Log.d(MainActivity.TAG, "write endpoint found"); } } else { switch(ep.getType()) { case UsbConstants.USB_ENDPOINT_XFER_BULK: mUsbReadEp = ep; // Log.d(MainActivity.TAG, "read endpoint found"); break; case UsbConstants.USB_ENDPOINT_XFER_INT: mUsbInterruptEp = ep; // Log.d(MainActivity.TAG, "interrupt endpoint found"); break; } } } } else Log.d(TAG, "No compatible USB interface found"); } else Log.d(TAG, "USB interface found"); // if we have read and write endpoints then we good to go if (mUsbReadEp != null && mUsbWriteEp != null) { if (!mIsUsbDeviceInitialized) { mUsbConnection = mUsbManager.openDevice(mUsbDevice); mIsUsbDeviceInitialized = mUsbConnection != null; } if (mIsUsbDeviceInitialized) { // Log.d(TAG, "USB Device Initialized"); if (!mIsUsbInterfaceClaimed) { mIsUsbInterfaceClaimed = mUsbConnection.claimInterface(mUsbIntf, true); // Log.d(TAG, "USB Interface claimed: " + isInterfaceClaimed); } sendPtpServiceEvent(PtpServiceEvent.UsbDeviceInitialized); // create the USB communicator PtpUsbCommunicator communicator = new PtpUsbCommunicator(new PtpSession()); // initialize the USB communicator communicator.initCommunicator(mUsbConnection, mUsbWriteEp, mUsbReadEp, mUsbInterruptEp); // initialize the PTP device mPtpDevice.initialize(mUsbDevice.getVendorId(), mUsbDevice.getProductId(), communicator); } } } else Log.d(TAG, "No USB device present"); } catch (Exception e){ Log.d(TAG, "InitUsb exception: " + e.getMessage()); } } // preferences properties public SharedPreferences getPreferences() { return mPrefs; } }
Java
package com.dslr.dashboard; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.GridLayout; import android.widget.TextView; public class FlashCommanderFragment extends DslrFragmentBase { private final static String TAG = FlashCommanderFragment.class.getSimpleName(); private TextView txtInternalFlashRPTIntense, txtInternalFlashRPTCount, txtInternalFlashRPTInterval; private TextView txtInternalFlashCommanderChannel; private CheckableImageView btnInternalFlashCommanderSelf, btnInternalFlashCommanderGroupA, btnInternalFlashCommanderGroupB; private TextView txtInternalFlashCommanderSelfComp, txtInternalFlashCommanderSelfIntense; private TextView txtInternalFlashCommanderGroupAComp, txtInternalFlashCommanderGroupAIntense; private TextView txtInternalFlashCommanderGroupBComp, txtInternalFlashCommanderGroupBIntense; private GridLayout mGridLayout; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View mView = inflater.inflate(R.layout.flash_commander_fragment, container, false); getDialog().setTitle("Flash Commander"); mGridLayout = (GridLayout)mView.findViewById(R.id.flash_grid_layout); // repeat flash properties txtInternalFlashRPTIntense = (TextView)mView.findViewById(R.id.txtflashrptintense); txtInternalFlashRPTCount = (TextView)mView.findViewById(R.id.txtflashrptcout); txtInternalFlashRPTInterval = (TextView)mView.findViewById(R.id.txtflashrptinterval); // commander channel txtInternalFlashCommanderChannel = (TextView)mView.findViewById(R.id.txtflashcommanderchannel); // commander self btnInternalFlashCommanderSelf = (CheckableImageView)mView.findViewById(R.id.imginternalflashcommanderself); txtInternalFlashCommanderSelfComp = (TextView)mView.findViewById(R.id.txtflashcommanderselfcomp); txtInternalFlashCommanderSelfIntense = (TextView)mView.findViewById(R.id.txtflashcommanderselfintense); // commander group A btnInternalFlashCommanderGroupA = (CheckableImageView)mView.findViewById(R.id.imginternalflashcommandergroupa); txtInternalFlashCommanderGroupAComp = (TextView)mView.findViewById(R.id.txtflashcommandergroupacomp); txtInternalFlashCommanderGroupAIntense = (TextView)mView.findViewById(R.id.txtflashcommandergroupaintense); // commander group B btnInternalFlashCommanderGroupB = (CheckableImageView)mView.findViewById(R.id.imginternalflashcommandergroupb); txtInternalFlashCommanderGroupBComp = (TextView)mView.findViewById(R.id.txtflashcommandergroupbcomp); txtInternalFlashCommanderGroupBIntense = (TextView)mView.findViewById(R.id.txtflashcommandergroupbintense); // repeat flash properties txtInternalFlashRPTIntense.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.InternalFlashManualRPTIntense, "Internal Flash Repeat mode intensity", null); } }); txtInternalFlashRPTCount.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.InternalFlashManualRPTCount, "Internal Flash Repeat mode count", null); } }); txtInternalFlashRPTInterval.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.InternalFlashManualRPTInterval, "Internal Flash Repeat mode interval", null); } }); // commander channel txtInternalFlashCommanderChannel.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.InternalFlashCommanderChannel, "Internal Flash Commander channel", null); } }); // commander self btnInternalFlashCommanderSelf.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.InternalFlashCommanderSelfMode, "Commander-Self mode", null); } }); txtInternalFlashCommanderSelfComp.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.InternalFlashCommanderSelfComp, "Commander-Self compensation", null); } }); txtInternalFlashCommanderSelfIntense.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.InternalFlashCommanderSelfIntense, "Commander-Self intensity", null); } }); // commander group A btnInternalFlashCommanderGroupA.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.InternalFlashCommanderGroupAMode, "Commander-Group A mode", null); } }); txtInternalFlashCommanderGroupAComp.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.InternalFlashCommanderGroupAComp, "Commander-Group A compensation", null); } }); txtInternalFlashCommanderGroupAIntense.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.InternalFlashCommanderGroupAIntense, "Commander-Group A intensity", null); } }); // commander group B btnInternalFlashCommanderGroupB.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.InternalFlashCommanderGroupBMode, "Commander-Group B mode", null); } }); txtInternalFlashCommanderGroupBComp.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.InternalFlashCommanderGroupBComp, "Commander-Group B compensation", null); } }); txtInternalFlashCommanderGroupBIntense.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.InternalFlashCommanderGroupBIntense, "Commander-Group B intensity", null); } }); return mView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); Log.d(TAG, "onAttach"); } @Override public void onStart() { Log.d(TAG, "onStart"); super.onStart(); } @Override public void onResume() { Log.d(TAG, "onResume"); super.onResume(); } @Override public void onPause() { Log.d(TAG, "onPause"); super.onPause(); } @Override public void onStop() { Log.d(TAG, "onStop"); super.onStop(); } @Override public void onDestroy() { Log.d(TAG, "onDestroy"); super.onDestroy(); } @Override public void onDetach() { Log.d(TAG, "onDetach"); super.onDetach(); } @Override protected void internalInitFragment() { initializePtpPropertyView(txtInternalFlashRPTIntense, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashManualRPTIntense)); initializePtpPropertyView(txtInternalFlashRPTCount, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashManualRPTCount)); initializePtpPropertyView(txtInternalFlashRPTInterval, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashManualRPTInterval)); initializePtpPropertyView(txtInternalFlashCommanderChannel, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashCommanderChannel)); initializePtpPropertyView(btnInternalFlashCommanderSelf, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashCommanderSelfMode)); initializePtpPropertyView(txtInternalFlashCommanderSelfComp, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashCommanderSelfComp)); initializePtpPropertyView(txtInternalFlashCommanderSelfIntense, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashCommanderSelfIntense)); initializePtpPropertyView(btnInternalFlashCommanderGroupA, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashCommanderGroupAMode)); initializePtpPropertyView(txtInternalFlashCommanderGroupAComp, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashCommanderGroupAComp)); initializePtpPropertyView(txtInternalFlashCommanderGroupAIntense, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashCommanderGroupAIntense)); initializePtpPropertyView(btnInternalFlashCommanderGroupB, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashCommanderGroupBMode)); initializePtpPropertyView(txtInternalFlashCommanderGroupBComp, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashCommanderGroupBComp)); initializePtpPropertyView(txtInternalFlashCommanderGroupBIntense, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashCommanderGroupBIntense)); } @Override protected void internalPtpPropertyChanged(PtpProperty property) { if (property != null) { switch(property.getPropertyCode()) { case PtpProperty.InternalFlashManualRPTIntense: DslrHelper.getInstance().setDslrTxt(txtInternalFlashRPTIntense, property); break; case PtpProperty.InternalFlashManualRPTCount: DslrHelper.getInstance().setDslrTxt(txtInternalFlashRPTCount, property); break; case PtpProperty.InternalFlashManualRPTInterval: DslrHelper.getInstance().setDslrTxt(txtInternalFlashRPTInterval, property); break; case PtpProperty.InternalFlashCommanderChannel: DslrHelper.getInstance().setDslrTxt(txtInternalFlashCommanderChannel, property); break; case PtpProperty.InternalFlashCommanderSelfMode: DslrHelper.getInstance().setDslrImg(btnInternalFlashCommanderSelf, property); break; case PtpProperty.InternalFlashCommanderSelfComp: DslrHelper.getInstance().setDslrTxt(txtInternalFlashCommanderSelfComp, property); break; case PtpProperty.InternalFlashCommanderSelfIntense: DslrHelper.getInstance().setDslrTxt(txtInternalFlashCommanderSelfIntense, property); break; case PtpProperty.InternalFlashCommanderGroupAMode: DslrHelper.getInstance().setDslrImg(btnInternalFlashCommanderGroupA, property); break; case PtpProperty.InternalFlashCommanderGroupAComp: DslrHelper.getInstance().setDslrTxt(txtInternalFlashCommanderGroupAComp, property); break; case PtpProperty.InternalFlashCommanderGroupAIntense: DslrHelper.getInstance().setDslrTxt(txtInternalFlashCommanderGroupAIntense, property); break; case PtpProperty.InternalFlashCommanderGroupBMode: DslrHelper.getInstance().setDslrImg(btnInternalFlashCommanderGroupB, property); break; case PtpProperty.InternalFlashCommanderGroupBComp: DslrHelper.getInstance().setDslrTxt(txtInternalFlashCommanderGroupBComp, property); break; case PtpProperty.InternalFlashCommanderGroupBIntense: DslrHelper.getInstance().setDslrTxt(txtInternalFlashCommanderGroupBIntense, property); break; } } } @Override protected void ptpDeviceEvent(PtpDeviceEvent event, Object data) { switch(event) { case BusyBegin: Log.d(TAG, "Busy begin"); DslrHelper.getInstance().enableDisableControls(mGridLayout, false); break; case BusyEnd: Log.d(TAG, "Busy end"); DslrHelper.getInstance().enableDisableControls(mGridLayout, true); break; } } @Override protected void internalSharedPrefsChanged(SharedPreferences prefs, String key) { // TODO Auto-generated method stub } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Rect; import android.graphics.RectF; import android.util.AttributeSet; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; public class LvSurfaceBase extends SurfaceView implements SurfaceHolder.Callback, Runnable { private static final String TAG = "LvSurfaceBase"; private SurfaceHolder mHolder; private int mFrameWidth; private int mFrameHeight; private LvSurfaceHelper mHelper = null; private Paint mPaintBlack, mPaintRed, mPaintGreen, mPaintBlue, mPaintYellow; private Thread mDrawThread; private Context mContext; private boolean mThreadRun; private final Object mSyncRoot = new Object(); public LvSurfaceBase(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; mHolder = getHolder(); mHolder.addCallback(this); mPaintBlack = new Paint(); mPaintBlack.setStyle(Paint.Style.FILL); mPaintBlack.setColor(Color.BLACK); mPaintYellow = new Paint(); mPaintYellow.setStyle(Paint.Style.FILL); mPaintYellow.setColor(Color.YELLOW); mPaintRed = new Paint(); mPaintRed.setStyle(Paint.Style.FILL); mPaintRed.setColor(Color.RED); mPaintGreen = new Paint(); mPaintGreen.setStyle(Paint.Style.FILL); mPaintGreen.setColor(Color.GREEN); mPaintBlue = new Paint(); mPaintBlue.setStyle(Paint.Style.FILL); mPaintBlue.setColor(Color.BLUE); // mPaint = new Paint(); // mPaint.setColor(Color.GREEN); // mPaint.setAntiAlias(true); // mPaint.setStyle(Style.STROKE); // mPaint.setStrokeWidth(2); Log.d(TAG, "Created new " + this.getClass()); } public int getFrameWidth() { return mFrameWidth; } public int getFrameHeight() { return mFrameHeight; } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Log.d(TAG, "Surface changed"); mFrameWidth = width; mFrameHeight = height; } public void surfaceCreated(SurfaceHolder holder) { Log.d(TAG, "Surface created"); mDrawThread = new Thread(this); mDrawThread.start(); } public void surfaceDestroyed(SurfaceHolder holder) { Log.d(TAG, "Surface destroyed"); mDrawThread.interrupt(); mThreadRun = false; } public void processLvObject(LvSurfaceHelper helper) { synchronized (mSyncRoot) { mHelper = helper; mSyncRoot.notify(); } } long mTime = 0; public void setDefaultImage() { synchronized (mSyncRoot) { mHelper = null; // mLvo = null; mSyncRoot.notify(); } } private void doDraw(Canvas canvas) { long time = System.currentTimeMillis(); double fps = 0; if (mTime != 0) fps = 1000 / (time - mTime); mTime = time; Bitmap mBitmap = null; if (canvas != null) { if (mHelper == null || mHelper.mLvo == null) { canvas.drawColor(Color.BLACK); return; } mBitmap = BitmapFactory.decodeByteArray(mHelper.mLvo.data, mHelper.mLvo.imgPos, mHelper.mLvo.imgLen);// processLvImage(mLvo); if (mBitmap != null) { canvas.drawBitmap(mBitmap, new Rect(0, 0, mHelper.mLvo.jpegImageSize.horizontal, mHelper.mLvo.jpegImageSize.vertical), new RectF(0, 0, mFrameWidth, mFrameHeight), null); mPaintGreen.setStyle(Paint.Style.STROKE); mPaintGreen.clearShadowLayer(); mPaintYellow.setStyle(Paint.Style.STROKE); mPaintYellow.clearShadowLayer(); mPaintRed.setStyle(Paint.Style.STROKE); mPaintRed.clearShadowLayer(); // draw focus rect canvas.drawRect(mHelper.mLvo.afRects[0], mPaintGreen); // draw rects for face detection if (mHelper.mLvo.faceDetectionPersonNo > 0) { for(int i = 1; i <= mHelper.mLvo.faceDetectionPersonNo; i++){ canvas.drawRect(mHelper.mLvo.afRects[i], mPaintYellow); } } // mPaint.setTextSize(20); // mPaint.setShadowLayer(3, 1, 1, Color.BLACK); // canvas.drawText(String.format("%.1f", fps), 100, 20, mPaint); float fontSize = (mFrameWidth * 32) / 1280; mPaintBlack.setTextSize(fontSize); mPaintGreen.setTextSize(fontSize); mPaintRed.setTextSize(fontSize); mPaintYellow.setTextSize(fontSize); String tmpStr; if ((mHelper.mOsdDisplay & 1) == 1) { //mPaintGreen.setStrokeWidth(1); float thirdx = mFrameWidth / 3; float thirdy = mFrameHeight / 3; if (mHelper.mLvZoom != null && (Integer)mHelper.mLvZoom.getValue() == 0) { canvas.drawLine(thirdx, 0, thirdx, mFrameHeight, mPaintGreen); canvas.drawLine(2 * thirdx, 0, 2 * thirdx, mFrameHeight, mPaintGreen); canvas.drawLine(0, thirdy, mFrameWidth, thirdy, mPaintGreen); canvas.drawLine(0, thirdy * 2, mFrameWidth, thirdy * 2, mPaintGreen); } } mPaintGreen.setShadowLayer(3, 1, 1, Color.BLACK); mPaintRed.setShadowLayer(3, 1, 1, Color.BLACK); mPaintYellow.setShadowLayer(3, 1, 1, Color.BLACK); if ((mHelper.mOsdDisplay & 2) == 2) { //mPaintGreen.setTextSize(20); canvas.drawText(String.format("LV remain %d s", mHelper.mLvo.countDownTime), 20, 25, mPaintGreen); if ((mHelper.mLvo.shutterSpeedUpper / mHelper.mLvo.shutterSpeedLower) >= 1) tmpStr = String.format("f %.1f %.1f \"", (double)mHelper.mLvo.apertureValue / 100, (double)(mHelper.mLvo.shutterSpeedUpper / mHelper.mLvo.shutterSpeedLower)); else tmpStr = String.format("f %.1f %d / %d", (double)mHelper.mLvo.apertureValue / 100, mHelper.mLvo.shutterSpeedUpper, mHelper.mLvo.shutterSpeedLower); if (mHelper.mLvo.hasApertureAndShutter) { float tWidth = mPaintGreen.measureText(tmpStr); canvas.drawText(tmpStr, (mFrameWidth / 2) - (tWidth / 2) , 25, mPaintGreen); } if (mHelper.mLvo.focusDrivingStatus == 1) canvas.drawText("AF", 70, 60, mPaintGreen); // canvas.drawText(String.format("Focus %d / %d", mHelper.mFocusCurrent, mHelper.mFocusMax ), 80, 75, mPaintGreen); // switch(mHelper.mTouchMode){ // case LVFOCUS: // canvas.drawText("Manual focus", 80, 105, mPaintGreen); // canvas.drawText(String.format("Focus step: %d", mMfDriveStep), 50, 370, mPaintGreen); // break; // case LVZOOM: // canvas.drawText("Zoom", 80, 105, mPaintGreen); // break; // } if (mHelper.mLvo.hasRolling) { tmpStr = String.format("Rolling %.2f", mHelper.mLvo.rolling); canvas.drawText(tmpStr, mFrameWidth - mPaintGreen.measureText(tmpStr) - 20, 105, mPaintGreen); } if (mHelper.mLvo.hasPitching) { tmpStr = String.format("Pitching %.2f", mHelper.mLvo.pitching); canvas.drawText(tmpStr, mFrameWidth - mPaintGreen.measureText(tmpStr) - 20, 135, mPaintGreen); } if (mHelper.mLvo.hasYawing) { tmpStr = String.format("Yawing %.2f", mHelper.mLvo.yawing); canvas.drawText(tmpStr, mFrameWidth - mPaintGreen.measureText(tmpStr) - 20, 165, mPaintGreen); } if (mHelper.mLvo.movieRecording) { tmpStr = String.format("REC remaining %d s", mHelper.mLvo.movieRecordingTime / 1000); canvas.drawText(tmpStr, mFrameWidth - mPaintGreen.measureText(tmpStr) - 20, 75, mPaintRed); } mPaintGreen.setStyle(Paint.Style.FILL); mPaintYellow.setStyle(Paint.Style.FILL); mPaintRed.setStyle(Paint.Style.FILL); switch(mHelper.mLvo.focusingJudgementResult){ case 0: canvas.drawCircle(50, 50, 10, mPaintYellow); break; case 1: canvas.drawCircle(50, 50, 10, mPaintRed); break; case 2: canvas.drawCircle(50, 50, 10, mPaintGreen); break; } // focus position drawin // paint.setColor(Color.GREEN); // paint.setStyle(Style.FILL_AND_STROKE); // // float fx = (mFrameWidth * mHelper.mFocusCurrent) / mHelper.mFocusMax; // canvas.drawCircle(fx, mFrameHeight - 20, 10, paint); } if (mHelper.mHistogramEnabled) { Bitmap histBmp = NativeMethods.getInstance().createHistogramBitmap(mBitmap,mHelper.mHistogramSeparate); int hWidth = histBmp.getWidth(); int hHeight = histBmp.getHeight(); if (hWidth > (int)(mFrameWidth / 3)) { //hHeight = (int)(hHeight * (hWidth / (mFrameWidth / 3)) ); hWidth = (int)(mFrameWidth / 3); } if (hHeight > mFrameHeight) { //hWidth = (int)(hWidth * (hHeight / mFrameHeight)); hHeight = mFrameHeight; } canvas.drawBitmap(histBmp, new Rect(0, 0, histBmp.getWidth(), histBmp.getHeight()), new RectF(0, 0, hWidth, hHeight), null); histBmp.recycle(); } mBitmap.recycle(); } else { canvas.drawColor(Color.BLACK); } } } public void run() { mThreadRun = true; Log.d(TAG, "Starting LV image processing thread"); while (mThreadRun) { synchronized (mSyncRoot) { try { mSyncRoot.wait(); } catch (InterruptedException e) { Log.d(TAG, "Draw thread interrupted"); } } try { Canvas canvas = mHolder.lockCanvas(); doDraw(canvas); mHolder.unlockCanvasAndPost(canvas); } catch (Exception e) { Log.e(TAG, "LVSurface draw exception: " + e.getMessage()); } } } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; public enum PtpServiceEvent { UsbDeviceFount, UsbDeviceInitialized, UsbDeviceRemoved }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import java.util.Hashtable; public class DslrProperties { private Hashtable<Integer, DslrProperty> mProperties; private int mVendorId, mProductId; public DslrProperties(int vendorId, int productId){ mVendorId = vendorId; mProductId = productId; mProperties = new Hashtable<Integer, DslrProperty>(); } public Hashtable<Integer, DslrProperty> properties(){ return mProperties; } public DslrProperty addProperty(int propertyCode){ DslrProperty property = new DslrProperty(propertyCode); mProperties.put(propertyCode, property); return property; } public boolean containsProperty(int propertyCode){ return mProperties.containsKey(propertyCode); } public DslrProperty getProperty(int propertyCode){ return mProperties.get(propertyCode); } public int getVendorId(){ return mVendorId; } public int getProductId(){ return mProductId; } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.TextView; public class ExifAdapter extends BaseAdapter { private ArrayList<ExifDataHelper> _items; public ArrayList<ExifDataHelper> items(){ return _items; } public Context context; public LayoutInflater inflater; public ExifAdapter(Context context, ArrayList<ExifDataHelper> arrayList){ super(); this.context = context; this._items = arrayList; this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public void changeItems(ArrayList<ExifDataHelper> arrayList){ _items = arrayList; notifyDataSetChanged(); } public int getCount() { return _items.size(); } public Object getItem(int position) { return _items.get(position); } public long getItemId(int position) { return position; } @Override public boolean hasStableIds() { return true; } @Override public int getItemViewType(int position) { return IGNORE_ITEM_VIEW_TYPE; } @Override public int getViewTypeCount() { return 1; } public static class ViewHolder { TextView txtExifName; TextView txtExifValue; } public View getView(int position, View convertView, ViewGroup parent) { final ViewHolder holder; if(convertView==null) { holder = new ViewHolder(); convertView = inflater.inflate(R.layout.exif_list_item, null); holder.txtExifName = (TextView) convertView.findViewById(R.id.txtexifdescription); holder.txtExifValue = (TextView) convertView.findViewById(R.id.txtexifvalue); convertView.setTag(holder); } else holder=(ViewHolder)convertView.getTag(); ExifDataHelper helper = _items.get(position); holder.txtExifName.setText(helper.mExifDescription); holder.txtExifValue.setText(helper.mExifValue); return convertView; } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbManager; import android.util.Log; import com.hoho.android.usbserial.driver.UsbSerialDriver; import com.hoho.android.usbserial.driver.UsbSerialProber; import com.hoho.android.usbserial.util.SerialInputOutputManager; public class UsbSerialService extends ServiceBase { private final static String TAG = UsbSerialService.class.getSimpleName(); @Override public void onCreate() { Log.d(TAG, "onCreate"); mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent( ACTION_USB_PERMISSION), 0); IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION); registerReceiver(mUsbPermissionReceiver, filter); try { mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE); } catch (Exception e) { Log.d(TAG, "UsbManager not available: " + e.getMessage()); } super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "onStartCommand"); searchForSerialUsb(); return START_STICKY; } @Override public void onDestroy() { Log.d(TAG, "onDestroy"); stopIoManager(); unregisterReceiver(mUsbPermissionReceiver); super.onDestroy(); } public interface ButtonStateChangeListener { void onButtonStateChanged(int buttons); } private ButtonStateChangeListener mButtonStateListener = null; public void setButtonStateChangeListener(ButtonStateChangeListener listener) { mButtonStateListener = listener; } private final ExecutorService mExecutor = Executors .newSingleThreadExecutor(); private UsbSerialDriver mSerialDevice; private UsbManager mUsbManager; private UsbDevice mUsbSerialDevice; PendingIntent mPermissionIntent; private SerialInputOutputManager mSerialIoManager; private static final String ACTION_USB_PERMISSION = "com.dslr.dashboard.USB_SERIAL_PERMISSION"; private final SerialInputOutputManager.Listener mListener = new SerialInputOutputManager.Listener() { public void onRunError(Exception e) { Log.d(TAG, "Runner stopped."); } public void onNewData(final byte[] data) { updateReceivedData(data); } }; private void startUsbSerialDevice() { Log.d(TAG, "Starting USB Serial device"); mSerialDevice = UsbSerialProber.acquire(mUsbManager); Log.d(TAG, "Resumed, mSerialDevice=" + mSerialDevice); if (mSerialDevice == null) { Log.d(TAG, "No serial device."); } else { try { mSerialDevice.open(); } catch (IOException e) { Log.e(TAG, "Error setting up device: " + e.getMessage(), e); try { mSerialDevice.close(); } catch (IOException e2) { // Ignore. } mSerialDevice = null; return; } Log.d(TAG, "Serial device: " + mSerialDevice); } onDeviceStateChange(); } private void stopIoManager() { if (mSerialIoManager != null) { Log.i(TAG, "Stopping io manager .."); mSerialIoManager.stop(); mSerialIoManager = null; mUsbSerialDevice = null; } } private void startIoManager() { if (mSerialDevice != null) { Log.i(TAG, "Starting io manager .."); mSerialIoManager = new SerialInputOutputManager(mSerialDevice, mListener); mExecutor.submit(mSerialIoManager); } } private void onDeviceStateChange() { stopIoManager(); startIoManager(); } private boolean mNeedMoreBytes = false; private byte[] mData = new byte[1024]; private int mOffset = 0; private boolean mSyncFound = false; private int mSyncPos = 0; private void updateReceivedData(byte[] data) { // Log.d(TAG, "Incomind size: " + data.length); System.arraycopy(data, 0, mData, mOffset, data.length); mOffset += data.length; if (!mSyncFound) { int i = 0; do { if ((mData[i] & 0xff) == 0xaa) { //Log.d(TAG, "First sync found 0xaa"); if ((i + 1) < mOffset) { if ((mData[i+1] & 0xff) == 0x55) { //Log.d(TAG, "Second sync found 0x55"); mSyncFound = true; mSyncPos = i+2; mNeedMoreBytes = false; break; } } else { //Log.d(TAG, "Need more bytes for second sync"); mNeedMoreBytes = true; } } i++; } while (i < mOffset); } if (mSyncFound) { int length = 0; if (mNeedMoreBytes) { //Log.d(TAG, "Sync found need more byte"); length = (0xff & mData[mSyncPos + 1] << 8) + 0xff & mData[mSyncPos]; // Log.d(TAG, "Need size: " + length + " Offset: " + mOffset); if ((mSyncPos + length) == mOffset) { // Log.d(TAG, String.format("got all data: %d, %d",length, // mOffset) ); mNeedMoreBytes = false; mOffset = 0; } } else { //Log.d(TAG, "Sync found first check for bytes"); //Log.d(TAG, "Packet syncpos: " + mSyncPos + " offset: " + mOffset); if ((mSyncPos + 1) < mOffset) { //if (data.length > 1) { length = (0xff & mData[mSyncPos + 1] << 8) + 0xff & mData[mSyncPos]; //Log.d(TAG, "Packet length: " + length + " syncpos: " + mSyncPos + " offset: " + mOffset); //length = (0xff & data[1] << 8) + 0xff & data[0]; if ((mSyncPos + length) > mOffset) { //if (length != mOffset) { mNeedMoreBytes = true; } else { // Log.d(TAG, // String.format("got right size: %d, %d",length, // mOffset) ); mOffset = 0; } } else { mNeedMoreBytes = true; } } } if (!mNeedMoreBytes && mSyncFound) { int command = ((0xff & mData[mSyncPos + 3]) << 8) + (0xff & mData[mSyncPos +2]); switch (command) { case 0x0001: int buttons = ((0xff & mData[mSyncPos + 5]) << 8) + (0xff & mData[mSyncPos +4]); mSyncFound = false; mSyncPos = 0; //Log.d(TAG, "Serial button change detected"); if (mButtonStateListener != null) mButtonStateListener.onButtonStateChanged(buttons); break; } } } public void searchForSerialUsb() { if (mUsbSerialDevice == null) { Log.d(TAG, "Ptp Serial USB device not initialized, search for one"); if (mUsbManager != null) { HashMap<String, UsbDevice> devices = mUsbManager .getDeviceList(); Log.d(TAG, "Found USB devices count: " + devices.size()); Iterator<UsbDevice> iterator = devices.values().iterator(); while (iterator.hasNext()) { UsbDevice usbDevice = iterator.next(); Log.d(TAG, "USB Device: " + usbDevice.getDeviceName() + " Product ID: " + usbDevice.getProductId() + " Vendor ID: " + usbDevice.getVendorId() + " Interface count: " + usbDevice.getInterfaceCount()); if (usbDevice.getVendorId() == 0x2341) {// check if arduino Log.d(TAG, "Found Arduino"); mUsbManager.requestPermission(usbDevice, mPermissionIntent); break; } } } else Log.d(TAG, "USB Manager is unavailable"); } } private final BroadcastReceiver mUsbPermissionReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.d(TAG, "USB Serial permission Intent received " + action); if (ACTION_USB_PERMISSION.equals(action)) { synchronized (this) { UsbDevice usbDevice = (UsbDevice) intent .getParcelableExtra(UsbManager.EXTRA_DEVICE); if (intent.getBooleanExtra( UsbManager.EXTRA_PERMISSION_GRANTED, false)) { Log.d(TAG, "USB device permission granted"); // if arduino, then start USB serial communication if (usbDevice.getVendorId() == 0x2341) { mUsbSerialDevice = usbDevice; startUsbSerialDevice(); } } } } } }; }
Java
package com.dslr.dashboard; import java.io.File; import java.util.LinkedList; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.util.Log; public class GpsLocationHelper { private final static String TAG = GpsLocationHelper.class.getSimpleName(); private Context mContext = null; private LocationManager mLocationManager; private Location mLastLocation = null; private LinkedList<File> mGpsList; private boolean mIsWaitingForGpsUpdate = false; private int mGpsSampleInterval = 1; public int mGpsSampleCount = 3; private int mGpsUpdateCount = 0; private Thread mGpsThread; private Handler mGpsHandler = null; public void setGpsSampleCount(int value) { mGpsSampleCount = value; } public void setGpsSampleInterval(int value) { mGpsSampleInterval = value; } public GpsLocationHelper(Context context) { mContext = context; mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); mGpsList = new LinkedList<File>(); mGpsThread = new Thread() { public void run() { Log.d( TAG,"Creating handler ..." ); Looper.prepare(); mGpsHandler = new Handler(); Looper.loop(); Log.d( TAG, "Looper thread ends" ); } }; mGpsThread.start(); } public void stopGpsLocator() { Log.d(TAG, "stopGpsLocator"); mGpsHandler.getLooper().quit(); mGpsHandler = null; mLocationManager.removeUpdates(locationListener); } // Define a listener that responds to location updates LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { Log.i(TAG, "New location latitude: " + location.getLatitude() + " longituted: " + location.getLongitude() + " altitude: " + location.getAltitude() + " count: " + mGpsUpdateCount); if (isBetterLocation(location, mLastLocation)) mLastLocation = location; mGpsUpdateCount++; //Log.i(TAG, "GPS time: " + location.getTime()); //Log.i(TAG, "Time: " + System.currentTimeMillis()); // wait for 3 location updates if (mGpsUpdateCount == mGpsSampleCount) { mLocationManager.removeUpdates(locationListener); //_gpsUpdateCount = 0; synchronized (mGpsList) { while(!mGpsList.isEmpty()){ File file = mGpsList.poll(); setImageGpsLocation(location, file); } mIsWaitingForGpsUpdate = false; } } } public void onStatusChanged(String provider, int status, Bundle extras) { Log.i(TAG, "Status changes: " + status); } public void onProviderEnabled(String provider) { Log.i(TAG, "Provider enabled: " + provider); } public void onProviderDisabled(String provider) { Log.i(TAG, "Provider disable: " + provider); } }; /** Determines whether one Location reading is better than the current Location fix * @param location The new Location that you want to evaluate * @param currentBestLocation The current Location fix, to which you want to compare the new one */ protected boolean isBetterLocation(Location location, Location currentBestLocation) { if (currentBestLocation == null) { // A new location is always better than no location return true; } // Check whether the new location fix is newer or older long timeDelta = location.getTime() - currentBestLocation.getTime(); boolean isSignificantlyNewer = timeDelta > getSampleInterval(); boolean isSignificantlyOlder = timeDelta < -getSampleInterval(); boolean isNewer = timeDelta > 0; // If it's been more than two minutes since the current location, use the new location // because the user has likely moved if (isSignificantlyNewer) { return true; // If the new location is more than two minutes older, it must be worse } else if (isSignificantlyOlder) { return false; } // Check whether the new location fix is more or less accurate int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy()); boolean isLessAccurate = accuracyDelta > 0; boolean isMoreAccurate = accuracyDelta < 0; boolean isSignificantlyLessAccurate = accuracyDelta > 200; // Check if the old and new location are from the same provider boolean isFromSameProvider = isSameProvider(location.getProvider(), currentBestLocation.getProvider()); // Determine location quality using a combination of timeliness and accuracy if (isMoreAccurate) { return true; } else if (isNewer && !isLessAccurate) { return true; } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) { return true; } return false; } private int getSampleInterval(){ return 1000 * 60 * mGpsSampleInterval; } /** Checks whether two providers are the same */ private boolean isSameProvider(String provider1, String provider2) { if (provider1 == null) { return provider2 == null; } return provider1.equals(provider2); } private void setImageGpsLocation(Location location, File file) { NativeMethods.getInstance().setGPSExifData(file.getAbsolutePath(), location.getLatitude(), location.getLongitude(), location.getAltitude()); runMediaScanner(file); } private void runMediaScanner(File file) { Uri contentUri = Uri.fromFile(file); Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE"); mediaScanIntent.setData(contentUri); mContext.sendBroadcast(mediaScanIntent); } private boolean needLocationUpdate() { if (mLastLocation != null) { long utcTime = System.currentTimeMillis(); if ((utcTime - mLastLocation.getTime()) < getSampleInterval()) return false; } return true; } public void updateGpsLocation() { if (mGpsHandler != null) mGpsHandler.post(new Runnable() { public void run() { Log.d(TAG, "Getting new GPS Location"); if (!mIsWaitingForGpsUpdate) { mIsWaitingForGpsUpdate = true; mGpsUpdateCount = 0; Log.d(TAG, "Need GPS location update"); mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); } } }); } public void addGpsLocation(File file) { synchronized (mGpsList) { Log.d(TAG, "Getting exif gps data"); if (needLocationUpdate()) { mGpsList.push(file); Log.d(TAG, "Need new GPS Location"); updateGpsLocation(); } else { setImageGpsLocation(mLastLocation, file); } } } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import android.content.Context; import android.util.AttributeSet; import android.widget.Checkable; import android.widget.ImageView; public class CheckableImageView extends ImageView implements Checkable { private boolean mChecked; private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked }; public CheckableImageView(Context context, AttributeSet attrs) { super(context, attrs); } @Override public int[] onCreateDrawableState(int extraSpace) { final int[] drawableState = super.onCreateDrawableState(extraSpace + 1); if (isChecked()) { mergeDrawableStates(drawableState, CHECKED_STATE_SET); } return drawableState; } public void toggle() { setChecked(!mChecked); } public boolean isChecked() { return mChecked; } public void setChecked(boolean checked) { if (mChecked != checked) { mChecked = checked; refreshDrawableState(); } } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import java.io.File; import java.lang.ref.SoftReference; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Handler; import android.os.Message; import android.util.Log; import android.widget.ImageView; public enum BitmapManager { INSTANCE; private final String TAG = "ThumbLoader"; private final Map<String, SoftReference<Bitmap>> cache; private final ExecutorService pool; private Map<ImageView, String> imageViews = Collections.synchronizedMap(new WeakHashMap<ImageView, String>()); private Bitmap placeholder; BitmapManager() { cache = new HashMap<String, SoftReference<Bitmap>>(); pool = Executors.newFixedThreadPool(5); } public void setPlaceholder(Bitmap bmp) { placeholder = bmp; } public Bitmap getBitmapFromCache(String url) { if (cache.containsKey(url)) { return cache.get(url).get(); } return null; } public void clearCach(){ cache.clear(); imageViews.clear(); } public void queueJob(final String url, final ImageView imageView) { final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { String tag = imageViews.get(imageView); if (tag != null && tag.equals(url)) { Bitmap bmp = (Bitmap)msg.obj; if (bmp != null) { imageView.setImageBitmap(bmp); cache.put(url, new SoftReference<Bitmap>(bmp)); } else { imageView.setImageBitmap(placeholder); } } } }; pool.submit(new Runnable() { public void run() { final Bitmap bmp = downloadBitmap(url); Message message = Message.obtain(); message.obj = bmp; //Log.d(TAG, "Item downloaded: " + url); handler.sendMessage(message); } }); } public void loadBitmap(final String url, final ImageView imageView) { Bitmap bitmap = getBitmapFromCache(url); if (bitmap != null) { imageView.setImageBitmap(bitmap); } else { imageViews.put(imageView, url); imageView.setImageBitmap(placeholder); queueJob(url, imageView); } } private File getThumbFilePath( String fileName, String ext){ File file = new File(fileName); File f = new File(file.getParent() + "/.thumb"); if (!f.exists()) f.mkdir(); String fname = file.getName(); if (!ext.isEmpty()) return new File(f, fname + "." + ext); else return new File(f, fname); } private Bitmap downloadBitmap(String url) { Log.d(TAG, "downloadBitmap: " + url); String thumbPath = ""; Bitmap bitmap = null; if (url.contains(".dslrthumbs")) thumbPath = url; else { File thumbFile = getThumbFilePath(url, "png"); if (thumbFile.exists()) thumbPath = thumbFile.getAbsolutePath(); else{ thumbFile = getThumbFilePath(url, "jpg"); if (thumbFile.exists()) thumbPath = thumbFile.getAbsolutePath(); } } if (!thumbPath.equals("")) { final int IMAGE_MAX_SIZE = 30000; // 1.2MP BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; Bitmap tmp = BitmapFactory.decodeFile(thumbPath, options); int scale = 1; while ((options.outWidth * options.outHeight) * (1 / Math.pow(scale, 2)) > IMAGE_MAX_SIZE) { scale++; } tmp = null; if (scale > 1) { scale--; options = new BitmapFactory.Options(); options.inSampleSize = scale; bitmap = BitmapFactory.decodeFile(thumbPath, options); } else bitmap = BitmapFactory.decodeFile(thumbPath); } return bitmap; } }
Java
// Copyright 2000 by David Brownell <dbrownell@users.sourceforge.net> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // package com.dslr.dashboard; import java.util.Vector; public class PtpProperty { int mPropertyCode; int mDataType; boolean mWritable; Object mFactoryDefault; Object mCurrentValue; int mFormType; Object mConstraints; public PtpProperty () { } public void parse (PtpBuffer data) { data.parse (); // per 13.3.3, tables 23, 24, 25 mPropertyCode = data.nextU16 (); mDataType = data.nextU16 (); mWritable = data.nextU8 () != 0; // FIXME use factories, as vendor hooks mFactoryDefault = PtpPropertyValue.get (mDataType, data); mCurrentValue = PtpPropertyValue.get (mDataType, data); mFormType = data.nextU8 (); switch (mFormType) { case 0: // no more break; case 1: // range: min, max, step mConstraints = new PtpRange (mDataType, data); break; case 2: // enumeration: n, value1, ... valueN mConstraints = parseEnumeration (data); break; default: System.err.println ("ILLEGAL prop desc form, " + mFormType); mFormType = 0; break; } } public int getPropertyCode(){ return mPropertyCode; } public int getDataType(){ return mDataType; } /** Returns true if the property is writable */ public boolean getIsWritable () { return mWritable; } /** Returns the current value (treat as immutable!) */ public Object getValue () { return mCurrentValue; } /** Returns the factory default value (treat as immutable!) */ public Object getDefault () { return mFactoryDefault; } public int getFormType() { return mFormType; } // code values, per 13.3.5 table 26 public static final int BatteryLevel = 0x5001; public static final int FunctionalMode = 0x5002; public static final int ImageSize = 0x5003; public static final int CompressionSetting = 0x5004; public static final int WhiteBalance = 0x5005; public static final int RGBGain = 0x5006; public static final int FStop = 0x5007; public static final int FocalLength = 0x5008; public static final int FocusDistance = 0x5009; public static final int FocusMode = 0x500a; public static final int ExposureMeteringMode = 0x500b; public static final int FlashMode = 0x500c; public static final int ExposureTime = 0x500d; public static final int ExposureProgramMode = 0x500e; public static final int ExposureIndex = 0x500f; public static final int ExposureBiasCompensation = 0x5010; public static final int DateTime = 0x5011; public static final int CaptureDelay = 0x5012; public static final int StillCaptureMode = 0x5013; public static final int Contrast = 0x5014; public static final int Sharpness = 0x5015; public static final int DigitalZoom = 0x5016; public static final int EffectMode = 0x5017; public static final int BurstNumber = 0x5018; public static final int BurstInterval = 0x5019; public static final int TimelapseNumber = 0x501a; public static final int TimelapseInterval = 0x501b; public static final int FocusMeteringMode = 0x501c; public static final int UploadURL = 0x501d; public static final int Artist = 0x501e; public static final int CopyrightInfo = 0x501f; public static final int WbTuneAuto = 0xd017; public static final int WbTuneIncandescent = 0xd018; public static final int WbTuneFluorescent = 0xd019; public static final int WbTuneSunny = 0xd01a; public static final int WbTuneFlash = 0xd01b; public static final int WbTuneCloudy = 0xd01c; public static final int WbTuneShade = 0xd01d; public static final int WbPresetDataNo = 0xd01f; public static final int WbPresetDataValue0 = 0xd025; public static final int WbPresetDataValue1 = 0xd026; public static final int ColorSpace = 0xd032; public static final int VideoMode = 0xd036; public static final int ResetCustomSetting = 0xd045; public static final int IsoAutocontrol = 0xd054; public static final int ExposureEvStep = 0xd056; public static final int AfAtLiveView = 0xd05d; public static final int AeLockRelease = 0xd05e; public static final int AeAfLockSetting = 0xd05f; public static final int AfModeAtLiveView = 0xd061; public static final int AutoMeterOffDelay = 0xd062; public static final int SelfTimerDelay = 0xd063; public static final int LcdPowerOff = 0xd064; public static final int ImageConfirmTimeAfterPhoto = 0xd065; public static final int AutoOffTime = 0xd066; public static final int ExposureDelay = 0xd06a; public static final int NoiseReduction = 0xd06b; public static final int NumberingMode = 0xd06c; public static final int NoiseReductionHiIso = 0xd070; public static final int FlashSyncSpeed = 0xd074; public static final int FlashSlowSpeedLimit = 0xd075; public static final int BracketingType = 0xd078; public static final int FunctionButton = 0xd084; public static final int CommandDialRotation = 0xd085; public static final int EnableShutter = 0xd08a; public static final int CommentString = 0xd090; public static final int Enablecomment = 0xd091; public static final int OrientationSensorMode = 0xd092; public static final int MovieRecordScreenSize = 0xd0a0; public static final int MovieRecordWithVoice = 0xd0a1; public static final int MovieRecordMicrophoneLevel = 0xd0a2; public static final int MovieRecProhibitionCondition = 0xd0a4; public static final int LiveViewScreenDisplaySetting = 0xd0b2; public static final int EnableBracketing = 0xd0c0; public static final int AeBracketingStep = 0xd0c1; public static final int AeBracketingCount = 0xd0c3; public static final int WbBracketingStep = 0xd0c4; public static final int LensId = 0xd0e0; public static final int LensSort = 0xd0e1; public static final int LensType = 0xd0e2; public static final int LensfocalMin = 0xd0e3; public static final int LensFocalMax = 0xd0e4; public static final int LensApatureMin = 0xd0e5; public static final int LensApatureMax = 0xd0e6; public static final int FinderIsoDisplay = 0xd0f0; public static final int SelfTimerShootExpose = 0xd0f5; public static final int AutoDistortion = 0xd0f8; public static final int SceneMode = 0xd0f9; public static final int ShutterSpeed = 0xd100; public static final int ExternalDcIn = 0xd101; public static final int WarningStatus = 0xd102; public static final int RemainingExposure = 0xd103; public static final int AfLockStatus = 0xd104; public static final int AeLockStatus = 0xd105; public static final int FocusArea = 0xd108; public static final int FlexibleProgram = 0xd109; public static final int RecordingMedia = 0xd10b; public static final int UsbSpeed = 0xd10c; public static final int CcdNumber = 0xd10d; public static final int Orientation = 0xd10e; public static final int ExternalSpeedLightExist = 0xd120; public static final int ExternalSpeedLightStatus = 0xd121; public static final int ExternalSpeedLightSort = 0xd122; public static final int FlashCompensation = 0xd124; public static final int NewExternalSpeedLightMode = 0xd125; public static final int InternalFlashCompensation = 0xd126; public static final int Slot2ImageSaveMode = 0xd148; public static final int ActiveDLighting = 0xd14e; public static final int WbTuneFluorescentType = 0xd14f; public static final int Beep = 0xd160; public static final int AfModeSelect = 0xd161; public static final int AfSubLight = 0xd163; public static final int IsoAutoShutterTimer = 0xd164; public static final int InternalFlashMode = 0xd167; public static final int IsoAutoSetting = 0xd16a; public static final int RemoteControlDelay = 0xd16b; public static final int GridDisplay = 0xd16c; public static final int InternalFlashManual = 0xd16d; public static final int DateImprintSetting = 0xd170; public static final int DateCounterSelect = 0xd171; public static final int DateCountData = 0xd172; public static final int DateCountDisplaySetting = 0xd173; public static final int RangeFinderSetting = 0xd174; public static final int IsoautoHighLimit = 0xd183; public static final int IndicatorDisplay = 0xd18d; public static final int LiveViewStatus = 0xd1a2; public static final int LiveViewImageZoomRatio = 0xd1a3; public static final int LiveViewProhibitionCondition = 0xd1a4; public static final int ExposureDisplayStatus = 0xd1b0; public static final int ExposureIndicateStatus = 0xd1b1; public static final int InfoDisplayErrorStatus = 0xd1b2; public static final int ExposureIndicateLightup = 0xd1b3; public static final int InternalFlashPopup = 0xd1c0; public static final int InternalFlashStatus = 0xd1c1; public static final int InternalFlashManualRPTIntense = 0xd1d0; public static final int InternalFlashManualRPTCount = 0xd1d1; public static final int InternalFlashManualRPTInterval = 0xd1d2; public static final int InternalFlashCommanderChannel = 0xd1d3; public static final int InternalFlashCommanderSelfMode = 0xd1d4; public static final int InternalFlashCommanderSelfComp = 0xd1d5; public static final int InternalFlashCommanderSelfIntense = 0xd1d6; public static final int InternalFlashCommanderGroupAMode = 0xd1d7; public static final int InternalFlashCommanderGroupAComp = 0xd1d8; public static final int InternalFlashCommanderGroupAIntense = 0xd1d9; public static final int InternalFlashCommanderGroupBMode = 0xd1da; public static final int InternalFlashCommanderGroupBComp = 0xd1db; public static final int InternalFlashCommanderGroupBIntense = 0xd1dc; public static final int ActiveSlot = 0xd1f2; public static final int ActivePicCtrlItem = 0xd200; public static final int ChangePicCtrlItem = 0xd201; public static final int SessionInitiatorVersionInfo = 0xd406; public static final int PerceivedDeviceType = 0xd407; /** * This class describes value ranges by minima, maxima, * and permissible increments. */ public static final class PtpRange { private Object min, max, step; PtpRange (int dataType, PtpBuffer data) { min = PtpPropertyValue.get (dataType, data); max = PtpPropertyValue.get (dataType, data); step = PtpPropertyValue.get (dataType, data); } /** Returns the maximum value of this range */ public Object getMaximum () { return max; } /** Returns the minimum value of this range */ public Object getMinimum () { return min; } /** Returns the increment of values in this range */ public Object getIncrement () { return step; } } /** Returns any range constraints for this property's value, or null */ public PtpRange getRange () { if (mFormType == 1) return (PtpRange) mConstraints; return null; } private Vector<Object> parseEnumeration (PtpBuffer data) { int len = data.nextU16 (); Vector<Object> retval = new Vector<Object> (len); while (len-- > 0) retval.addElement (PtpPropertyValue.get (mDataType, data)); return retval; } /** Returns any enumerated options for this property's value, or null */ public Vector<?> getEnumeration () { if (mFormType == 2) return (Vector<?>) mConstraints; return null; } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; public interface IDslrActivity { public PtpDevice getPtpDevice(); public void toggleFullScreen(); public boolean getIsFullScreen(); public void toggleLvLayout(); public void toggleLvLayout(boolean showLvLayout); public boolean getIsLvLayoutEnabled(); public void zoomLiveView(boolean up); }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.app.Fragment; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; public abstract class DslrFragmentBase extends DialogFragment { private IDslrActivity mActivity = null; private boolean mIsAttached = false; private PtpDevice mPtpDevice = null; protected IDslrActivity getDslrActivity() { return mActivity; } protected PtpDevice getPtpDevice() { return mPtpDevice; } protected boolean getIsAttached() { return mIsAttached; } protected boolean getIsPtpDeviceInitialized() { return mPtpDevice != null ? mPtpDevice.getIsPtpDeviceInitialized() : false; } @Override public void onAttach(Activity activity) { super.onAttach(activity); try{ mActivity = (IDslrActivity)activity; mPtpDevice = mActivity.getPtpDevice(); mIsAttached = true; } catch (ClassCastException e) { mActivity = null; } } @Override public void onDetach() { mIsAttached = false; mActivity = null; super.onDetach(); } public void initFragment(){ if (mIsAttached) internalInitFragment(); } public void ptpPropertyChanged(PtpProperty property) { internalPtpPropertyChanged(property); } public void sharedPrefsChanged(SharedPreferences prefs, String key) { internalSharedPrefsChanged(prefs, key); } @Override public void onResume() { super.onResume(); internalInitFragment(); } protected void initializePtpPropertyView(View view, PtpProperty property) { if (property == null) view.setVisibility(View.GONE); else { view.setVisibility(View.VISIBLE); internalPtpPropertyChanged(property); } } protected abstract void internalInitFragment(); protected abstract void internalPtpPropertyChanged(PtpProperty property); protected abstract void ptpDeviceEvent(PtpDeviceEvent event, Object data); protected abstract void internalSharedPrefsChanged(SharedPreferences prefs, String key); }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; public interface IPtpCommandFinalProcessor { public boolean doFinalProcessing(PtpCommand cmd); }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.util.Log; import android.view.ActionProvider; import android.view.LayoutInflater; import android.view.View; import android.widget.LinearLayout; public class MainMenuProvider extends ActionProvider { private static final String TAG = "MainMenuProvider"; private Context mContext; private LinearLayout mMenuLayout; private CheckableImageView mShootingMode, mSceneMode, mCameraMode, mLiveView, mCustomBracketing, mTimelapse, mFlashCommander, mFocusBracketing; public MainMenuProvider(Context context) { super(context); mContext = context; } @Override public View onCreateActionView() { Log.d(TAG, "onCreateActionView"); LayoutInflater layoutInflater = LayoutInflater.from(mContext); View view = layoutInflater.inflate(R.layout.main_menu_provider,null); mMenuLayout = (LinearLayout)view.findViewById(R.id.menu_layout); mShootingMode = (CheckableImageView)view.findViewById(R.id.shootingmode); mSceneMode = (CheckableImageView)view.findViewById(R.id.scenemode); mCameraMode = (CheckableImageView)view.findViewById(R.id.cameramode); mLiveView = (CheckableImageView)view.findViewById(R.id.liveview); mCustomBracketing = (CheckableImageView)view.findViewById(R.id.custom_bracketing); mFlashCommander = (CheckableImageView)view.findViewById(R.id.flash_commander); mTimelapse = (CheckableImageView)view.findViewById(R.id.timelapse); mFocusBracketing = (CheckableImageView)view.findViewById(R.id.focus_bracketing); mShootingMode.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(mContext, PtpProperty.ExposureProgramMode, "Select exposure program mode", null); } }); mSceneMode.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(mContext, PtpProperty.SceneMode, "Select Scene mode", null); } }); mCameraMode.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().getPtpDevice().changeCameraMode(); } }); mLiveView.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (mLiveView.isChecked()) DslrHelper.getInstance().getPtpDevice().endLiveViewCmd(true); else DslrHelper.getInstance().getPtpDevice().startLiveViewCmd(); } }); mCustomBracketing.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { BracketingDialog dialog = new BracketingDialog(mContext); dialog.show(); } }); mCustomBracketing.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { PtpDevice ptpDevice = DslrHelper.getInstance().getPtpDevice(); ptpDevice.setIsCustomBracketingEnabled(!ptpDevice.getIsCustomBracketingEnabled()); mCustomBracketing.setChecked(ptpDevice.getIsCustomBracketingEnabled()); return true; } }); mTimelapse.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { TimelapseDialog dialog = new TimelapseDialog(mContext); dialog.show(); } }); mFlashCommander.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { FlashCommanderFragment dialog = new FlashCommanderFragment(); dialog.show(((Activity)mContext).getFragmentManager().beginTransaction() , "flash_commnder"); // FlashDialog dialog = new FlashDialog(mContext); // dialog.show(); } }); mFocusBracketing.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { FocusStackingDialog dialog = new FocusStackingDialog(mContext); dialog.show(); } }); if (DslrHelper.getInstance().getIsInitialized() && DslrHelper.getInstance().getPtpDevice().getIsInitialized()) updateDisplay(); return view; } public void initDisplay(){ updateDisplay(); } private void updateDisplay() { DslrHelper dslrHelper = DslrHelper.getInstance(); if (dslrHelper != null && dslrHelper.getIsInitialized()) { if (dslrHelper.getPtpDevice().getIsCommandSupported(PtpCommand.ChangeCameraMode)) mCameraMode.setVisibility(View.VISIBLE); else mCameraMode.setVisibility(View.GONE); PtpProperty property = dslrHelper.getPtpDevice().getPtpProperty(PtpProperty.ExposureProgramMode); if (property != null) { dslrHelper.setDslrImg(mShootingMode, property); mShootingMode.setEnabled(property.getIsWritable()); if (mCameraMode.getVisibility() == View.VISIBLE) { mCameraMode.setChecked(property.getIsWritable()); mCameraMode.setImageResource(mCameraMode.isChecked() ? R.drawable.hostmode : R.drawable.cameramode); } } else mShootingMode.setVisibility(View.GONE); property = dslrHelper.getPtpDevice().getPtpProperty(PtpProperty.SceneMode); if (property != null) { dslrHelper.setDslrImg(mSceneMode, property); } else mSceneMode.setVisibility(View.GONE); property = dslrHelper.getPtpDevice().getPtpProperty(PtpProperty.LiveViewStatus); if (property != null) { boolean lvEnabled = (Integer)property.getValue() != 0; mLiveView.setVisibility(View.VISIBLE); mLiveView.setChecked(lvEnabled); } else mLiveView.setVisibility(View.GONE); mCustomBracketing.setChecked(dslrHelper.getPtpDevice().getIsCustomBracketingEnabled()); property = dslrHelper.getPtpDevice().getPtpProperty(PtpProperty.InternalFlashCommanderSelfComp); if (property != null) mFlashCommander.setVisibility(View.VISIBLE); else mFlashCommander.setVisibility(View.GONE); } } public void ptpPropertyChanged(PtpProperty property) { DslrHelper dslrHelper = DslrHelper.getInstance(); if (property != null && dslrHelper.getIsInitialized() && mCameraMode != null && mShootingMode != null && mLiveView != null) { switch(property.getPropertyCode()) { case PtpProperty.ExposureProgramMode: dslrHelper.setDslrImg(mShootingMode, property); mShootingMode.setEnabled(property.getIsWritable()); if (mCameraMode.getVisibility() == View.VISIBLE) { mCameraMode.setChecked(property.getIsWritable()); mCameraMode.setImageResource(mCameraMode.isChecked() ? R.drawable.hostmode : R.drawable.cameramode); } break; case PtpProperty.SceneMode: dslrHelper.setDslrImg(mSceneMode, property); break; case PtpProperty.LiveViewStatus: boolean lvEnabled = (Integer)property.getValue() != 0; mLiveView.setVisibility(View.VISIBLE); mLiveView.setChecked(lvEnabled); break; } } } public void ptpDeviceEvent(PtpDeviceEvent event, Object eventData) { switch(event) { case BusyBegin: Log.d(TAG, "BusyBegin"); DslrHelper.getInstance().enableDisableControls(mMenuLayout, false); break; case BusyEnd: Log.d(TAG, "BusyEnd"); DslrHelper.getInstance().enableDisableControls(mMenuLayout, true); break; } } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class PtpPartialObjectProccessor implements IPtpCommandFinalProcessor { private static String TAG = "GetPartialObjectProcessor"; public interface PtpPartialObjectProgressListener { public void onProgress(int offset); } private PtpPartialObjectProgressListener mProgressListener; public void setProgressListener(PtpPartialObjectProgressListener listener){ mProgressListener = listener; } private PtpObjectInfo mObjectInfo; private int mOffset = 0; private int mMaxSize = 0x100000; //private byte[] _objectData; private File mFile; private OutputStream mStream; // public byte[] pictureData(){ // return _objectData; // } public PtpObjectInfo objectInfo(){ return mObjectInfo; } public int maxSize(){ return mMaxSize; } public PtpPartialObjectProccessor(PtpObjectInfo objectInfo, File file){ this(objectInfo, 0x100000, file); } public PtpPartialObjectProccessor(PtpObjectInfo objectInfo, int maxSize, File file){ mFile = file; mObjectInfo = objectInfo; mMaxSize = maxSize; //_objectData = new byte[_objectInfo.objectCompressedSize]; try { mStream = new BufferedOutputStream(new FileOutputStream(mFile)); } catch (FileNotFoundException e) { } } public boolean doFinalProcessing(PtpCommand cmd) { boolean result = false; int count = cmd.incomingData().getPacketLength() - 12; if (cmd.isResponseOk()) { try { mStream.write(cmd.incomingData().data(), 12, count); } catch (IOException e) { } //System.arraycopy(cmd.incomingData().data(), 12, _objectData, _offset, count); if ((mOffset + count) < mObjectInfo.objectCompressedSize) { mOffset += count; cmd.getParams().set(1, mOffset); if ((mOffset + mMaxSize) > mObjectInfo.objectCompressedSize) cmd.getParams().set(2, mObjectInfo.objectCompressedSize - mOffset); else cmd.getParams().set(2, mMaxSize); result = true; } else { mOffset += count; try { mStream.flush(); mStream.close(); } catch (IOException e) { } } if (mProgressListener != null){ mProgressListener.onProgress(mOffset); } } return result; } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import com.dslr.dashboard.imgzoom.*; import android.app.Activity; import android.content.ComponentName; import android.content.ContentValues; import android.content.Intent; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.RectF; import android.net.Uri; import android.os.Bundle; import android.os.Vibrator; import android.provider.MediaStore; import android.util.FloatMath; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; public class ImagePreviewActivity extends ActivityBase { private static String TAG = "ImagePreviewActivity"; private ListView mExifList; private ImageView mHistogramView; private boolean mHistogramSeparate = true; private Boolean mIsExifVisible = false; private String[] mExifNames; /** Image zoom view */ private ImageZoomView mZoomView; private TextView mTxtLoading; private LinearLayout mProgressLayout; /** Zoom control */ private DynamicZoomControl mZoomControl; /** Decoded bitmap image */ private Bitmap mBitmap = null; /** On touch listener for zoom view */ // private LongPressZoomListener mZoomListener; private String _imgPath; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "onCreate"); if (savedInstanceState != null) { String tmpPath = savedInstanceState.getString("tmpFile"); if (!tmpPath.isEmpty()) { Log.i(TAG, "Restore from tmp file: " + tmpPath); File f = new File(tmpPath); mBitmap = BitmapFactory.decodeFile(f.getAbsolutePath()); Log.i(TAG, "Delete temp file"); if (!f.delete()) Log.d(TAG, "tmp file not deleted"); } //mBitmap = savedInstanceState.getParcelable("bitmap"); _imgPath = savedInstanceState.getString("imgPath"); } mLongPressTimeout = ViewConfiguration.getLongPressTimeout(); mScaledTouchSlop = ViewConfiguration.get(this).getScaledTouchSlop(); mScaledMaximumFlingVelocity = ViewConfiguration.get(this) .getScaledMaximumFlingVelocity(); mVibrator = (Vibrator)getSystemService("vibrator"); setContentView(R.layout.activity_image_preview); getActionBar().setDisplayShowTitleEnabled(false); getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setDisplayUseLogoEnabled(true); mZoomControl = new DynamicZoomControl(); mZoomView = (ImageZoomView)findViewById(R.id.zoomview); mZoomView.setZoomState(mZoomControl.getZoomState()); mZoomView.setOnTouchListener(mZoomListener); mZoomControl.setAspectQuotient(mZoomView.getAspectQuotient()); mZoomView.setVisibility(View.GONE); mHistogramView = (ImageView)findViewById(R.id.histogram_view); mHistogramView.setAlpha((float)0.4); mHistogramView.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mHistogramSeparate = !mHistogramSeparate; mHistogramView.setImageBitmap(NativeMethods.getInstance().createHistogramBitmap(mBitmap, mHistogramSeparate)); } }); mTxtLoading = (TextView)findViewById(R.id.txtLoading); mProgressLayout = (LinearLayout)findViewById(R.id.progresslayout); mExifList = (ListView)findViewById(R.id.exifList); mExifNames = getResources().getStringArray(R.array.exifNames); } private void toggleActionBar(){ if (getActionBar().isShowing()) getActionBar().hide(); else getActionBar().show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { Log.d(TAG, "onCreateOptionsMenu"); getMenuInflater().inflate(R.menu.menu_image_preview, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.menu_histogram: if (mHistogramView.getVisibility() == View.GONE) { mHistogramView.setImageBitmap(NativeMethods.getInstance().createHistogramBitmap(mBitmap, mHistogramSeparate)); mHistogramView.setVisibility(View.VISIBLE); } else mHistogramView.setVisibility(View.GONE); return true; case R.id.menu_exif: displayExif(); return true; case R.id.menu_share: shareImage(); return true; default: return true; } } private void displayExif() { if (_imgPath != null && !_imgPath.isEmpty()){ if (!mIsExifVisible) { ArrayList<ExifDataHelper> exifs = NativeMethods.getInstance().getImageExif(mExifNames, _imgPath); ExifAdapter adapter = new ExifAdapter(this, exifs); mExifList.setAdapter(adapter); } mIsExifVisible = !mIsExifVisible; mExifList.setVisibility(mIsExifVisible ? View.VISIBLE : View.GONE); } } private int reqCode = 1; private String tmpPath; private boolean isTemporary = false; private void shareImage(){ tmpPath = _imgPath; if (!tmpPath.isEmpty() && mBitmap != null) { // if nef we need to save to jpg if (tmpPath.substring((tmpPath.lastIndexOf(".") + 1), tmpPath.length()).toLowerCase().equals("nef")) { tmpPath = tmpPath.substring(0, tmpPath.lastIndexOf(".") + 1) + "jpg"; isTemporary = saveAsJpeg(new File(tmpPath)); if (isTemporary) NativeMethods.getInstance().copyExifData(_imgPath, tmpPath); } File f = new File(tmpPath); ContentValues values = new ContentValues(2); values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg"); values.put(MediaStore.Images.Media.DATA, f.getAbsolutePath()); Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("image/png"); intent.putExtra(Intent.EXTRA_STREAM, uri); intent.putExtra(Intent.EXTRA_TEXT, "Shared with DslrDashboard"); startActivityForResult(Intent.createChooser(intent , "How do you want to share?"), reqCode); } } private boolean saveAsJpeg(File f) { FileOutputStream fOut; try { fOut = new FileOutputStream(f); mBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut); fOut.flush(); fOut.close(); return true; } catch (Exception e) { return false; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(TAG, "onActivityResult"); if (requestCode == reqCode) { Log.d(TAG, "Result: " + resultCode); if (isTemporary) { Log.d(TAG, "Temporary file, delete"); File f = new File(tmpPath); f.delete(); } else Log.d(TAG, "Original file shared"); } super.onActivityResult(requestCode, resultCode, data); } @Override protected void onResume() { super.onResume(); Log.d(TAG, "onResume"); if (mBitmap != null) { Log.d(TAG, "displaying image"); displayBitmap(mBitmap); } } @Override protected void onPause() { Log.d(TAG, "onPause"); super.onPause(); } @Override protected void onStart() { Log.d(TAG, "onStart"); if (mBitmap != null) loadImage(null); else { Intent intent = getIntent(); if (intent != null){ Log.d(TAG, "Image from intent"); Uri data = intent.getData(); if (data != null) { String path = data.getEncodedPath(); Log.d(TAG, "Image path " + path); _imgPath = path; loadImage(path); } else if (intent.hasExtra("data")){ Log.d(TAG, "Image from bitmap "); mBitmap = BitmapFactory.decodeByteArray( intent.getByteArrayExtra("data"),0,getIntent().getByteArrayExtra("data").length); loadImage(null); } else { Log.d(TAG, "No data in intent"); loadImage(null); } } else { Log.d(TAG, "No Intent"); loadImage(null); } } super.onStart(); } @Override protected void onStop() { Log.d(TAG, "onStop"); super.onStop(); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy - bitmap recycle"); mZoomView.setImage(null); if (mBitmap != null) mBitmap.recycle(); mBitmap = null; super.onDestroy(); } @Override protected void onSaveInstanceState(Bundle outState) { if (mBitmap != null) { // check if this is a nef file, then save as temp file File cache = getCacheDir(); File f; try { f = File.createTempFile("dslr", "jpg", cache); if (saveAsJpeg(f)) { Log.d(TAG, "Tmp file: " + f.getAbsolutePath()); outState.putString("tmpFile", f.getAbsolutePath()); } } catch (IOException e) { } } if (_imgPath != null && !_imgPath.isEmpty()) outState.putString("imgPath", _imgPath); Log.d(TAG, "onSaveInstanceState"); super.onSaveInstanceState(outState); } @Override public void onConfigurationChanged(Configuration newConfig) { Log.d(TAG, "onConfigurationChanged"); super.onConfigurationChanged(newConfig); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch(keyCode) { case KeyEvent.KEYCODE_BACK: if (mBitmap != null) { mBitmap.recycle(); //mBitmap = null; } finish(); return true; default: return super.onKeyDown(keyCode, event); } } private Bitmap loadJpeg(String path) { Log.i(TAG,"loading:"+path); //final int IMAGE_MAX_SIZE = 8000000; // 1.2MP Bitmap bm = null; File file=new File(path); BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; try { FileInputStream fis = new FileInputStream(file); BitmapFactory.decodeStream(fis, null, o); fis.close(); } catch (IOException e) { return null; } int scale = 1; int width = o.outWidth; int height = o.outHeight; while ((int)(width / scale) > 2048 || (int)(height / scale) > 2048) scale++; scale++; // while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) > IMAGE_MAX_SIZE) { // scale++; // } Log.i(TAG, "Sample size: " + scale); BitmapFactory.Options bfOptions=new BitmapFactory.Options(); bfOptions.inMutable = true; bfOptions.inSampleSize = scale; bfOptions.inDither=false; //Disable Dithering mode bfOptions.inPurgeable=true; //Tell to gc that whether it needs free memory, the Bitmap can be cleared bfOptions.inInputShareable=true; //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future bfOptions.inTempStorage=new byte[32 * 1024]; FileInputStream fs=null; try { fs = new FileInputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); } try { if(fs!=null) bm=BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions); } catch (IOException e) { } finally{ if(fs!=null) { try { fs.close(); } catch (IOException e) { } } } return bm; } private void displayBitmap(final Bitmap bmp){ runOnUiThread(new Runnable() { public void run() { if (bmp != null) { Log.d(TAG, "displayBitmap"); mProgressLayout.setVisibility(View.GONE); mZoomView.setImage(bmp); mZoomView.setVisibility(View.VISIBLE); resetZoomState(); } } }); } private float calcBarHeight(int value, int max, int height) { float proc = (float)(100 * value) / (float)max; return (float) height * proc / (float) 100; } private void loadImage(final String path){ new Thread(new Runnable() { public void run() { try { if (path != null && !path.isEmpty()) { File f = new File(path); if (f.exists()) { if (path.substring((path.lastIndexOf(".") + 1), path.length()).toLowerCase().equals("nef")) { mBitmap = (Bitmap)NativeMethods.getInstance().loadRawImage(path); Log.d(TAG, "IsMutable: " + mBitmap.isMutable()); //drawHistogram(mBitmap); } else { mBitmap = loadJpeg(path); } } } } catch (Exception e) { Log.e(TAG, "Exeption: " + e.getMessage()); } if (mBitmap != null) { displayBitmap(mBitmap); } } }).start(); } private void resetZoomState() { mZoomControl.getZoomState().setPanX(0.5f); mZoomControl.getZoomState().setPanY(0.5f); mZoomControl.getZoomState().setZoom(1f); mZoomControl.getZoomState().notifyObservers(); } /** * Enum defining listener modes. Before the view is touched the listener is * in the UNDEFINED mode. Once touch starts it can enter either one of the * other two modes: If the user scrolls over the view the listener will * enter PAN mode, if the user lets his finger rest and makes a longpress * the listener will enter ZOOM mode. */ private enum Mode { UNDEFINED, PAN, ZOOM, PINCH, FULLSCREEN } /** Time of tactile feedback vibration when entering zoom mode */ private static final long VIBRATE_TIME = 50; /** Current listener mode */ private Mode mMode = Mode.UNDEFINED; /** X-coordinate of previously handled touch event */ private float mX; /** Y-coordinate of previously handled touch event */ private float mY; /** X-coordinate of latest down event */ private float mDownX; /** Y-coordinate of latest down event */ private float mDownY; /** Velocity tracker for touch events */ private VelocityTracker mVelocityTracker; /** Distance touch can wander before we think it's scrolling */ private int mScaledTouchSlop; /** Duration in ms before a press turns into a long press */ private int mLongPressTimeout; /** Vibrator for tactile feedback */ private Vibrator mVibrator; /** Maximum velocity for fling */ private int mScaledMaximumFlingVelocity; float dist0, distCurrent, mCenterx, mCentery; private View.OnTouchListener mZoomListener = new View.OnTouchListener() { /** * Runnable that enters zoom mode */ private final Runnable mLongPressRunnable = new Runnable() { public void run() { // mMode = Mode.ZOOM; // mVibrator.vibrate(VIBRATE_TIME); } }; // implements View.OnTouchListener public boolean onTouch(View v, MotionEvent event) { final int action = event.getAction() & MotionEvent.ACTION_MASK; final float x = event.getX(); final float y = event.getY(); float distx, disty; if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(event); switch (action) { case MotionEvent.ACTION_DOWN: mZoomControl.stopFling(); v.postDelayed(mLongPressRunnable, mLongPressTimeout); mDownX = x; mDownY = y; mX = x; mY = y; mMode = Mode.FULLSCREEN; break; case MotionEvent.ACTION_POINTER_DOWN: //Get the distance when the second pointer touch mMode = Mode.PINCH; distx = Math.abs(event.getX(0) - event.getX(1)); disty = Math.abs(event.getY(0) - event.getY(1)); dist0 = FloatMath.sqrt(distx * distx + disty * disty); mCenterx = ((event.getX(0) + event.getX(1)) / 2) / v.getWidth(); mCentery = ((event.getY(0) + event.getY(1)) / 2) / v.getHeight(); Log.d(TAG, "Pinch mode"); break; case MotionEvent.ACTION_POINTER_UP: mMode = Mode.UNDEFINED; break; case MotionEvent.ACTION_MOVE: { final float dx = (x - mX) / v.getWidth(); final float dy = (y - mY) / v.getHeight(); if (mMode == Mode.ZOOM) { //Log.d(TAG, "dy: " + dy + "zoom: " + (float)Math.pow(20, -dy)); mZoomControl.zoom((float)Math.pow(20, -dy), mDownX / v.getWidth(), mDownY / v.getHeight()); } else if (mMode == Mode.PAN) { mZoomControl.pan(-dx, -dy); } else if (mMode == Mode.PINCH) { //Get the current distance distx = Math.abs(event.getX(0) - event.getX(1)); disty = Math.abs(event.getY(0) - event.getY(1)); distCurrent = FloatMath.sqrt(distx * distx + disty * disty); float factor = (float)Math.pow(2, -(dist0 - distCurrent)/1000); mZoomControl.zoom(factor, mCenterx, mCentery); } else if (mMode == Mode.FULLSCREEN) { mMode = Mode.PAN; } else { final float scrollX = mDownX - x; final float scrollY = mDownY - y; final float dist = (float)Math.sqrt(scrollX * scrollX + scrollY * scrollY); if (dist >= mScaledTouchSlop) { v.removeCallbacks(mLongPressRunnable); mMode = Mode.PAN; } } mX = x; mY = y; break; } case MotionEvent.ACTION_UP: switch (mMode) { case PAN: mVelocityTracker.computeCurrentVelocity(1000, mScaledMaximumFlingVelocity); mZoomControl.startFling(-mVelocityTracker.getXVelocity() / v.getWidth(), -mVelocityTracker.getYVelocity() / v.getHeight()); break; case FULLSCREEN: toggleActionBar(); break; case PINCH: break; default: mZoomControl.startFling(0, 0); break; } mVelocityTracker.recycle(); mVelocityTracker = null; v.removeCallbacks(mLongPressRunnable); mMode = Mode.UNDEFINED; break; default: mVelocityTracker.recycle(); mVelocityTracker = null; v.removeCallbacks(mLongPressRunnable); mMode = Mode.UNDEFINED; break; } return true; } }; @Override protected void serviceConnected(Class<?> serviceClass, ComponentName name, ServiceBase service) { // TODO Auto-generated method stub } @Override protected void serviceDisconnected(Class<?> serviceClass, ComponentName name) { // TODO Auto-generated method stub } @Override protected void processArduinoButtons( EnumSet<ArduinoButtonEnum> pressedButtons, EnumSet<ArduinoButtonEnum> releasedButtons) { for (ArduinoButtonEnum button : releasedButtons) { switch (button) { case Button4: generateKeyEvent(new KeyEvent(button.getLongPressStart(), button.getLongPressEnd(), KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK,0)); break; case Button5: generateKeyEvent(new KeyEvent(button.getLongPressStart(), button.getLongPressEnd(), KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER,0)); break; case Button6: generateKeyEvent(new KeyEvent(button.getLongPressStart(), button.getLongPressEnd(), KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_LEFT,0)); break; case Button7: generateKeyEvent(new KeyEvent(button.getLongPressStart(), button.getLongPressEnd(), KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_RIGHT,0)); break; case Button8: generateKeyEvent(new KeyEvent(button.getLongPressStart(), button.getLongPressEnd(), KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_UP,0)); break; case Button9: generateKeyEvent(new KeyEvent(button.getLongPressStart(), button.getLongPressEnd(), KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_DOWN,0)); break; } Log.d(TAG, "Released button: " + button.toString() + " is long press: " + button.getIsLongPress()); } for (ArduinoButtonEnum button : pressedButtons) { switch(button){ case Button4: generateKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK)); break; case Button5: generateKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER)); break; case Button6: generateKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT)); break; case Button7: generateKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT)); break; case Button8: generateKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_UP)); break; case Button9: generateKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_DOWN)); break; } Log.d(TAG, "Pressed button: " + button.toString()); } } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class PtpPropertyListAdapter extends BaseAdapter { private ArrayList<PtpPropertyListItem> mItemList; private Context mContext; private LayoutInflater mInflater; private int mSelectedItem; public PtpPropertyListAdapter(Context context, ArrayList<PtpPropertyListItem> itemList, int selectedItem){ super(); mSelectedItem = selectedItem; mContext = context; mItemList = itemList; mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public int getCount() { return mItemList.size(); } public Object getItem(int position) { return mItemList.get(position); } public long getItemId(int position) { return 0; } public static class ViewHolder { ImageView mImageViewLogo; TextView mTextViewTitle; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if(convertView==null) { holder = new ViewHolder(); convertView = mInflater.inflate(R.layout.property_list_item, null); holder.mImageViewLogo = (ImageView) convertView.findViewById(R.id.imgViewLogo); holder.mTextViewTitle = (TextView) convertView.findViewById(R.id.txtViewTitle); convertView.setTag(holder); } else holder=(ViewHolder)convertView.getTag(); PtpPropertyListItem listItem = (PtpPropertyListItem) mItemList.get(position); if (listItem.getImage() > 0) { holder.mImageViewLogo.setImageResource(listItem.getImage()); holder.mImageViewLogo.setVisibility(View.VISIBLE); } else { holder.mImageViewLogo.setImageDrawable(null); holder.mImageViewLogo.setVisibility(View.GONE); } if (listItem.getNameId() > 0) holder.mTextViewTitle.setText(listItem.getNameId()); else holder.mTextViewTitle.setText(listItem.getTitle()); return convertView; } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import android.app.Activity; import android.content.SharedPreferences; import android.graphics.PorterDuffColorFilter; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; public class LeftFragment extends DslrFragmentBase { private static final String TAG = "LeftFragment"; private LinearLayout mLeftLayout, mLeftScrollLayout; private CheckableImageView mInitiateCapture, mAutoFocus, mMovieRec; private PorterDuffColorFilter mColorFilterRed; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_left, container, false); mColorFilterRed = new PorterDuffColorFilter(getResources().getColor(R.color.Red), android.graphics.PorterDuff.Mode.SRC_ATOP); mLeftLayout = (LinearLayout)view.findViewById(R.id.left_layout); mLeftScrollLayout = (LinearLayout)view.findViewById(R.id.left_scroll_layout); mInitiateCapture = (CheckableImageView)view.findViewById(R.id.initiatecapture); mAutoFocus = (CheckableImageView)view.findViewById(R.id.autofocus); mMovieRec = (CheckableImageView)view.findViewById(R.id.movierec); mInitiateCapture.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { getPtpDevice().initiateCaptureCmd(true); } }); mInitiateCapture.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { getPtpDevice().setCaptureToSdram(!getPtpDevice().getCaptureToSdram()); //mInitiateCapture.setColorFilter(getPtpDevice().getCaptureToSdram() ? mColorFilterRed : null); return true; } }); mAutoFocus.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { getPtpDevice().startAfDriveCmd(); } }); mAutoFocus.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { getPtpDevice().setAFBeforeCapture(!getPtpDevice().getAFBeforeCapture()); setAfColor(); return true; } }); mMovieRec.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (!getPtpDevice().getIsMovieRecordingStarted()) getPtpDevice().startMovieRecCmd(); else getPtpDevice().stopMovieRecCmd(); } }); return view; } @Override public void onAttach(Activity activity) { super.onAttach(activity); Log.d(TAG, "onAttach"); } @Override public void onStart() { Log.d(TAG, "onStart"); super.onStart(); } @Override public void onResume() { Log.d(TAG, "onResume"); super.onResume(); } @Override public void onPause() { Log.d(TAG, "onPause"); super.onPause(); } @Override public void onStop() { Log.d(TAG, "onStop"); super.onStop(); } @Override public void onDestroy() { Log.d(TAG, "onDestroy"); super.onDestroy(); } @Override public void onDetach() { Log.d(TAG, "onDetach"); super.onDetach(); } @Override protected void internalInitFragment() { if (getIsPtpDeviceInitialized()) { if (getPtpDevice().getIsLiveViewEnabled()){ // toggle movie recording button; toggleMovieRecVisibility(); } else mMovieRec.setVisibility(View.GONE); if (getPtpDevice().getIsCommandSupported(PtpCommand.AfDrive)) { mAutoFocus.setVisibility(View.VISIBLE); setAfColor(); } else mAutoFocus.setVisibility(View.GONE); if (getPtpDevice().getCaptureToSdram()) mInitiateCapture.setColorFilter(mColorFilterRed); else mInitiateCapture.setColorFilter(null); } } private void toggleMovieRecVisibility(){ if (getPtpDevice().getIsCommandSupported(PtpCommand.StartMovieRecInCard)) { mMovieRec.setVisibility(View.VISIBLE); if (getPtpDevice().getIsMovieRecordingStarted()) mMovieRec.setColorFilter(mColorFilterRed); else mMovieRec.setColorFilter(null); } else mMovieRec.setVisibility(View.GONE); } @Override protected void internalPtpPropertyChanged(PtpProperty property) { // TODO Auto-generated method stub } @Override protected void ptpDeviceEvent(PtpDeviceEvent event, Object data) { switch (event) { case LiveviewStart: toggleMovieRecVisibility(); break; case LiveviewStop: mMovieRec.setVisibility(View.GONE); break; case MovieRecordingStart: mMovieRec.setColorFilter(mColorFilterRed); break; case MovieRecordingEnd: mMovieRec.setColorFilter(null); break; case BusyBegin: Log.d(TAG, "Busy begin"); DslrHelper.getInstance().enableDisableControls(mLeftLayout, false); DslrHelper.getInstance().enableDisableControls(mLeftScrollLayout, false); break; case BusyEnd: Log.d(TAG, "Busy end"); DslrHelper.getInstance().enableDisableControls(mLeftLayout, true); DslrHelper.getInstance().enableDisableControls(mLeftScrollLayout, true); break; case RecordingDestinationChanged: mInitiateCapture.setColorFilter(getPtpDevice().getCaptureToSdram() ? mColorFilterRed : null); break; } } private void setAfColor(){ if (getPtpDevice().getAFBeforeCapture()) mAutoFocus.setColorFilter(mColorFilterRed); else mAutoFocus.setColorFilter(null); } @Override protected void internalSharedPrefsChanged(SharedPreferences prefs, String key) { if (key.equals(PtpDevice.PREF_KEY_SHOOTING_AF)) { setAfColor(); } } }
Java
package com.dslr.dashboard; /** * @author Ashok Gelal * copyright: Ashok */ public class TimeSpan{ public static final long TicksPerMillisecond = 10000L; public static final long TicksPerSecond = 10000000L; public static final long TicksPerMinute = 600000000L; public static final long TicksPerHour = 36000000000L; public static final long TicksPerDay = 864000000000L; public static final TimeSpan Zero = new TimeSpan(0); public static final TimeSpan MinValue = new TimeSpan(Long.MIN_VALUE); public static final TimeSpan MaxValue = new TimeSpan(Long.MAX_VALUE); private long ticks; public int Hours() { return hours; } public int Minutes() { return minutes; } public int Seconds() { return seconds; } public int Days() { return days; } public int Milliseconds() { return milliseconds; } private int days; private int hours; private int minutes; private int seconds; private int milliseconds; private void TotalDays(double totalDays) { this.totalDays = totalDays; } private void TotalHours(double totalHours) { this.totalHours = totalHours; } private void TotalMinutes(double totalMinutes) { this.totalMinutes = totalMinutes; } private void TotalSeconds(double totalSeconds) { this.totalSeconds = totalSeconds; } public double TotalDays() { return totalDays; } public double TotalHours() { return totalHours; } public double TotalMinutes() { return totalMinutes; } public double TotalSeconds() { return totalSeconds; } public double TotalMilliseconds() { return totalMilliseconds; } private void TotalMilliseconds(double totalMilliseconds) { this.totalMilliseconds = totalMilliseconds; } private double totalDays; private double totalHours; private double totalMinutes; private double totalSeconds; private double totalMilliseconds; public long Ticks() { return ticks; } public TimeSpan(long ticks) { this.ticks = ticks; ConvertTicksToTotalTime(); ConvertTicksToTime(); } private void ConvertTicksToTime() { days = (int)(ticks / (TicksPerDay+0.0)); long diff = (ticks - TicksPerDay * days); hours = (int)(diff / (TicksPerHour+0.0)); diff = (diff - TicksPerHour * hours); minutes = (int)(diff / (TicksPerMinute+0.0)); diff = (diff - TicksPerMinute * minutes); seconds = (int)(diff / (TicksPerSecond + 0.0)); diff = (diff - TicksPerSecond * seconds); milliseconds = (int)((diff / TicksPerMillisecond+0.0)); } private void ConvertTicksToTotalTime() { TotalDays(ticks / (TicksPerDay + 0.0f)); TotalHours(ticks / (TicksPerHour + 0.0f)); TotalMinutes(ticks / (TicksPerMinute + 0.0f)); TotalSeconds(ticks/(TicksPerSecond+0.0f)); TotalMilliseconds(ticks/(TicksPerMillisecond+0.0f)); } public TimeSpan(int hours, int minutes, int seconds) { this(0, hours, minutes, seconds); } public TimeSpan(int days, int hours, int minutes, int seconds) { this(days, hours, minutes, seconds, 0); } public TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds) { this.days = days; this.hours = hours; this.minutes = minutes; this.seconds = seconds; this.milliseconds = milliseconds; CalculateTicks(); } private void CalculateTicks(){ this.ticks = days * TicksPerDay + hours * TicksPerHour + minutes * TicksPerMinute + seconds * TicksPerSecond + milliseconds * TicksPerMillisecond; ConvertTicksToTotalTime(); } public static TimeSpan Add(TimeSpan t1, TimeSpan t2) { return new TimeSpan(t1.ticks+t2.ticks); } public TimeSpan Add(TimeSpan t1) { return new TimeSpan(this.ticks + t1.ticks); } @Override public boolean equals(Object other){ if(other == null) return false; if(other == this) return true; if(this.getClass() != other.getClass()) return false; TimeSpan otherClass = (TimeSpan) other; return (ticks==otherClass.Ticks()); } public boolean Equals(TimeSpan other) { return equals(other); } public static boolean Equals(TimeSpan time1, TimeSpan time2) { return time1.Equals(time2); } public boolean GreaterThan(TimeSpan time) { return ticks > time.Ticks(); } public boolean GreaterThanOrEqual(TimeSpan time) { return ticks >= time.Ticks(); } public boolean NotEquals(TimeSpan time) { return !Equals(time); } public boolean LessThan(TimeSpan time) { return ticks < time.Ticks(); } public boolean LessThanOrEqual(TimeSpan time) { return ticks <= time.Ticks(); } public TimeSpan Subtract(TimeSpan time) { return new TimeSpan(ticks - time.Ticks()); } public static TimeSpan Subtract(TimeSpan time1, TimeSpan time2) { return new TimeSpan(time1.Ticks() - time2.Ticks()); } public TimeSpan Duration() { return new TimeSpan(Math.abs(ticks)); } public static TimeSpan FromDays(double days) { return new TimeSpan((long)(Math.ceil(days * 24 * 3600 * 1000) * TicksPerMillisecond)); } public static TimeSpan FromHours(double hours) { return new TimeSpan((long)(Math.ceil(hours * 3600 * 1000) * TicksPerMillisecond)); } public static TimeSpan FromMinutes(double minutes) { return new TimeSpan((long)(Math.ceil(minutes * 60 * 1000) * TicksPerMillisecond)); } public static TimeSpan FromSeconds(double seconds) { return new TimeSpan((long)(Math.ceil(seconds * 1000) * TicksPerMillisecond)); } public static TimeSpan FromMilliseconds(double milliseconds) { return new TimeSpan((long)(Math.ceil(milliseconds) * TicksPerMillisecond)); } public static TimeSpan FromTicks(long ticks) { return new TimeSpan(ticks); } @Override public String toString() { StringBuilder str = new StringBuilder(); if(days>=1 || days<=-1) str.append(String.format("%02d.", days)); str.append(String.format("%02d:", hours)); str.append(String.format("%02d:", minutes)); str.append(String.format("%02d", seconds)); if(milliseconds>=1) str.append(String.format(".%d%s", milliseconds, TRAILING_ZEROS.substring(Integer.toString(milliseconds).length()))); return str.toString(); } private static final String TRAILING_ZEROS = "0000000"; }
Java
// Copyright 2000 by David Brownell <dbrownell@users.sourceforge.net> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // package com.dslr.dashboard; public class PtpResponse { /** ResponseCode: */ public static final int Undefined = 0x2000; /** ResponseCode: */ public static final int OK = 0x2001; /** ResponseCode: */ public static final int GeneralError = 0x2002; /** ResponseCode: */ public static final int SessionNotOpen = 0x2003; /** ResponseCode: */ public static final int InvalidTransactionID = 0x2004; /** ResponseCode: */ public static final int OperationNotSupported = 0x2005; /** ResponseCode: */ public static final int ParameterNotSupported = 0x2006; /** ResponseCode: */ public static final int IncompleteTransfer = 0x2007; /** ResponseCode: */ public static final int InvalidStorageID = 0x2008; /** ResponseCode: */ public static final int InvalidObjectHandle = 0x2009; /** ResponseCode: */ public static final int DevicePropNotSupported = 0x200a; /** ResponseCode: */ public static final int InvalidObjectFormatCode = 0x200b; /** ResponseCode: */ public static final int StoreFull = 0x200c; /** ResponseCode: */ public static final int ObjectWriteProtected = 0x200d; /** ResponseCode: */ public static final int StoreReadOnly = 0x200e; /** ResponseCode: */ public static final int AccessDenied = 0x200f; /** ResponseCode: */ public static final int NoThumbnailPresent = 0x2010; /** ResponseCode: */ public static final int SelfTestFailed = 0x2011; /** ResponseCode: */ public static final int PartialDeletion = 0x2012; /** ResponseCode: */ public static final int StoreNotAvailable = 0x2013; /** ResponseCode: */ public static final int SpecificationByFormatUnsupported = 0x2014; /** ResponseCode: */ public static final int NoValidObjectInfo = 0x2015; /** ResponseCode: */ public static final int InvalidCodeFormat = 0x2016; /** ResponseCode: */ public static final int UnknownVendorCode = 0x2017; /** ResponseCode: */ public static final int CaptureAlreadyTerminated = 0x2018; /** ResponseCode: */ public static final int DeviceBusy = 0x2019; /** ResponseCode: */ public static final int InvalidParentObject = 0x201a; /** ResponseCode: */ public static final int InvalidDevicePropFormat = 0x201b; /** ResponseCode: */ public static final int InvalidDevicePropValue = 0x201c; /** ResponseCode: */ public static final int InvalidParameter = 0x201d; /** ResponseCode: */ public static final int SessionAlreadyOpen = 0x201e; /** ResponseCode: */ public static final int TransactionCanceled = 0x201f; /** ResponseCode: */ public static final int SpecificationOfDestinationUnsupported = 0x2020; public static final int HardwareError = 0xa001; public static final int OutOfFocus = 0xa002; public static final int ChangeCameraModeFailed = 0xa003; public static final int InvalidStatus = 0xa004; public static final int SetPropertyNotSupport = 0xa005; public static final int WbPresetError = 0xa006; public static final int DustRefenreceError = 0xa007; public static final int ShutterSpeedBulb = 0xa008; public static final int MirrorUpSquence = 0xa009; public static final int CameraModeNotAdjustFnumber = 0xa00a; public static final int NotLiveView = 0xa00b; public static final int MfDriveStepEnd = 0xa00c; public static final int MfDriveStepInsufficiency = 0xa00e; public static final int InvalidObjectPropCode = 0xa801; public static final int InvalidObjectPropFormat = 0xa802; public static final int ObjectPropNotSupported = 0xa80a; }
Java
// Copyright 2000 by David Brownell <dbrownell@users.sourceforge.net> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // package com.dslr.dashboard; public class PtpDeviceInfo { private int mStandardVersion; private int mVendorExtensionId; private int mVendorExtensionVersion; private String mVendorExtensionDesc; private int mFunctionalMode; // may change; private int mOperationsSupported []; // 10.2 private int mEventsSupported []; // 12.5 private int mPropertiesSupported []; // 13.3.5 private int mCaptureFormats []; // 6 private int mImageFormats []; // 6 private String mManufacturer; private String mModel; private String mDeviceVersion; private String mSerialNumber; private boolean mIsInitialized = false; public PtpDeviceInfo () { mIsInitialized = false; } public PtpDeviceInfo(PtpBuffer data) { parse(data); } public int getStandardVersion() { return mStandardVersion; } public int getVendorExtensionId() { return mVendorExtensionId; } public int getVendorExtensionVersion() { return mVendorExtensionVersion; } public String getVendorExtensionDesc() { return mVendorExtensionDesc; } public int getFunctionalMode() { return mFunctionalMode; } public int[] getOperationsSupported() { return mOperationsSupported; } public int[] getEventsSupported() { return mEventsSupported; } public int[] getPropertiesSupported() { return mPropertiesSupported; } public int[] getCaptureFormats() { return mCaptureFormats; } public int[] getImageFormats() { return mImageFormats; } public String getManufacturer(){ return mManufacturer; } public String getModel() { return mModel; } public String getDeviceVersion(){ return mDeviceVersion; } public String getSerialNumber(){ return mSerialNumber; } public boolean getIsInitialized() { return mIsInitialized; } private boolean supports (int supported [], int code) { for (int i = 0; i < supported.length; i++) { if (code == supported [i]) return true; } return false; } /** Returns true iff the device supports this operation */ public boolean supportsOperation (int opCode) { return supports (mOperationsSupported, opCode); } /** Returns true iff the device supports this event */ public boolean supportsEvent (int eventCode) { return supports (mEventsSupported, eventCode); } /** Returns true iff the device supports this property */ public boolean supportsProperty (int propCode) { return supports (mPropertiesSupported, propCode); } /** Returns true iff the device supports this capture format */ public boolean supportsCaptureFormat (int formatCode) { return supports (mCaptureFormats, formatCode); } /** Returns true iff the device supports this image format */ public boolean supportsImageFormat (int formatCode) { return supports (mImageFormats, formatCode); } public void parse (PtpBuffer data) { data.parse(); mStandardVersion = data.nextU16 (); mVendorExtensionId = /* unsigned */ data.nextS32 (); mVendorExtensionVersion = data.nextU16 (); mVendorExtensionDesc = data.nextString (); mFunctionalMode = data.nextU16 (); mOperationsSupported = data.nextU16Array (); mEventsSupported = data.nextU16Array (); mPropertiesSupported = data.nextU16Array (); mCaptureFormats = data. nextU16Array (); mImageFormats = data.nextU16Array (); mManufacturer = data.nextString (); mModel = data.nextString (); mDeviceVersion = data.nextString (); mSerialNumber = data.nextString (); mIsInitialized = true; } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import java.util.ArrayList; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.CheckBox; import android.widget.TextView; public class BracketingDialog{ private static String TAG = "BracketingDialog"; private Context mContext; private DslrHelper mDslrHelper; private PtpDevice mPtpDevice; private View mView; private TextView txtCustomBktStep, txtCustomBktDirection, txtCustomBktCount; private CheckBox mBktFocusFirst; public BracketingDialog(Context context) { mContext = context; mDslrHelper = DslrHelper.getInstance(); mPtpDevice = mDslrHelper.getPtpDevice(); LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mView = inflater.inflate(R.layout.bracketingdialog, null); // addContentView(layout, new LayoutParams( // LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); //((TextView) layout.findViewById(R.id.title)).setText("Custom Bracketing settings"); txtCustomBktStep = (TextView)mView.findViewById(R.id.txt_custombktstep); txtCustomBktDirection = (TextView)mView.findViewById(R.id.txt_custombktdirection); txtCustomBktCount = (TextView)mView.findViewById(R.id.txt_custombktcount); mBktFocusFirst = (CheckBox)mView.findViewById(R.id.bkt_focus_first); setCustomValues(); txtCustomBktStep.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { customBktStepDialog(); } }); txtCustomBktDirection.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { customBktDirektionDialog(); } }); txtCustomBktCount.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { customBktCountDialog(); } }); mBktFocusFirst.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mPtpDevice.setCustomBracketingFocusFirst(mBktFocusFirst.isChecked()); } }); } public void show() { CustomDialog.Builder customBuilder = new CustomDialog.Builder(mContext); customBuilder.setTitle("Custom Bracketing settings") .setContentView(mView); customBuilder .create() .show(); } private void setCustomValues(){ if (mPtpDevice != null && mPtpDevice.getIsPtpDeviceInitialized()){ txtCustomBktDirection.setText(getCustomBktDirection(mPtpDevice.getCustomBracketingDirection())); txtCustomBktCount.setText((String.format("%d", mPtpDevice.getCustomBracketingCount()))); PtpProperty property = mPtpDevice.getPtpProperty(PtpProperty.ExposureEvStep); if (property != null) { if ((Integer)property.getValue() == 0) txtCustomBktStep.setText(String.format("%.1f EV", mPtpDevice.getCustomBracketingStep() * (1f / 3f))); else txtCustomBktStep.setText(String.format("%.1f EV", mPtpDevice.getCustomBracketingStep() * (1f / 2f))); } mBktFocusFirst.setChecked(mPtpDevice.getCustomBracketingFocusFirst()); //txtCustomBktStep.setText((String.format("%d", _dslrHelper.getPtpService().getBktStep()))); } } private String getCustomBktDirection(int direktion){ switch(direktion){ case 0: return "Negative"; case 1: return "Positive"; case 2: return "Both"; default: return "Both"; } } private void customBktCountDialog(){ final ArrayList<PtpPropertyListItem> items = new ArrayList<PtpPropertyListItem>(); int selectedItem = -1; for(int i = 0; i <= 3; i++){ int current = 3 + (i * 2); if (current == mPtpDevice.getCustomBracketingCount()) selectedItem = i; PtpPropertyListItem item = new PtpPropertyListItem(); item.setImage(-1); item.setValue(current); item.setTitle(String.format("%d images", current)); items.add(item); } CustomDialog.Builder customBuilder = new CustomDialog.Builder(mContext); customBuilder.setTitle("Custom bracketing count") .setListItems(items, selectedItem) .setListOnClickListener(new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (which >= 0 && which < items.size()){ mPtpDevice.setCustomBracketingCount((Integer) items.get(which).getValue()); txtCustomBktCount.setText(items.get(which).getTitle()); } } }); CustomDialog dialog = customBuilder.create(); dialog.show(); } private void customBktDirektionDialog(){ final ArrayList<PtpPropertyListItem> items = new ArrayList<PtpPropertyListItem>(); for(int i = 0; i <= 2; i++){ PtpPropertyListItem item = new PtpPropertyListItem(); item.setImage(-1); item.setValue(i); item.setTitle(getCustomBktDirection(i)); items.add(item); } CustomDialog.Builder customBuilder = new CustomDialog.Builder(mContext); customBuilder.setTitle("Custom bracketing direktion") .setListItems(items, mPtpDevice.getCustomBracketingDirection()) .setListOnClickListener(new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (which >= 0 && which < items.size()){ mPtpDevice.setCustomBracketingDirection((Integer) items.get(which).getValue()); txtCustomBktDirection.setText(items.get(which).getTitle()); } } }); CustomDialog dialog = customBuilder.create(); dialog.show(); } private void customBktStepDialog(){ PtpProperty prop = mPtpDevice.getPtpProperty(PtpProperty.ExposureEvStep); if (prop != null){ int evStep = (Integer) prop.getValue(); final ArrayList<PtpPropertyListItem> items = new ArrayList<PtpPropertyListItem>(); switch(evStep) { case 0: // 1/3 for(int i = 1; i <= 6; i++){ PtpPropertyListItem item = new PtpPropertyListItem(); item.setImage(-1); item.setTitle(String.format("%.1f EV", i * (1f / 3f))); item.setValue(i); items.add(item); } break; case 1: // 1/2 if (mPtpDevice.getCustomBracketingStep() > 4) mPtpDevice.setCustomBracketingStep(1); for(int i = 1; i <= 4; i++){ PtpPropertyListItem item = new PtpPropertyListItem(); item.setImage(-1); item.setTitle(String.format("%.1f EV", i * (1f / 2f))); item.setValue(i); items.add(item); } break; } CustomDialog.Builder customBuilder = new CustomDialog.Builder(mContext); customBuilder.setTitle("Custom bracketing EV step") .setListItems(items, mPtpDevice.getCustomBracketingStep() - 1) .setListOnClickListener(new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (which >= 0 && which < items.size()){ mPtpDevice.setCustomBracketingStep((Integer) items.get(which).getValue()); txtCustomBktStep.setText(items.get(which).getTitle()); } } }); CustomDialog dialog = customBuilder.create(); dialog.show(); } } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import android.content.Context; import android.content.DialogInterface; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.SeekBar; import android.widget.TextView; public class TimelapseDialog { private final static String TAG = "TimelapseDialog"; private Context mContext; private DslrHelper mDslrHelper; private PtpDevice mPtpDevice; private View mView; private TextView txtCaptureDuration; private TextView txtMovieLength; private TextView txtInterval; private TextView txtFrameRate; private TextView txtFrameCount; private Button mStartTimelapse; private SeekBar mSeekBar; private CustomDialog mDialog; private TimeSpan mCaptureDuration; private TimeSpan mMovieLength; private TimeSpan mInterval; private int mFrameRate = 25; private int mFrameCount= 0; public TimelapseDialog(Context context) { mContext = context; mDslrHelper = DslrHelper.getInstance(); mPtpDevice = mDslrHelper.getPtpDevice(); LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mView = inflater.inflate(R.layout.timelapsedialog, null); mCaptureDuration = new TimeSpan(0, 0, 0); mMovieLength = new TimeSpan(0, 0, 0); mInterval = new TimeSpan(0, 0, 0); txtCaptureDuration = (TextView)mView.findViewById(R.id.txtcaptureduration); txtMovieLength = (TextView)mView.findViewById(R.id.txtmovielength); txtInterval = (TextView)mView.findViewById(R.id.txtinterval); txtFrameRate = (TextView)mView.findViewById(R.id.txtframerate); txtFrameCount = (TextView)mView.findViewById(R.id.txtframecount); mStartTimelapse = (Button)mView.findViewById(R.id.timelapse_start); mSeekBar = (SeekBar)mView.findViewById(R.id.timelapse_framerate); mSeekBar.setProgress(mFrameRate); if (mPtpDevice != null) { Log.d(TAG, "Interval: " + mPtpDevice.getTimelapseInterval()); Log.d(TAG, "Iterations: " + mPtpDevice.getTimelapseIterations()); mInterval = TimeSpan.FromMilliseconds(mPtpDevice.getTimelapseInterval()); mFrameCount = mPtpDevice.getTimelapseIterations(); mMovieLength = TimeSpan.FromSeconds(mFrameCount / mFrameRate); mCaptureDuration = TimeSpan.FromSeconds(mInterval.TotalSeconds() * mFrameCount); } // calculateRecordingLength(); updateDisplay(); txtCaptureDuration.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { TimePickerDialog tpd = new TimePickerDialog(mContext, "", mCaptureDuration, new TimePickerDialog.OnTimeSetListener() { public void onTimeSet(int hourOfDay, int minute, int second) { mCaptureDuration = new TimeSpan(hourOfDay, minute, second); mFrameCount = (int)(mCaptureDuration.TotalMilliseconds() / mInterval.TotalMilliseconds()); mMovieLength = TimeSpan.FromSeconds(mFrameCount * mFrameRate); updateDisplay(); //calculateInterval(); } }); tpd.show(); } }); txtMovieLength.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { new TimePickerDialog(mContext, "", mMovieLength, new TimePickerDialog.OnTimeSetListener() { public void onTimeSet(int hourOfDay, int minute, int second) { mMovieLength = new TimeSpan(hourOfDay, minute, second); mFrameCount = (int)(mMovieLength.TotalSeconds() * mFrameRate); mCaptureDuration = TimeSpan.FromMilliseconds(mInterval.TotalMilliseconds() * mFrameCount); updateDisplay(); //calculateFrameCount(); //calculateInterval(); } }).show(); } }); txtInterval.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { new TimePickerDialog(mContext, "", mInterval, new TimePickerDialog.OnTimeSetListener() { public void onTimeSet(int hourOfDay, int minute, int second) { mInterval = new TimeSpan(hourOfDay, minute, second); mCaptureDuration = TimeSpan.FromMilliseconds(mInterval.TotalMilliseconds() * mFrameCount); updateDisplay(); //calculateRecordingLength(); } }).show(); } }); mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { public void onStopTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { if (progress > 0) { mFrameRate = progress; mFrameCount = (int)(mMovieLength.TotalSeconds() * mFrameRate); mCaptureDuration = TimeSpan.FromMilliseconds(mInterval.TotalMilliseconds() * mFrameCount); updateDisplay(); } } } }); // txtFrameRate.addTextChangedListener(new TextWatcher() { // // public void onTextChanged(CharSequence s, int start, int before, int count) { // // TODO Auto-generated method stub // // } // // public void beforeTextChanged(CharSequence s, int start, int count, // int after) { // // TODO Auto-generated method stub // // } // // public void afterTextChanged(Editable s) { // try { // mFrameRate = Integer.parseInt(s.toString()); // // //calculateFrameCount(); // //calculateInterval(); // } catch (NumberFormatException e) { // // } // } // }); mStartTimelapse.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Log.d(TAG, "Interval: " + mInterval.TotalMilliseconds()); Log.d(TAG, "Iterations: " + mFrameCount); mPtpDevice.startTimelapse((long)mInterval.TotalMilliseconds(), mFrameCount); mDialog.dismiss(); } }); } private void calculateRecordingLength(){ double recordingLength = mFrameRate * mMovieLength.TotalSeconds() * mInterval.TotalSeconds(); mCaptureDuration = TimeSpan.FromSeconds(recordingLength); txtCaptureDuration.setText(mCaptureDuration.toString()); Log.d(TAG, "Recording length " + recordingLength / 3600); } private void calculateInterval() { double frameCount = mFrameRate * mMovieLength.TotalSeconds(); double interval = 0; if (frameCount > 0) interval = (mCaptureDuration.TotalHours() * 3600) / frameCount; mInterval = TimeSpan.FromSeconds(interval); txtInterval.setText(mInterval.toString()); Log.d(TAG, "interval " + interval); } private void calculateFrameCount(){ mFrameCount = (int)(mMovieLength.TotalSeconds() * mFrameRate); txtFrameCount.setText(String.format("%d", mFrameCount)); } private void updateDisplay(){ txtFrameRate.setText(String.format("%d", mFrameRate)); txtCaptureDuration.setText(mCaptureDuration.toString()); txtMovieLength.setText(mMovieLength.toString()); txtInterval.setText(mInterval.toString()); txtFrameCount.setText(String.format("%d", mFrameCount)); } public void show() { CustomDialog.Builder customBuilder = new CustomDialog.Builder(mContext); customBuilder.setTitle("Timelapse settings") .setContentView(mView); mDialog = customBuilder .create(); mDialog.show(); } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import android.os.Bundle; import android.preference.PreferenceFragment; public class SettingsFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; public abstract class PtpCommunicatorBase { protected abstract void processCommand(PtpCommand cmd) throws Exception; public abstract boolean getIsNetworkCommunicator(); public abstract int getWriteEpMaxPacketSize(); public abstract void closeCommunicator(); }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; public class ExifDataHelper { public String mExifName; public String mExifDescription; public String mExifValue; public ExifDataHelper(String exifName, String exifDescription) { mExifName = exifName; mExifDescription = exifDescription; } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import java.util.ArrayList; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import android.util.Log; public class PtpCommand implements Callable<PtpCommand> { private static String TAG = "PtpCommand"; public interface OnCommandFinishedListener { public void onCommandFinished(PtpCommand command); } private OnCommandFinishedListener _cmdFinishedListener = null; private int mCommandCode; protected ArrayList<Integer> mParams; private int mSessionId = 0; private boolean mHasSessionId = false; private PtpBuffer mBuffer; private byte[] mCommandData = null; private boolean mHasSendData = false; private PtpCommunicatorBase mCommunicator; private IPtpCommandFinalProcessor mFinalProcessor = null; private String mNotificationMsg; public int getCommandCode(){ return mCommandCode; } public IPtpCommandFinalProcessor getFinalProcessor(){ return mFinalProcessor; } public ArrayList<Integer> getParams(){ return mParams; } public int getSssionId(){ return mSessionId; } public boolean getHasSessionId(){ return mHasSessionId; } public boolean getHasSendData(){ return mHasSendData; } public PtpCommunicatorBase getCommunicator(){ return mCommunicator; } public String getNotificatinMsg(){ return mNotificationMsg; } public PtpCommand addParam(int param) { mParams.add(param); return this; } public PtpCommand setCommandData(byte[] commandData){ mCommandData = commandData; mHasSendData = true; return this; } public PtpCommand setOnCommandFinishedListener(OnCommandFinishedListener listener){ _cmdFinishedListener = listener; return this; } public PtpCommand setFinalProcessor(IPtpCommandFinalProcessor processor){ mFinalProcessor = processor; return this; } public FutureTask<PtpCommand> getTask(PtpCommunicatorBase communicator){ mCommunicator = communicator; return new FutureTask<PtpCommand>(this); } public PtpCommand(int commandCode){ mCommandCode = commandCode; mParams = new ArrayList<Integer>(); mBuffer = new PtpBuffer(); } public PtpCommand(String notification){ mNotificationMsg = notification; mCommandCode = 0; } public PtpCommand call() throws Exception { //Log.d(TAG, "Before sending command: " + _communicator); try { mCommunicator.processCommand(this); } catch (Exception e) { Log.d(TAG, e.getMessage()); throw e; } if (_cmdFinishedListener != null) _cmdFinishedListener.onCommandFinished(this); //Log.d(TAG, String.format("Command finished: %#04x", _commandCode)); return this; } protected byte[] getCommandPacket(int sessionId){ mSessionId = sessionId; mHasSessionId = true; int bufLen = 12 + (4 * mParams.size()); byte[] data = new byte[bufLen]; mBuffer.wrap(data); mBuffer.put32(bufLen); // size of the packet mBuffer.put16(1); // this is a command packet mBuffer.put16(mCommandCode); // command code mBuffer.put32(mSessionId); // session id for(int i = 0; i < mParams.size(); i++){ mBuffer.put32(mParams.get(i)); } return data; } protected byte[] getCommandDataPacket(){ if (mHasSessionId && mHasSendData){ mBuffer.wrap(new byte[12 + mCommandData.length]); mBuffer.put32(mBuffer.length()); // size will be later set; mBuffer.put16(2); // this is a data packet mBuffer.put16(mCommandCode); // the command code mBuffer.put32(mSessionId); // session id // copy the data byte[] to the packet System.arraycopy(mCommandData, 0, mBuffer.data(), 12, mCommandData.length); return mBuffer.data(); } else return null; } private boolean mHasData = false; private boolean mHasResponse = false; private PtpBuffer mIncomingData = null; private PtpBuffer mIncomingResponse = null; private boolean _needMoreBytes = false; private int _bytesCount = 0; private int _packetLen = 0; private byte[] _tmpData = null; public boolean hasData(){ return mHasData; } public boolean hasResponse(){ return mHasResponse; } public boolean isResponseOk(){ return mHasResponse ? mIncomingResponse.getPacketCode() == PtpResponse.OK : false; } public int getResponseCode() { return mHasResponse ? mIncomingResponse.getPacketCode() : 0; } public boolean isDataOk(){ return mHasData ? isResponseOk() : false; } public PtpBuffer incomingData(){ return mIncomingData; } public PtpBuffer incomingResponse(){ return mIncomingResponse; } public int responseParam(){ if (mHasResponse){ mIncomingResponse.parse(); return mIncomingResponse.nextS32(); } return 0; } protected boolean newPacket(byte[] packet, int size){ if (_needMoreBytes){ System.arraycopy(packet, 0, _tmpData, _bytesCount, size); _bytesCount += size; if (_bytesCount >= _packetLen){ _needMoreBytes = false; processPacket(); return false; } else return true; } else { mBuffer.wrap(packet); _packetLen = mBuffer.getPacketLength(); int packetType = mBuffer.getPacketType(); switch(packetType){ case 2: // data mIncomingData = new PtpBuffer(new byte[_packetLen]); _tmpData = mIncomingData.data(); break; case 3: // response mIncomingResponse = new PtpBuffer(new byte[_packetLen]); _tmpData = mIncomingResponse.data(); break; } System.arraycopy(packet, 0, _tmpData, 0, size); if (_packetLen > size) {// we need more bytes _needMoreBytes = true; _bytesCount = size; return true; } else { processPacket(); return false; } } } protected void processPacket(){ mBuffer.wrap(_tmpData); switch (mBuffer.getPacketType()) { case 2: //Log.d(TAG, "--- Incoming data packet"); mHasData = true; break; case 3: //Log.d(TAG, "--- Incoming response packet"); mHasResponse = true; //Log.d(TAG, "--- Response code " + Integer.toHexString(_incomingResponse.getPacketCode())); break; default: break; } } private void reset(){ mHasSessionId = false; mHasData = false; mHasResponse = false; _needMoreBytes = false; mIncomingData = null; mIncomingResponse = null; _tmpData = null; } public boolean weFinished() { boolean result = doFinalProcessing(); if (!result){ // we finished } else { // we need another run, reset evrything reset(); } return result; } protected boolean doFinalProcessing(){ return mFinalProcessor == null ? false : mFinalProcessor.doFinalProcessing(this); } public static final int GetDeviceInfo = 0x1001; public static final int OpenSession = 0x1002; public static final int CloseSession = 0x1003; public static final int GetStorageIDs = 0x1004; public static final int GetStorageInfo = 0x1005; public static final int GetNumObjects = 0x1006; public static final int GetObjectHandles = 0x1007; public static final int GetObjectInfo = 0x1008; public static final int GetObject = 0x1009; public static final int GetThumb = 0x100a; public static final int DeleteObject = 0x100b; public static final int SendObjectInfo = 0x100c; public static final int SendObject = 0x100d; public static final int InitiateCapture = 0x100e; public static final int FormatStore = 0x100f; public static final int ResetDevice = 0x1010; public static final int SelfTest = 0x1011; public static final int SetObjectProtection = 0x1012; public static final int PowerDown = 0x1013; public static final int GetDevicePropDesc = 0x1014; public static final int GetDevicePropValue = 0x1015; public static final int SetDevicePropValue = 0x1016; public static final int ResetDevicePropValue = 0x1017; public static final int TerminateOpenCapture = 0x1018; public static final int MoveObject = 0x1019; public static final int CopyObject = 0x101a; public static final int GetPartialObject = 0x101b; public static final int InitiateOpenCapture = 0x101c; public static final int InitiateCaptureRecInSdram = 0x90c0; public static final int AfDrive = 0x90c1; public static final int ChangeCameraMode = 0x90c2; public static final int DeleteImagesInSdram = 0x90c3; public static final int GetLargeThumb = 0x90c4; public static final int GetEvent = 0x90c7; public static final int DeviceReady = 0x90c8; public static final int SetPreWbData = 0x90c9; public static final int GetVendorPropCodes = 0x90ca; public static final int AfAndCaptureRecInSdram = 0x90cb; public static final int GetPicCtrlData = 0x90cc; public static final int SetPicCtrlData = 0x90cd; public static final int DeleteCustomPicCtrl = 0x90ce; public static final int GetPicCtrlCapability = 0x90cf; public static final int GetPreviewImage = 0x9200; public static final int StartLiveView = 0x9201; public static final int EndLiveView = 0x9202; public static final int GetLiveViewImage = 0x9203; public static final int MfDrive = 0x9204; public static final int ChangeAfArea = 0x9205; public static final int AfDriveCancel = 0x9206; public static final int InitiateCaptureRecInMedia = 0x9207; public static final int StartMovieRecInCard = 0x920a; public static final int EndMovieRec = 0x920b; public static final int MtpGetObjectPropsSupported = 0x9801; public static final int MtpGetObjectPropDesc = 0x9802; public static final int MtpGetObjectPropValue = 0x9803; public static final int MtpSetObjectPropValue = 0x9804; public static final int MtpGetObjPropList = 0x9805; }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; public class RightFragmentLv extends DslrFragmentBase { private static final String TAG = "RightFragmentLv"; private LinearLayout mRightLvLayout; private CheckableImageView mZoomIn, mZoomOut, mLvFocusMode, mMovieRecordWithVoice, mMovieRecordMicrophoneLevel, mMovieRecordSize; private TextView mVideoMode, mAfAtLiveView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_right_lv, container, false); mRightLvLayout = (LinearLayout)view.findViewById(R.id.right_lv_layout); mZoomIn = (CheckableImageView)view.findViewById(R.id.lvzoomin); mZoomOut = (CheckableImageView)view.findViewById(R.id.lvzoomout); mLvFocusMode = (CheckableImageView)view.findViewById(R.id.lvfocusmode); mAfAtLiveView = (TextView)view.findViewById(R.id.afatliveview); mVideoMode = (TextView)view.findViewById(R.id.videomode); mMovieRecordSize = (CheckableImageView)view.findViewById(R.id.movierecordsize); mMovieRecordWithVoice = (CheckableImageView)view.findViewById(R.id.movierecordwithvoice); mMovieRecordMicrophoneLevel = (CheckableImageView)view.findViewById(R.id.movierecordmicrophonelevel); mZoomIn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (getDslrActivity() != null) getDslrActivity().zoomLiveView(true); } }); mZoomOut.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (getDslrActivity() != null) getDslrActivity().zoomLiveView(false); } }); mLvFocusMode.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.AfAtLiveView, "Select LV Focus Mode", null); } }); mVideoMode.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.VideoMode, "Select Video mode", null); } }); mMovieRecordSize.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.MovieRecordScreenSize, getMovieRecordSizeOffset(), "Select Movie recording screen size", null); } }); mMovieRecordWithVoice.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.MovieRecordWithVoice, "Select Movie voice recording mode", null); } }); mMovieRecordMicrophoneLevel.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.MovieRecordMicrophoneLevel, "Select Movie recording Microphone level", null); } }); return view; } @Override public void onAttach(Activity activity) { super.onAttach(activity); Log.d(TAG, "onAttach"); } @Override public void onStart() { Log.d(TAG, "onStart"); super.onStart(); } @Override public void onResume() { Log.d(TAG, "onResume"); super.onResume(); } @Override public void onPause() { Log.d(TAG, "onPause"); super.onPause(); } @Override public void onStop() { Log.d(TAG, "onStop"); super.onStop(); } @Override public void onDestroy() { Log.d(TAG, "onDestroy"); super.onDestroy(); } @Override public void onDetach() { Log.d(TAG, "onDetach"); super.onDetach(); } private int getMovieRecordSizeOffset() { Integer offset = 0; switch(getPtpDevice().getProductId()) { case 0x0428: case 0x0429: PtpProperty vMode = getPtpDevice().getPtpProperty(PtpProperty.VideoMode); if (vMode != null) { if ((Integer)vMode.getValue() == 1) offset = 16; } break; default: break; } return offset; } @Override protected void internalInitFragment() { if (getIsPtpDeviceInitialized()) { initializePtpPropertyView(mLvFocusMode, getPtpDevice().getPtpProperty(PtpProperty.AfAtLiveView)); initializePtpPropertyView(mAfAtLiveView, getPtpDevice().getPtpProperty(PtpProperty.AfModeAtLiveView)); initializePtpPropertyView(mVideoMode, getPtpDevice().getPtpProperty(PtpProperty.VideoMode)); initializePtpPropertyView(mMovieRecordSize, getPtpDevice().getPtpProperty(PtpProperty.MovieRecordScreenSize)); initializePtpPropertyView(mMovieRecordWithVoice, getPtpDevice().getPtpProperty(PtpProperty.MovieRecordWithVoice)); initializePtpPropertyView(mMovieRecordMicrophoneLevel, getPtpDevice().getPtpProperty(PtpProperty.MovieRecordMicrophoneLevel)); } } @Override protected void internalPtpPropertyChanged(PtpProperty property) { if (property != null) { switch (property.getPropertyCode()) { case PtpProperty.AfAtLiveView: DslrHelper.getInstance().setDslrImg(mLvFocusMode, property); break; case PtpProperty.AfModeAtLiveView: DslrHelper.getInstance().setDslrTxt(mAfAtLiveView, property); break; case PtpProperty.VideoMode: DslrHelper.getInstance().setDslrTxt(mVideoMode, property); break; case PtpProperty.MovieRecordScreenSize: DslrHelper.getInstance().setDslrImg(mMovieRecordSize,getMovieRecordSizeOffset(), property); break; case PtpProperty.MovieRecordWithVoice: DslrHelper.getInstance().setDslrImg(mMovieRecordWithVoice, property); break; case PtpProperty.MovieRecordMicrophoneLevel: DslrHelper.getInstance().setDslrImg(mMovieRecordMicrophoneLevel, property); break; } } } @Override protected void ptpDeviceEvent(PtpDeviceEvent event, Object data) { switch(event) { case BusyBegin: DslrHelper.getInstance().enableDisableControls(mRightLvLayout, false); break; case BusyEnd: DslrHelper.getInstance().enableDisableControls(mRightLvLayout, true); break; } } @Override protected void internalSharedPrefsChanged(SharedPreferences prefs, String key) { // TODO Auto-generated method stub } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; public class UsbAttachedActivity extends Activity { private static final String TAG = "UsbAttachedActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "onCreate"); } @Override protected void onRestart() { Log.d(TAG, "onRestart"); super.onRestart(); } @Override protected void onStart() { Log.d(TAG, "onStart"); super.onStart(); } @Override protected void onNewIntent(Intent intent) { Log.d(TAG, "onNewIntent"); super.onNewIntent(intent); } @Override protected void onResume() { Log.d(TAG, "onResume"); Intent intent = new Intent(this, MainActivity.class); intent.setAction(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); Bundle extras = new Bundle(); extras.putBoolean("UsbAttached", true); intent.putExtras(extras); startActivity(intent); finish(); super.onResume(); } @Override protected void onPause() { Log.d(TAG, "onPause"); super.onPause(); } @Override protected void onStop() { Log.d(TAG, "onStop"); super.onStop(); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy"); super.onDestroy(); } }
Java
// Copyright 2000 by David Brownell <dbrownell@users.sourceforge.net> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // package com.dslr.dashboard; import android.util.Log; public class PtpSession { private static String TAG = "PtpSession"; private int sessionId; private int xid; private boolean active; public PtpSession () { } int getNextXID () { return (active ? xid++ : 0); } int getNextSessionID () { if (!active) return ++sessionId; else return xid++; } public boolean isActive () { return active; } public void open () { xid = 1; active = true; Log.d(TAG, "**** sesion opened");} public void close () { active = false; } int getSessionId () { return sessionId; } // track objects and their info by handles; // hookup to marshaling system and event framework }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.ComponentName; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.WindowManager; public class MainActivity extends ActivityBase implements IDslrActivity { private static final String TAG = "MainActivity"; private boolean mCheckForUsb = false; private List<WeakReference<Fragment>> mFragments = new ArrayList<WeakReference<Fragment>>(); private MenuItem mMainMenuItem; private MainMenuProvider mMainMenuProvider; private BottomFragment mBottomFragment; private RightFragment mRightFragment; private LeftFragment mLeftFragment; private LiveViewFragment mLiveViewFragment; private RightFragmentLv mRightFragmentLv; private AboutFragment mAboutFragment; private ProgressFragment mProgressFragment; private DslrFragmentBase mLeft, mRight, mBottom, mCenter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "onCreate"); setContentView(R.layout.activity_main); //SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if (mPrefs.getBoolean(PtpDevice.PREF_KEY_GENERAL_SCREEN_ON, true)) getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); else getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); mMainMenuProvider = new MainMenuProvider(this); getActionBar().setDisplayShowTitleEnabled(false); getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setDisplayUseLogoEnabled(true); mBottomFragment = new BottomFragment(); mRightFragment = new RightFragment(); mLeftFragment = new LeftFragment(); mLiveViewFragment = new LiveViewFragment(); mRightFragmentLv = new RightFragmentLv(); mAboutFragment = new AboutFragment(); mProgressFragment = new ProgressFragment(); mBottom = mBottomFragment; mLeft = mLeftFragment; mRight = mRightFragment; mCenter = mAboutFragment; getFragmentManager().beginTransaction() .replace(R.id.center_layout, mCenter) .commit(); } private void toggleKeepScreenOn(){ if (getPtpDevice().getGeneralScreenOn()) getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); else getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } @Override public boolean onCreateOptionsMenu(Menu menu) { Log.d(TAG, "onCreateOptionsMenu"); getMenuInflater().inflate(R.menu.activity_main, menu); mMainMenuItem = menu.findItem(R.id.menu_action_test); mMainMenuItem.setActionProvider(mMainMenuProvider); if (mPtpDevice != null && mPtpDevice.getIsPtpDeviceInitialized()) mMainMenuItem.setVisible(true); else mMainMenuItem.setVisible(false); return true; } @Override protected void onRestart() { Log.d(TAG, "onRestart"); super.onRestart(); } @Override protected void onStart() { Log.d(TAG, "onStart"); super.onStart(); } @Override protected void onResume() { Log.d(TAG, "onResume"); checkUsbIntent(getIntent()); doBindService(PtpService.class); super.onResume(); } @Override protected void onPause() { Log.d(TAG, "onPause"); unbindPtpService(true, true); setPtpDevice(null); super.onPause(); } @Override protected void onStop() { Log.d(TAG, "onStop"); super.onStop(); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy"); super.onDestroy(); } @Override protected void onNewIntent(Intent intent) { Log.d(TAG, "onNewIntent"); checkUsbIntent(intent); super.onNewIntent(intent); } @Override public void onAttachFragment(Fragment fragment) { super.onAttachFragment(fragment); Log.d(TAG, "onAttachFragment"); try { if (fragment instanceof DslrFragmentBase) Log.d(TAG, "This is DslrFramentBase"); DslrFragmentBase dslrFragment = (DslrFragmentBase)fragment; if (dslrFragment != null) { if (!mFragments.contains(fragment)) { Log.d(TAG, "attach new fragment"); mFragments.add(new WeakReference<Fragment>(fragment)); } } } catch (ClassCastException e) { Log.d(TAG, "Not DSLR fragment"); } } private void checkUsbIntent(Intent intent) { if (intent != null ) { Bundle extras = intent.getExtras(); if (extras != null) { if (extras.containsKey("UsbAttached")) mCheckForUsb = true; } } } PtpDevice.OnPtpDeviceEventListener mPtpDeviceEventListener = new PtpDevice.OnPtpDeviceEventListener() { public void sendEvent(final PtpDeviceEvent event, final Object data) { Log.d(TAG, "OnPtpDeviceEventListener"); runOnUiThread(new Runnable() { public void run() { switch(event) { case PtpDeviceInitialized: initDisplay(); break; case PtpDeviceStoped: removeDisplay(); break; case PrefsLoaded: toggleKeepScreenOn(); break; case LiveviewStart: //if (!mLiveViewFragment.getIsAttached()) getFragmentManager().beginTransaction() //.remove(mCenter) .replace(R.id.center_layout, mLiveViewFragment) .commit(); mCenter = mLiveViewFragment; break; case LiveviewStop: if (!mProgressFragment.getIsAttached()) { getFragmentManager().beginTransaction() //.remove(mCenter) .replace(R.id.center_layout, mAboutFragment) .commit(); mCenter = mAboutFragment; } toggleFullscreen(false); toggleLvLayout(false); break; case SdCardInfoUpdated: case SdCardInserted: case SdCardRemoved: break; case CaptureStart: break; case CaptureComplete: break; case BusyBegin: if (!mProgressFragment.getIsAttached()) { getFragmentManager() .beginTransaction() .replace(R.id.center_layout, mProgressFragment) .commit(); mCenter = mProgressFragment; } break; case BusyEnd: getFragmentManager() .beginTransaction() .replace(R.id.center_layout, mAboutFragment) .commit(); mCenter = mAboutFragment; break; case ObjectAdded: break; case GetObjectFromSdramInfo: break; case GetObjectFromSdramThumb: break; case GetObjectFromSdramProgress: break; case GetObjectFromCameraProgress: break; case GetObjectFromSdramFinished: break; case GetObjectFromCameraFinished: break; } ptpDeviceEvent(event, data); } }); } }; PtpDevice.OnPtpPropertyChangedListener mPtpPropertyChangedListener = new PtpDevice.OnPtpPropertyChangedListener() { public void sendPtpPropertyChanged(final PtpProperty property) { runOnUiThread(new Runnable() { public void run() { ptpPropertyChanged(property); } }); } }; SharedPreferences.OnSharedPreferenceChangeListener mSharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String key) { runOnUiThread(new Runnable() { public void run() { ptpDeviceSharedPrefs(sharedPreferences, key); if (key.equals(PtpDevice.PREF_KEY_GENERAL_SCREEN_ON)) toggleKeepScreenOn(); } }); } }; private void removeDisplay() { runOnUiThread(new Runnable() { public void run() { FragmentTransaction ft = getFragmentManager().beginTransaction(); if (mBottom != null) ft.remove(mBottom); if (mRight != null) ft.remove(mRight); if (mLeft != null) ft.remove(mLeft); if (mCenter != null && mCenter != mAboutFragment) ft.remove(mCenter); ft.commit(); mMainMenuItem.setVisible(false); } }); } private void initDisplay() { Log.d(TAG, "initDisplay"); DslrHelper.getInstance().loadDslrProperties(this, mPtpDevice, mPtpDevice.getVendorId() , mPtpDevice.getProductId()); if (mPtpDevice.getIsLiveViewEnabled()) mCenter = mLiveViewFragment; else mCenter = mAboutFragment; FragmentTransaction ft = getFragmentManager().beginTransaction(); if (mBottom != null && !mBottom.getIsAttached()) //!mBottom.isAdded()) ft.replace(R.id.bottom_layout, mBottom); if (!mIsFullScreen) { if (mRight != null && !mRight.getIsAttached()) // !mRight.isAdded()) ft.replace(R.id.right_layout, mRight); if (mLeft != null && !mLeft.isAdded()) ft.replace(R.id.left_layout, mLeft); } if (mCenter != null && !mCenter.getIsAttached()) // !mCenter.isAdded()) ft.replace(R.id.center_layout, mCenter); ft.commit(); runOnUiThread(new Runnable() { public void run() { if (mMainMenuItem != null) { mMainMenuItem.setVisible(true); mMainMenuProvider.initDisplay(); } } }); } private void ptpDeviceEvent(PtpDeviceEvent event, Object data) { for (WeakReference<Fragment> wr : mFragments) { Fragment fragment = wr.get(); if (fragment != null) { try{ DslrFragmentBase fr = (DslrFragmentBase)fragment; if (fr.getIsAttached()) fr.ptpDeviceEvent(event, data); } catch (ClassCastException e) { } } } mMainMenuProvider.ptpDeviceEvent(event, data); } private void ptpPropertyChanged(PtpProperty property) { for (WeakReference<Fragment> wr : mFragments) { Fragment fragment = wr.get(); if (fragment != null) { try{ DslrFragmentBase fr = (DslrFragmentBase)fragment; if (fr.getIsAttached()) fr.ptpPropertyChanged(property); } catch (ClassCastException e) { } } } mMainMenuProvider.ptpPropertyChanged(property); } private void ptpDeviceSharedPrefs(SharedPreferences prefs, String key) { for (WeakReference<Fragment> wr : mFragments) { Fragment fragment = wr.get(); if (fragment != null) { try{ DslrFragmentBase fr = (DslrFragmentBase)fragment; if (fr.getIsAttached()) fr.sharedPrefsChanged(prefs, key); } catch (ClassCastException e) { } } } } private void setPtpDevice(PtpDevice ptpDevice) { Log.d(TAG, "setPtpDevice"); // remove listener of the old PtpDevice if (mPtpDevice != null) { mPtpDevice.removeOnPtpDeviceEventListener(); mPtpDevice.removePtpPropertyChangedListener(); mPtpDevice.removeSharedPreferenceChangeListener(); // mPtpDevice.removeLiveViewObjectListener(); } mPtpDevice = ptpDevice; if (mPtpDevice != null) { // if (mPtpDevice.getIsPtpDeviceInitialized()) { // initDisplay(); // } mPtpDevice.setOnPtpDeviceEventListener(mPtpDeviceEventListener); mPtpDevice.setOnPtpPropertyChangedListener(mPtpPropertyChangedListener); mPtpDevice.setOnSharedPreferenceChangeListener(mSharedPreferenceChangeListener); // mPtpDevice.setLiveviewObjectListener(mLiveViewListener); } } // private boolean mIsBound = false; private PtpService mPtpService = null; private PtpDevice mPtpDevice = null; public PtpDevice getPtpDevice() { return mPtpDevice; } private void unbindPtpService(boolean stopService, boolean keepAliveIfUsbConnected) { if (stopService && mPtpService != null) mPtpService.stopPtpService(keepAliveIfUsbConnected); doUnbindService(PtpService.class); } @Override protected void serviceConnected(Class<?> serviceClass, ComponentName name, ServiceBase service) { Log.d(TAG, "onServiceConnected"); if (serviceClass.equals(PtpService.class)) { Log.d(TAG, "PtpService connected"); mPtpService = (PtpService) service; setPtpDevice(mPtpService.getPtpDevice()); startService(new Intent(MainActivity.this, PtpService.class)); if (mCheckForUsb) mPtpService.searchForUsbCamera(); if (mPtpService.getIsUsbDeviceInitialized() && mPtpDevice.getIsPtpDeviceInitialized()) initDisplay(); } } @Override protected void serviceDisconnected(Class<?> serviceClass, ComponentName name) { Log.d(TAG, "onServiceDisconnected " + name.getClassName()); if (serviceClass.equals(PtpService.class)) { Log.d(TAG, "PtpService disconnected"); mPtpService = null; } } public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.menu_settings: getFragmentManager().beginTransaction() .replace(R.id.center_layout, new SettingsFragment()) .addToBackStack("prefs") .commit(); return true; case R.id.menu_search_usb: if (!mPtpService.getIsUsbDeviceInitialized()) mPtpService.searchForUsbCamera(); return true; case R.id.menu_close_usb: if (mPtpService.getIsUsbDeviceInitialized()) mPtpService.closeUsbConnection(); return true; case R.id.menu_action_image_browse: Intent ipIntent = new Intent(this, DslrImageBrowserActivity.class); ipIntent.setAction(Intent.ACTION_VIEW); ipIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); this.startActivity(ipIntent); return true; default: return true; } } private boolean mIsFullScreen = false; public void toggleFullscreen(boolean enable) { if (enable != mIsFullScreen) { if (mPtpDevice != null && mPtpDevice.getIsPtpDeviceInitialized()) { if (!enable) { getActionBar().show(); getFragmentManager().beginTransaction() .replace(R.id.right_layout, mRight) .replace(R.id.left_layout, mLeft) .commit(); } else { getActionBar().hide(); getFragmentManager().beginTransaction() .remove(mRight) .remove(mLeft) .commit(); } mIsFullScreen = enable; } } } public void toggleFullScreen() { toggleFullscreen(!mIsFullScreen); } public boolean getIsFullScreen() { return mIsFullScreen; } private boolean mIsLvLayoutEnabled = false; public boolean getIsLvLayoutEnabled() { return mIsLvLayoutEnabled; } public void toggleLvLayout() { toggleLvLayout(!mIsLvLayoutEnabled); } public void toggleLvLayout(boolean showLvLayout) { if (showLvLayout) { if (mRight != mRightFragmentLv) { mRight = mRightFragmentLv; getFragmentManager().beginTransaction() .replace(R.id.right_layout, mRight) .commit(); } mIsLvLayoutEnabled = true; } else { if (mRight != mRightFragment) { mRight = mRightFragment; getFragmentManager().beginTransaction() .replace(R.id.right_layout, mRight) .commit(); } mIsLvLayoutEnabled = false; } } public void zoomLiveView(boolean up){ if (mPtpDevice != null && mPtpDevice.getIsPtpDeviceInitialized()){ // check if liveview is enabled PtpProperty lvStatus = mPtpDevice.getPtpProperty(PtpProperty.LiveViewStatus); if (lvStatus != null && (Integer)lvStatus.getValue() == 1){ // get the zoom factor PtpProperty zoom = mPtpDevice.getPtpProperty(PtpProperty.LiveViewImageZoomRatio); if (zoom != null){ int zValue = (Integer)zoom.getValue(); if (up){ if (zValue < 5) mPtpDevice.setDevicePropValueCmd(PtpProperty.LiveViewImageZoomRatio, zValue + 1); } else { if (zValue > 0) mPtpDevice.setDevicePropValueCmd(PtpProperty.LiveViewImageZoomRatio, zValue - 1); } } } } } @Override protected void processArduinoButtons(EnumSet<ArduinoButtonEnum> pressedButtons, EnumSet<ArduinoButtonEnum> releasedButtons) { for (ArduinoButtonEnum button : releasedButtons) { switch (button) { case Button0: if (!button.getIsLongPress()) mPtpDevice.initiateCaptureCmd(); else mPtpDevice.setCaptureToSdram(!mPtpDevice.getCaptureToSdram()); break; case Button4: generateKeyEvent(new KeyEvent(button.getLongPressStart(), button.getLongPressEnd(), KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK,0)); break; case Button5: generateKeyEvent(new KeyEvent(button.getLongPressStart(), button.getLongPressEnd(), KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER,0)); break; case Button6: generateKeyEvent(new KeyEvent(button.getLongPressStart(), button.getLongPressEnd(), KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_LEFT,0)); break; case Button7: generateKeyEvent(new KeyEvent(button.getLongPressStart(), button.getLongPressEnd(), KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_RIGHT,0)); break; case Button8: generateKeyEvent(new KeyEvent(button.getLongPressStart(), button.getLongPressEnd(), KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_UP,0)); break; case Button9: generateKeyEvent(new KeyEvent(button.getLongPressStart(), button.getLongPressEnd(), KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_DOWN,0)); break; } Log.d(TAG, "Released button: " + button.toString() + " is long press: " + button.getIsLongPress()); } for (ArduinoButtonEnum button : pressedButtons) { switch(button){ case Button4: generateKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK)); break; case Button5: generateKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER)); break; case Button6: generateKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT)); break; case Button7: generateKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT)); break; case Button8: generateKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_UP)); break; case Button9: generateKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_DOWN)); break; } Log.d(TAG, "Pressed button: " + button.toString()); } } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView.FindListener; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; public class ProgressFragment extends DslrFragmentBase { private static final String TAG = "ProgressFragment"; private TextView mProgressStatusMessage, mProgressFilename, mProgressBracketing, mProgressTimelapse, mProgressFocusStacking; private ProgressBar mProgressDownload; private Button mProgressStopTimelapse, mProgressStopFocusStacking; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_progress, container, false); mProgressStatusMessage = (TextView)view.findViewById(R.id.progress_status_msg); mProgressFilename = (TextView)view.findViewById(R.id.progress_filename); mProgressDownload = (ProgressBar)view.findViewById(R.id.progress_download); mProgressBracketing = (TextView)view.findViewById(R.id.progress_custombracketing); mProgressTimelapse = (TextView)view.findViewById(R.id.progress_timelapse); mProgressStopTimelapse = (Button)view.findViewById(R.id.progress_stop_timelapse); mProgressFocusStacking = (TextView)view.findViewById(R.id.progress_focusstacking); mProgressStopFocusStacking = (Button)view.findViewById(R.id.progress_stop_focusstacking); mProgressStopTimelapse.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { getPtpDevice().stopTimelapse(); mProgressStopTimelapse.setVisibility(View.GONE); } }); mProgressStopFocusStacking.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { getPtpDevice().stopFocusStacking(); mProgressStopFocusStacking.setVisibility(View.GONE); } }); return view; } @Override public void onAttach(Activity activity) { super.onAttach(activity); Log.d(TAG, "onAttach"); } @Override public void onStart() { Log.d(TAG, "onStart"); super.onStart(); } @Override public void onResume() { Log.d(TAG, "onResume"); super.onResume(); } @Override public void onPause() { Log.d(TAG, "onPause"); super.onPause(); } @Override public void onStop() { Log.d(TAG, "onStop"); super.onStop(); } @Override public void onDestroy() { Log.d(TAG, "onDestroy"); super.onDestroy(); } @Override public void onDetach() { Log.d(TAG, "onDetach"); super.onDetach(); } @Override protected void internalInitFragment() { // TODO Auto-generated method stub } @Override protected void internalPtpPropertyChanged(PtpProperty property) { // TODO Auto-generated method stub } @Override protected void ptpDeviceEvent(PtpDeviceEvent event, Object data) { switch (event) { case BusyBegin: mProgressStatusMessage.setText("Camera operation start"); break; case BusyEnd: mProgressBracketing.setVisibility(View.GONE); mProgressTimelapse.setVisibility(View.GONE); mProgressStopTimelapse.setVisibility(View.GONE); mProgressFocusStacking.setVisibility(View.GONE); mProgressStopFocusStacking.setVisibility(View.GONE); mProgressDownload.setVisibility(View.GONE); break; case CaptureStart: case CaptureInitiated: mProgressStatusMessage.setText("Capture start"); if (getPtpDevice().getNeedBracketing()) { mProgressBracketing.setVisibility(View.VISIBLE); mProgressBracketing.setText(String.format("Custom bracketing image %d of %d", getPtpDevice().getCurrentBracketing() + 1, getPtpDevice().getBracketingCount())); } else mProgressBracketing.setVisibility(View.GONE); if (getPtpDevice().getIsTimelapseRunning()) { mProgressTimelapse.setVisibility(View.VISIBLE); mProgressTimelapse.setText(String.format("Timelapse image %d of %d", getPtpDevice().getTimelapseIterations() - getPtpDevice().getTimelapseRemainingIterations() , getPtpDevice().getTimelapseIterations())); mProgressStopTimelapse.setVisibility(View.VISIBLE); } else { mProgressTimelapse.setVisibility(View.GONE); mProgressStopTimelapse.setVisibility(View.GONE); } if (getPtpDevice().getIsInFocusStacking()) { mProgressFocusStacking.setVisibility(View.VISIBLE); mProgressFocusStacking.setText(String.format("Focus stacking image %d of %d", getPtpDevice().getCurrentFocusStackingImage(), getPtpDevice().getFocusImages())); if (!getPtpDevice().getStopFocusStacking()) mProgressStopFocusStacking.setVisibility(View.VISIBLE); } else { mProgressFocusStacking.setVisibility(View.GONE); mProgressStopFocusStacking.setVisibility(View.GONE); } // mProgressMessage1.setText("Image capture started"); break; case CaptureComplete: mProgressStatusMessage.setText("Capture complete"); // mProgressMessage1.setText("Image capture finished"); break; case ObjectAdded: mProgressStatusMessage.setText("Object added"); mProgressDownload.setVisibility(View.GONE); if (data != null) { PtpObjectInfo obj = (PtpObjectInfo)data; mProgressFilename.setText(obj.filename); } break; case GetObjectFromSdramInfo: mProgressStatusMessage.setText("Got image info"); if (data != null) { ImageObjectHelper obj = (ImageObjectHelper)data; if (obj.galleryItemType == ImageObjectHelper.PHONE_PICTURE) { mProgressFilename.setText(obj.file.getName()); mProgressDownload.setVisibility(View.VISIBLE); mProgressDownload.setProgress(0); mProgressDownload.setMax(obj.objectInfo.objectCompressedSize); } else { mProgressFilename.setText(obj.objectInfo.filename); } } break; case GetObjectFromSdramThumb: mProgressStatusMessage.setText("Got image thumb"); // mProgressMessage1.setText("Got image thumb"); break; case GetObjectFromSdramProgress: mProgressStatusMessage.setText("Downloading image"); if (data != null) { ImageObjectHelper obj = (ImageObjectHelper)data; mProgressDownload.setProgress(obj.progress); } break; case GetObjectFromSdramFinished: mProgressStatusMessage.setText("Image transfered from Camera SDRAM"); mProgressDownload.setVisibility(View.GONE); break; } } @Override protected void internalSharedPrefsChanged(SharedPreferences prefs, String key) { // TODO Auto-generated method stub } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.utils.GraphCanvas; import nl.sogeti.android.gpstracker.actions.utils.StatisticsCalulator; import nl.sogeti.android.gpstracker.actions.utils.StatisticsDelegate; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.util.UnitsI18n; import nl.sogeti.android.gpstracker.viewer.TrackList; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.ContentResolver; import android.content.Intent; import android.database.ContentObserver; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.ContextMenu; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextView; import android.widget.ViewFlipper; /** * Display some calulations based on a track * * @version $Id$ * @author rene (c) Oct 19, 2009, Sogeti B.V. */ public class Statistics extends Activity implements StatisticsDelegate { private static final int DIALOG_GRAPHTYPE = 3; private static final int MENU_GRAPHTYPE = 11; private static final int MENU_TRACKLIST = 12; private static final int MENU_SHARE = 41; private static final String TRACKURI = "TRACKURI"; private static final String TAG = "OGT.Statistics"; private static final int SWIPE_MIN_DISTANCE = 120; private static final int SWIPE_MAX_OFF_PATH = 250; private static final int SWIPE_THRESHOLD_VELOCITY = 200; private Uri mTrackUri = null; private boolean calculating; private TextView overallavgSpeedView; private TextView avgSpeedView; private TextView distanceView; private TextView endtimeView; private TextView starttimeView; private TextView maxSpeedView; private TextView waypointsView; private TextView mAscensionView; private TextView mElapsedTimeView; private UnitsI18n mUnits; private GraphCanvas mGraphTimeSpeed; private ViewFlipper mViewFlipper; private Animation mSlideLeftIn; private Animation mSlideLeftOut; private Animation mSlideRightIn; private Animation mSlideRightOut; private GestureDetector mGestureDetector; private GraphCanvas mGraphDistanceSpeed; private GraphCanvas mGraphTimeAltitude; private GraphCanvas mGraphDistanceAltitude; private final ContentObserver mTrackObserver = new ContentObserver( new Handler() ) { @Override public void onChange( boolean selfUpdate ) { if( !calculating ) { Statistics.this.drawTrackingStatistics(); } } }; private OnClickListener mGraphControlListener = new View.OnClickListener() { @Override public void onClick( View v ) { int id = v.getId(); switch( id ) { case R.id.graphtype_timespeed: mViewFlipper.setDisplayedChild( 0 ); break; case R.id.graphtype_distancespeed: mViewFlipper.setDisplayedChild( 1 ); break; case R.id.graphtype_timealtitude: mViewFlipper.setDisplayedChild( 2 ); break; case R.id.graphtype_distancealtitude: mViewFlipper.setDisplayedChild( 3 ); break; default: break; } dismissDialog( DIALOG_GRAPHTYPE ); } }; class MyGestureDetector extends SimpleOnGestureListener { @Override public boolean onFling( MotionEvent e1, MotionEvent e2, float velocityX, float velocityY ) { if( Math.abs( e1.getY() - e2.getY() ) > SWIPE_MAX_OFF_PATH ) return false; // right to left swipe if( e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs( velocityX ) > SWIPE_THRESHOLD_VELOCITY ) { mViewFlipper.setInAnimation( mSlideLeftIn ); mViewFlipper.setOutAnimation( mSlideLeftOut ); mViewFlipper.showNext(); } else if( e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs( velocityX ) > SWIPE_THRESHOLD_VELOCITY ) { mViewFlipper.setInAnimation( mSlideRightIn ); mViewFlipper.setOutAnimation( mSlideRightOut ); mViewFlipper.showPrevious(); } return false; } } /** * Called when the activity is first created. */ @Override protected void onCreate( Bundle load ) { super.onCreate( load ); mUnits = new UnitsI18n( this, new UnitsI18n.UnitsChangeListener() { @Override public void onUnitsChange() { drawTrackingStatistics(); } } ); setContentView( R.layout.statistics ); mViewFlipper = (ViewFlipper) findViewById( R.id.flipper ); mViewFlipper.setDrawingCacheEnabled(true); mSlideLeftIn = AnimationUtils.loadAnimation( this, R.anim.slide_left_in ); mSlideLeftOut = AnimationUtils.loadAnimation( this, R.anim.slide_left_out ); mSlideRightIn = AnimationUtils.loadAnimation( this, R.anim.slide_right_in ); mSlideRightOut = AnimationUtils.loadAnimation( this, R.anim.slide_right_out ); mGraphTimeSpeed = (GraphCanvas) mViewFlipper.getChildAt( 0 ); mGraphDistanceSpeed = (GraphCanvas) mViewFlipper.getChildAt( 1 ); mGraphTimeAltitude = (GraphCanvas) mViewFlipper.getChildAt( 2 ); mGraphDistanceAltitude = (GraphCanvas) mViewFlipper.getChildAt( 3 ); mGraphTimeSpeed.setType( GraphCanvas.TIMESPEEDGRAPH ); mGraphDistanceSpeed.setType( GraphCanvas.DISTANCESPEEDGRAPH ); mGraphTimeAltitude.setType( GraphCanvas.TIMEALTITUDEGRAPH ); mGraphDistanceAltitude.setType( GraphCanvas.DISTANCEALTITUDEGRAPH ); mGestureDetector = new GestureDetector( new MyGestureDetector() ); maxSpeedView = (TextView) findViewById( R.id.stat_maximumspeed ); mAscensionView = (TextView) findViewById( R.id.stat_ascension ); mElapsedTimeView = (TextView) findViewById( R.id.stat_elapsedtime ); overallavgSpeedView = (TextView) findViewById( R.id.stat_overallaveragespeed ); avgSpeedView = (TextView) findViewById( R.id.stat_averagespeed ); distanceView = (TextView) findViewById( R.id.stat_distance ); starttimeView = (TextView) findViewById( R.id.stat_starttime ); endtimeView = (TextView) findViewById( R.id.stat_endtime ); waypointsView = (TextView) findViewById( R.id.stat_waypoints ); if( load != null && load.containsKey( TRACKURI ) ) { mTrackUri = Uri.withAppendedPath( Tracks.CONTENT_URI, load.getString( TRACKURI ) ); } else { mTrackUri = this.getIntent().getData(); } } @Override protected void onRestoreInstanceState( Bundle load ) { if( load != null ) { super.onRestoreInstanceState( load ); } if( load != null && load.containsKey( TRACKURI ) ) { mTrackUri = Uri.withAppendedPath( Tracks.CONTENT_URI, load.getString( TRACKURI ) ); } if( load != null && load.containsKey( "FLIP" ) ) { mViewFlipper.setDisplayedChild( load.getInt( "FLIP" ) ); } } @Override protected void onSaveInstanceState( Bundle save ) { super.onSaveInstanceState( save ); save.putString( TRACKURI, mTrackUri.getLastPathSegment() ); save.putInt( "FLIP" , mViewFlipper.getDisplayedChild() ); } /* * (non-Javadoc) * @see android.app.Activity#onPause() */ @Override protected void onPause() { super.onPause(); mViewFlipper.stopFlipping(); mGraphTimeSpeed.clearData(); mGraphDistanceSpeed.clearData(); mGraphTimeAltitude.clearData(); mGraphDistanceAltitude.clearData(); ContentResolver resolver = this.getContentResolver(); resolver.unregisterContentObserver( this.mTrackObserver ); } /* * (non-Javadoc) * @see android.app.Activity#onResume() */ @Override protected void onResume() { super.onResume(); drawTrackingStatistics(); ContentResolver resolver = this.getContentResolver(); resolver.registerContentObserver( mTrackUri, true, this.mTrackObserver ); } @Override public boolean onCreateOptionsMenu( Menu menu ) { boolean result = super.onCreateOptionsMenu( menu ); menu.add( ContextMenu.NONE, MENU_GRAPHTYPE, ContextMenu.NONE, R.string.menu_graphtype ).setIcon( R.drawable.ic_menu_picture ).setAlphabeticShortcut( 't' ); menu.add( ContextMenu.NONE, MENU_TRACKLIST, ContextMenu.NONE, R.string.menu_tracklist ).setIcon( R.drawable.ic_menu_show_list ).setAlphabeticShortcut( 'l' ); menu.add( ContextMenu.NONE, MENU_SHARE, ContextMenu.NONE, R.string.menu_shareTrack ).setIcon( R.drawable.ic_menu_share ).setAlphabeticShortcut( 's' ); return result; } @Override public boolean onOptionsItemSelected( MenuItem item ) { boolean handled = false; Intent intent; switch( item.getItemId() ) { case MENU_GRAPHTYPE: showDialog( DIALOG_GRAPHTYPE ); handled = true; break; case MENU_TRACKLIST: intent = new Intent( this, TrackList.class ); intent.putExtra( Tracks._ID, mTrackUri.getLastPathSegment() ); startActivityForResult( intent, MENU_TRACKLIST ); break; case MENU_SHARE: intent = new Intent( Intent.ACTION_RUN ); intent.setDataAndType( mTrackUri, Tracks.CONTENT_ITEM_TYPE ); intent.addFlags( Intent.FLAG_GRANT_READ_URI_PERMISSION ); Bitmap bm = mViewFlipper.getDrawingCache(); Uri screenStreamUri = ShareTrack.storeScreenBitmap(bm); intent.putExtra(Intent.EXTRA_STREAM, screenStreamUri); startActivityForResult(Intent.createChooser( intent, getString( R.string.share_track ) ), MENU_SHARE); handled = true; break; default: handled = super.onOptionsItemSelected( item ); } return handled; } @Override public boolean onTouchEvent( MotionEvent event ) { if( mGestureDetector.onTouchEvent( event ) ) return true; else return false; } /* * (non-Javadoc) * @see android.app.Activity#onActivityResult(int, int, android.content.Intent) */ @Override protected void onActivityResult( int requestCode, int resultCode, Intent intent ) { super.onActivityResult( requestCode, resultCode, intent ); switch( requestCode ) { case MENU_TRACKLIST: if( resultCode == RESULT_OK ) { mTrackUri = intent.getData(); drawTrackingStatistics(); } break; case MENU_SHARE: ShareTrack.clearScreenBitmap(); break; default: Log.w( TAG, "Unknown activity result request code" ); } } /* * (non-Javadoc) * @see android.app.Activity#onCreateDialog(int) */ @Override protected Dialog onCreateDialog( int id ) { Dialog dialog = null; LayoutInflater factory = null; View view = null; Builder builder = null; switch( id ) { case DIALOG_GRAPHTYPE: builder = new AlertDialog.Builder( this ); factory = LayoutInflater.from( this ); view = factory.inflate( R.layout.graphtype, null ); builder.setTitle( R.string.dialog_graphtype_title ).setIcon( android.R.drawable.ic_dialog_alert ).setNegativeButton( R.string.btn_cancel, null ).setView( view ); dialog = builder.create(); return dialog; default: return super.onCreateDialog( id ); } } /* * (non-Javadoc) * @see android.app.Activity#onPrepareDialog(int, android.app.Dialog) */ @Override protected void onPrepareDialog( int id, Dialog dialog ) { switch( id ) { case DIALOG_GRAPHTYPE: Button speedtime = (Button) dialog.findViewById( R.id.graphtype_timespeed ); Button speeddistance = (Button) dialog.findViewById( R.id.graphtype_distancespeed ); Button altitudetime = (Button) dialog.findViewById( R.id.graphtype_timealtitude ); Button altitudedistance = (Button) dialog.findViewById( R.id.graphtype_distancealtitude ); speedtime.setOnClickListener( mGraphControlListener ); speeddistance.setOnClickListener( mGraphControlListener ); altitudetime.setOnClickListener( mGraphControlListener ); altitudedistance.setOnClickListener( mGraphControlListener ); default: break; } super.onPrepareDialog( id, dialog ); } private void drawTrackingStatistics() { calculating = true; StatisticsCalulator calculator = new StatisticsCalulator( this, mUnits, this ); calculator.execute(mTrackUri); } @Override public void finishedCalculations(StatisticsCalulator calculated) { mGraphTimeSpeed.setData ( mTrackUri, calculated ); mGraphDistanceSpeed.setData ( mTrackUri, calculated ); mGraphTimeAltitude.setData ( mTrackUri, calculated ); mGraphDistanceAltitude.setData( mTrackUri, calculated ); mViewFlipper.postInvalidate(); maxSpeedView.setText( calculated.getMaxSpeedText() ); mElapsedTimeView.setText( calculated.getDurationText() ); mAscensionView.setText( calculated.getAscensionText() ); overallavgSpeedView.setText( calculated.getOverallavgSpeedText() ); avgSpeedView.setText( calculated.getAvgSpeedText() ); distanceView.setText( calculated.getDistanceText() ); starttimeView.setText( Long.toString( calculated.getStarttime() ) ); endtimeView.setText( Long.toString( calculated.getEndtime() ) ); String titleFormat = getString( R.string.stat_title ); setTitle( String.format( titleFormat, calculated.getTracknameText() ) ); waypointsView.setText( calculated.getWaypointsText() ); calculating = false; } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions; import java.util.Calendar; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnDismissListener; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; /** * Empty Activity that pops up the dialog to name the track * * @version $Id$ * @author rene (c) Jul 27, 2010, Sogeti B.V. */ public class NameTrack extends Activity { private static final int DIALOG_TRACKNAME = 23; protected static final String TAG = "OGT.NameTrack"; private EditText mTrackNameView; private boolean paused; Uri mTrackUri; private final DialogInterface.OnClickListener mTrackNameDialogListener = new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog, int which ) { String trackName = null; switch( which ) { case DialogInterface.BUTTON_POSITIVE: trackName = mTrackNameView.getText().toString(); ContentValues values = new ContentValues(); values.put( Tracks.NAME, trackName ); getContentResolver().update( mTrackUri, values, null, null ); clearNotification(); break; case DialogInterface.BUTTON_NEUTRAL: startDelayNotification(); break; case DialogInterface.BUTTON_NEGATIVE: clearNotification(); break; default: Log.e( TAG, "Unknown option ending dialog:"+which ); break; } finish(); } }; private void clearNotification() { NotificationManager noticationManager = (NotificationManager) this.getSystemService( Context.NOTIFICATION_SERVICE );; noticationManager.cancel( R.layout.namedialog ); } private void startDelayNotification() { int resId = R.string.dialog_routename_title; int icon = R.drawable.ic_maps_indicator_current_position; CharSequence tickerText = getResources().getString( resId ); long when = System.currentTimeMillis(); Notification nameNotification = new Notification( icon, tickerText, when ); nameNotification.flags |= Notification.FLAG_AUTO_CANCEL; CharSequence contentTitle = getResources().getString( R.string.app_name ); CharSequence contentText = getResources().getString( resId ); Intent notificationIntent = new Intent( this, NameTrack.class ); notificationIntent.setData( mTrackUri ); PendingIntent contentIntent = PendingIntent.getActivity( this, 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK ); nameNotification.setLatestEventInfo( this, contentTitle, contentText, contentIntent ); NotificationManager noticationManager = (NotificationManager) this.getSystemService( Context.NOTIFICATION_SERVICE ); noticationManager.notify( R.layout.namedialog, nameNotification ); } @Override protected void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); this.setVisible( false ); paused = false; mTrackUri = this.getIntent().getData(); } @Override protected void onPause() { super.onPause(); paused = true; } /* * (non-Javadoc) * @see com.google.android.maps.MapActivity#onPause() */ @Override protected void onResume() { super.onResume(); if( mTrackUri != null ) { showDialog( DIALOG_TRACKNAME ); } else { Log.e(TAG, "Naming track without a track URI supplied." ); finish(); } } @Override protected Dialog onCreateDialog( int id ) { Dialog dialog = null; LayoutInflater factory = null; View view = null; Builder builder = null; switch (id) { case DIALOG_TRACKNAME: builder = new AlertDialog.Builder( this ); factory = LayoutInflater.from( this ); view = factory.inflate( R.layout.namedialog, null ); mTrackNameView = (EditText) view.findViewById( R.id.nameField ); builder .setTitle( R.string.dialog_routename_title ) .setMessage( R.string.dialog_routename_message ) .setIcon( android.R.drawable.ic_dialog_alert ) .setPositiveButton( R.string.btn_okay, mTrackNameDialogListener ) .setNeutralButton( R.string.btn_skip, mTrackNameDialogListener ) .setNegativeButton( R.string.btn_cancel, mTrackNameDialogListener ) .setView( view ); dialog = builder.create(); dialog.setOnDismissListener( new OnDismissListener() { @Override public void onDismiss( DialogInterface dialog ) { if( !paused ) { finish(); } } }); return dialog; default: return super.onCreateDialog( id ); } } @Override protected void onPrepareDialog( int id, Dialog dialog ) { switch (id) { case DIALOG_TRACKNAME: String trackName; Calendar c = Calendar.getInstance(); trackName = String.format( getString( R.string.dialog_routename_default ), c, c, c, c, c ); mTrackNameView.setText( trackName ); mTrackNameView.setSelection( 0, trackName.length() ); break; default: super.onPrepareDialog( id, dialog ); break; } } }
Java
package nl.sogeti.android.gpstracker.actions.utils; public interface StatisticsDelegate { void finishedCalculations(StatisticsCalulator calculated); }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.utils; import android.app.Activity; import android.net.Uri; /** * Interface to which a Activity / Context can conform to receive progress * updates from async tasks * * @version $Id:$ * @author rene (c) May 29, 2011, Sogeti B.V. */ public interface ProgressListener { void setIndeterminate(boolean indeterminate); /** * Signifies the start of background task, will be followed by setProgress(int) calls. */ void started(); /** * Set the progress on the scale of 0...10000 * * @param value * * @see Activity.setProgress * @see Window.PROGRESS_END */ void setProgress(int value); /** * Signifies end of background task and the location of the result * * @param result */ void finished(Uri result); void showError(String task, String errorMessage, Exception exception); }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.utils; import nl.sogeti.android.gpstracker.db.GPStracking.Segments; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.UnitsI18n; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.location.Location; import android.net.Uri; import android.os.AsyncTask; public class StatisticsCalulator extends AsyncTask<Uri, Void, Void> { @SuppressWarnings("unused") private static final String TAG = "OGT.StatisticsCalulator"; private Context mContext; private String overallavgSpeedText = "Unknown"; private String avgSpeedText = "Unknown"; private String maxSpeedText = "Unknown"; private String ascensionText = "Unknown"; private String minSpeedText = "Unknown"; private String tracknameText = "Unknown"; private String waypointsText = "Unknown"; private String distanceText = "Unknown"; private long mStarttime = -1; private long mEndtime = -1; private UnitsI18n mUnits; private double mMaxSpeed; private double mMaxAltitude; private double mMinAltitude; private double mAscension; private double mDistanceTraveled; private long mDuration; private double mAverageActiveSpeed; private StatisticsDelegate mDelegate; public StatisticsCalulator( Context ctx, UnitsI18n units, StatisticsDelegate delegate ) { mContext = ctx; mUnits = units; mDelegate = delegate; } private void updateCalculations( Uri trackUri ) { mStarttime = -1; mEndtime = -1; mMaxSpeed = 0; mAverageActiveSpeed = 0; mMaxAltitude = 0; mMinAltitude = 0; mAscension = 0; mDistanceTraveled = 0f; mDuration = 0; long duration = 1; double ascension = 0; ContentResolver resolver = mContext.getContentResolver(); Cursor waypointsCursor = null; try { waypointsCursor = resolver.query( Uri.withAppendedPath( trackUri, "waypoints" ), new String[] { "max (" + Waypoints.TABLE + "." + Waypoints.SPEED + ")" , "max (" + Waypoints.TABLE + "." + Waypoints.ALTITUDE + ")" , "min (" + Waypoints.TABLE + "." + Waypoints.ALTITUDE + ")" , "count(" + Waypoints.TABLE + "." + Waypoints._ID + ")" }, null, null, null ); if( waypointsCursor.moveToLast() ) { mMaxSpeed = waypointsCursor.getDouble( 0 ); mMaxAltitude = waypointsCursor.getDouble( 1 ); mMinAltitude = waypointsCursor.getDouble( 2 ); long nrWaypoints = waypointsCursor.getLong( 3 ); waypointsText = nrWaypoints + ""; } waypointsCursor.close(); waypointsCursor = resolver.query( Uri.withAppendedPath( trackUri, "waypoints" ), new String[] { "avg (" + Waypoints.TABLE + "." + Waypoints.SPEED + ")" }, Waypoints.TABLE + "." + Waypoints.SPEED +" > ?", new String[] { ""+Constants.MIN_STATISTICS_SPEED }, null ); if( waypointsCursor.moveToLast() ) { mAverageActiveSpeed = waypointsCursor.getDouble( 0 ); } } finally { if( waypointsCursor != null ) { waypointsCursor.close(); } } Cursor trackCursor = null; try { trackCursor = resolver.query( trackUri, new String[] { Tracks.NAME }, null, null, null ); if( trackCursor.moveToLast() ) { tracknameText = trackCursor.getString( 0 ); } } finally { if( trackCursor != null ) { trackCursor.close(); } } Cursor segments = null; Location lastLocation = null; Location lastAltitudeLocation = null; Location currentLocation = null; try { Uri segmentsUri = Uri.withAppendedPath( trackUri, "segments" ); segments = resolver.query( segmentsUri, new String[] { Segments._ID }, null, null, null ); if( segments.moveToFirst() ) { do { long segmentsId = segments.getLong( 0 ); Cursor waypoints = null; try { Uri waypointsUri = Uri.withAppendedPath( segmentsUri, segmentsId + "/waypoints" ); waypoints = resolver.query( waypointsUri, new String[] { Waypoints._ID, Waypoints.TIME, Waypoints.LONGITUDE, Waypoints.LATITUDE, Waypoints.ALTITUDE }, null, null, null ); if( waypoints.moveToFirst() ) { do { if( mStarttime < 0 ) { mStarttime = waypoints.getLong( 1 ); } currentLocation = new Location( this.getClass().getName() ); currentLocation.setTime( waypoints.getLong( 1 ) ); currentLocation.setLongitude( waypoints.getDouble( 2 ) ); currentLocation.setLatitude( waypoints.getDouble( 3 ) ); currentLocation.setAltitude( waypoints.getDouble( 4 ) ); // Do no include obvious wrong 0.0 lat 0.0 long, skip to next value in while-loop if( currentLocation.getLatitude() == 0.0d || currentLocation.getLongitude() == 0.0d ) { continue; } if( lastLocation != null ) { float travelPart = lastLocation.distanceTo( currentLocation ); long timePart = currentLocation.getTime() - lastLocation.getTime(); mDistanceTraveled += travelPart; duration += timePart; } if( currentLocation.hasAltitude() ) { if( lastAltitudeLocation != null ) { if( currentLocation.getTime() - lastAltitudeLocation.getTime() > 5*60*1000 ) // more then a 5m of climbing { if( currentLocation.getAltitude() > lastAltitudeLocation.getAltitude()+1 ) // more then 1m climb { ascension += currentLocation.getAltitude() - lastAltitudeLocation.getAltitude(); lastAltitudeLocation = currentLocation; } else { lastAltitudeLocation = currentLocation; } } } else { lastAltitudeLocation = currentLocation; } } lastLocation = currentLocation; mEndtime = lastLocation.getTime(); } while( waypoints.moveToNext() ); mDuration = mEndtime - mStarttime; } } finally { if( waypoints != null ) { waypoints.close(); } } lastLocation = null; } while( segments.moveToNext() ); } } finally { if( segments != null ) { segments.close(); } } double maxSpeed = mUnits.conversionFromMetersPerSecond( mMaxSpeed ); double overallavgSpeedfl = mUnits.conversionFromMeterAndMiliseconds( mDistanceTraveled, mDuration ); double avgSpeedfl = mUnits.conversionFromMeterAndMiliseconds( mDistanceTraveled, duration ); double traveled = mUnits.conversionFromMeter( mDistanceTraveled ); avgSpeedText = mUnits.formatSpeed( avgSpeedfl, true ); overallavgSpeedText = mUnits.formatSpeed( overallavgSpeedfl, true ); maxSpeedText = mUnits.formatSpeed( maxSpeed, true ); distanceText = String.format( "%.2f %s", traveled, mUnits.getDistanceUnit() ); ascensionText = String.format( "%.0f %s", ascension, mUnits.getHeightUnit() ); } /** * Get the overallavgSpeedText. * * @return Returns the overallavgSpeedText as a String. */ public String getOverallavgSpeedText() { return overallavgSpeedText; } /** * Get the avgSpeedText. * * @return Returns the avgSpeedText as a String. */ public String getAvgSpeedText() { return avgSpeedText; } /** * Get the maxSpeedText. * * @return Returns the maxSpeedText as a String. */ public String getMaxSpeedText() { return maxSpeedText; } /** * Get the minSpeedText. * * @return Returns the minSpeedText as a String. */ public String getMinSpeedText() { return minSpeedText; } /** * Get the tracknameText. * * @return Returns the tracknameText as a String. */ public String getTracknameText() { return tracknameText; } /** * Get the waypointsText. * * @return Returns the waypointsText as a String. */ public String getWaypointsText() { return waypointsText; } /** * Get the distanceText. * * @return Returns the distanceText as a String. */ public String getDistanceText() { return distanceText; } /** * Get the starttime. * * @return Returns the starttime as a long. */ public long getStarttime() { return mStarttime; } /** * Get the endtime. * * @return Returns the endtime as a long. */ public long getEndtime() { return mEndtime; } /** * Get the maximum speed. * * @return Returns the maxSpeeddb as m/s in a double. */ public double getMaxSpeed() { return mMaxSpeed; } /** * Get the min speed. * * @return Returns the average speed as m/s in a double. */ public double getAverageStatisicsSpeed() { return mAverageActiveSpeed; } /** * Get the maxAltitude. * * @return Returns the maxAltitude as a double. */ public double getMaxAltitude() { return mMaxAltitude; } /** * Get the minAltitude. * * @return Returns the minAltitude as a double. */ public double getMinAltitude() { return mMinAltitude; } /** * Get the total ascension in m. * * @return Returns the ascension as a double. */ public double getAscension() { return mAscension; } public CharSequence getAscensionText() { return ascensionText; } /** * Get the distanceTraveled. * * @return Returns the distanceTraveled as a float. */ public double getDistanceTraveled() { return mDistanceTraveled; } /** * Get the mUnits. * * @return Returns the mUnits as a UnitsI18n. */ public UnitsI18n getUnits() { return mUnits; } public String getDurationText() { long s = mDuration / 1000; String duration = String.format("%dh:%02dm:%02ds", s/3600, (s%3600)/60, (s%60)); return duration; } @Override protected Void doInBackground(Uri... params) { this.updateCalculations(params[0]); return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); if( mDelegate != null ) { mDelegate.finishedCalculations(this); } } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.utils; import java.text.DateFormat; import java.util.Date; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.db.GPStracking.Segments; import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.UnitsI18n; import android.content.ContentResolver; import android.content.Context; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.CornerPathEffect; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Typeface; import android.location.Location; import android.net.Uri; import android.util.AttributeSet; import android.view.View; /** * Calculate and draw graphs of track data * * @version $Id$ * @author rene (c) Mar 22, 2009, Sogeti B.V. */ public class GraphCanvas extends View { @SuppressWarnings("unused") private static final String TAG = "OGT.GraphCanvas"; public static final int TIMESPEEDGRAPH = 0; public static final int DISTANCESPEEDGRAPH = 1; public static final int TIMEALTITUDEGRAPH = 2; public static final int DISTANCEALTITUDEGRAPH = 3; private Uri mUri; private Bitmap mRenderBuffer; private Canvas mRenderCanvas; private Context mContext; private UnitsI18n mUnits; private int mGraphType = -1; private long mEndTime; private long mStartTime; private double mDistance; private int mHeight; private int mWidth; private int mMinAxis; private int mMaxAxis; private double mMinAlititude; private double mMaxAlititude; private double mHighestSpeedNumber; private double mDistanceDrawn; private long mStartTimeDrawn; private long mEndTimeDrawn; float density = Resources.getSystem().getDisplayMetrics().density; private Paint whiteText ; private Paint ltgreyMatrixDashed; private Paint greenGraphLine; private Paint dkgreyMatrixLine; private Paint whiteCenteredText; private Paint dkgrayLargeType; public GraphCanvas( Context context, AttributeSet attrs ) { this(context, attrs, 0); } public GraphCanvas( Context context, AttributeSet attrs, int defStyle ) { super(context, attrs, defStyle); mContext = context; whiteText = new Paint(); whiteText.setColor( Color.WHITE ); whiteText.setAntiAlias( true ); whiteText.setTextSize( (int)(density * 12) ); whiteCenteredText = new Paint(); whiteCenteredText.setColor( Color.WHITE ); whiteCenteredText.setAntiAlias( true ); whiteCenteredText.setTextAlign( Paint.Align.CENTER ); whiteCenteredText.setTextSize( (int)(density * 12) ); ltgreyMatrixDashed = new Paint(); ltgreyMatrixDashed.setColor( Color.LTGRAY ); ltgreyMatrixDashed.setStrokeWidth( 1 ); ltgreyMatrixDashed.setPathEffect( new DashPathEffect( new float[]{2,4}, 0 ) ); greenGraphLine = new Paint(); greenGraphLine.setPathEffect( new CornerPathEffect( 8 ) ); greenGraphLine.setStyle( Paint.Style.STROKE ); greenGraphLine.setStrokeWidth( 4 ); greenGraphLine.setAntiAlias( true ); greenGraphLine.setColor(Color.GREEN); dkgreyMatrixLine = new Paint(); dkgreyMatrixLine.setColor( Color.DKGRAY ); dkgreyMatrixLine.setStrokeWidth( 2 ); dkgrayLargeType = new Paint(); dkgrayLargeType.setColor( Color.LTGRAY ); dkgrayLargeType.setAntiAlias( true ); dkgrayLargeType.setTextAlign( Paint.Align.CENTER ); dkgrayLargeType.setTextSize( (int)(density * 21) ); dkgrayLargeType.setTypeface( Typeface.DEFAULT_BOLD ); } /** * Set the dataset for which to draw data. Also provide hints and helpers. * * @param uri * @param startTime * @param endTime * @param distance * @param minAlititude * @param maxAlititude * @param maxSpeed * @param units */ public void setData( Uri uri, StatisticsCalulator calc ) { boolean rerender = false; if( uri.equals( mUri ) ) { double distanceDrawnPercentage = mDistanceDrawn / mDistance; double duractionDrawnPercentage = (double)((1d+mEndTimeDrawn-mStartTimeDrawn) / (1d+mEndTime-mStartTime)); rerender = distanceDrawnPercentage < 0.99d || duractionDrawnPercentage < 0.99d; } else { if( mRenderBuffer == null && super.getWidth() > 0 && super.getHeight() > 0 ) { initRenderBuffer(super.getWidth(), super.getHeight()); } rerender = true; } mUri = uri; mUnits = calc.getUnits(); mMinAlititude = mUnits.conversionFromMeterToHeight( calc.getMinAltitude() ); mMaxAlititude = mUnits.conversionFromMeterToHeight( calc.getMaxAltitude() ); if( mUnits.isUnitFlipped() ) { mHighestSpeedNumber = 1.5 * mUnits.conversionFromMetersPerSecond( calc.getAverageStatisicsSpeed() ); } else { mHighestSpeedNumber = mUnits.conversionFromMetersPerSecond( calc.getMaxSpeed() ); } mStartTime = calc.getStarttime(); mEndTime = calc.getEndtime(); mDistance = calc.getDistanceTraveled(); if( rerender ) { renderGraph(); } } public synchronized void clearData() { mUri = null; mUnits = null; mRenderBuffer = null; } public void setType( int graphType) { if( mGraphType != graphType ) { mGraphType = graphType; renderGraph(); } } public int getType() { return mGraphType; } @Override protected synchronized void onSizeChanged( int w, int h, int oldw, int oldh ) { super.onSizeChanged( w, h, oldw, oldh ); initRenderBuffer(w, h); renderGraph(); } private void initRenderBuffer(int w, int h) { mRenderBuffer = Bitmap.createBitmap( w, h, Config.ARGB_8888 ); mRenderCanvas = new Canvas( mRenderBuffer ); } @Override protected synchronized void onDraw( Canvas canvas ) { super.onDraw(canvas); if( mRenderBuffer != null ) { canvas.drawBitmap( mRenderBuffer, 0, 0, null ); } } private synchronized void renderGraph() { if( mRenderBuffer != null && mUri != null ) { mRenderBuffer.eraseColor( Color.TRANSPARENT ); switch( mGraphType ) { case( TIMESPEEDGRAPH ): setupSpeedAxis(); drawGraphType(); drawTimeAxisGraphOnCanvas( new String[] { Waypoints.TIME, Waypoints.SPEED }, Constants.MIN_STATISTICS_SPEED ); drawSpeedsTexts(); drawTimeTexts(); break; case( DISTANCESPEEDGRAPH ): setupSpeedAxis(); drawGraphType(); drawDistanceAxisGraphOnCanvas( new String[] { Waypoints.LONGITUDE, Waypoints.LATITUDE, Waypoints.SPEED }, Constants.MIN_STATISTICS_SPEED ); drawSpeedsTexts(); drawDistanceTexts(); break; case( TIMEALTITUDEGRAPH ): setupAltitudeAxis(); drawGraphType(); drawTimeAxisGraphOnCanvas( new String[] { Waypoints.TIME, Waypoints.ALTITUDE }, -1000d ); drawAltitudesTexts(); drawTimeTexts(); break; case( DISTANCEALTITUDEGRAPH ): setupAltitudeAxis(); drawGraphType(); drawDistanceAxisGraphOnCanvas( new String[] { Waypoints.LONGITUDE, Waypoints.LATITUDE, Waypoints.ALTITUDE }, -1000d ); drawAltitudesTexts(); drawDistanceTexts(); break; default: break; } mDistanceDrawn = mDistance; mStartTimeDrawn = mStartTime; mEndTimeDrawn = mEndTime; } postInvalidate(); } /** * * @param params * @param minValue Minimum value of params[1] that will be drawn */ private void drawDistanceAxisGraphOnCanvas( String[] params, double minValue ) { ContentResolver resolver = mContext.getContentResolver(); Uri segmentsUri = Uri.withAppendedPath( mUri, "segments" ); Uri waypointsUri = null; Cursor segments = null; Cursor waypoints = null; double[][] values ; int[][] valueDepth; double distance = 1; try { segments = resolver.query( segmentsUri, new String[]{ Segments._ID }, null, null, null ); int segmentCount = segments.getCount(); values = new double[segmentCount][mWidth]; valueDepth = new int[segmentCount][mWidth]; if( segments.moveToFirst() ) { for(int segment=0;segment<segmentCount;segment++) { segments.moveToPosition( segment ); long segmentId = segments.getLong( 0 ); waypointsUri = Uri.withAppendedPath( segmentsUri, segmentId+"/waypoints" ); try { waypoints = resolver.query( waypointsUri, params, null, null, null ); if( waypoints.moveToFirst() ) { Location lastLocation = null; Location currentLocation = null; do { currentLocation = new Location( this.getClass().getName() ); currentLocation.setLongitude( waypoints.getDouble( 0 ) ); currentLocation.setLatitude( waypoints.getDouble( 1 ) ); // Do no include obvious wrong 0.0 lat 0.0 long, skip to next value in while-loop if( currentLocation.getLatitude() == 0.0d || currentLocation.getLongitude() == 0.0d ) { continue; } if( lastLocation != null ) { distance += lastLocation.distanceTo( currentLocation ); } lastLocation = currentLocation; double value = waypoints.getDouble( 2 ); if( value != 0 && value > minValue && segment < values.length ) { int x = (int) ((distance)*(mWidth-1) / mDistance); if( x > 0 && x < valueDepth[segment].length ) { valueDepth[segment][x]++; values[segment][x] = values[segment][x]+((value-values[segment][x])/valueDepth[segment][x]); } } } while( waypoints.moveToNext() ); } } finally { if( waypoints != null ) { waypoints.close(); } } } } } finally { if( segments != null ) { segments.close(); } } for( int segment=0;segment<values.length;segment++) { for( int x=0;x<values[segment].length;x++) { if( valueDepth[segment][x] > 0 ) { values[segment][x] = translateValue( values[segment][x] ); } } } drawGraph( values, valueDepth ); } private void drawTimeAxisGraphOnCanvas( String[] params, double minValue ) { ContentResolver resolver = mContext.getContentResolver(); Uri segmentsUri = Uri.withAppendedPath( mUri, "segments" ); Uri waypointsUri = null; Cursor segments = null; Cursor waypoints = null; long duration = 1+mEndTime - mStartTime; double[][] values ; int[][] valueDepth; try { segments = resolver.query( segmentsUri, new String[]{ Segments._ID }, null, null, null ); int segmentCount = segments.getCount(); values = new double[segmentCount][mWidth]; valueDepth = new int[segmentCount][mWidth]; if( segments.moveToFirst() ) { for(int segment=0;segment<segmentCount;segment++) { segments.moveToPosition( segment ); long segmentId = segments.getLong( 0 ); waypointsUri = Uri.withAppendedPath( segmentsUri, segmentId+"/waypoints" ); try { waypoints = resolver.query( waypointsUri, params, null, null, null ); if( waypoints.moveToFirst() ) { do { long time = waypoints.getLong( 0 ); double value = waypoints.getDouble( 1 ); if( value != 0 && value > minValue && segment < values.length ) { int x = (int) ((time-mStartTime)*(mWidth-1) / duration); if( x > 0 && x < valueDepth[segment].length ) { valueDepth[segment][x]++; values[segment][x] = values[segment][x]+((value-values[segment][x])/valueDepth[segment][x]); } } } while( waypoints.moveToNext() ); } } finally { if( waypoints != null ) { waypoints.close(); } } } } } finally { if( segments != null ) { segments.close(); } } for( int p=0;p<values.length;p++) { for( int x=0;x<values[p].length;x++) { if( valueDepth[p][x] > 0 ) { values[p][x] = translateValue( values[p][x] ); } } } drawGraph( values, valueDepth ); } private void setupAltitudeAxis() { mMinAxis = -4 + 4 * (int)(mMinAlititude / 4); mMaxAxis = 4 + 4 * (int)(mMaxAlititude / 4); mWidth = mRenderCanvas.getWidth()-5; mHeight = mRenderCanvas.getHeight()-10; } private void setupSpeedAxis() { mMinAxis = 0; mMaxAxis = 4 + 4 * (int)( mHighestSpeedNumber / 4); mWidth = mRenderCanvas.getWidth()-5; mHeight = mRenderCanvas.getHeight()-10; } private void drawAltitudesTexts() { mRenderCanvas.drawText( String.format( "%d %s", mMinAxis, mUnits.getHeightUnit() ) , 8, mHeight, whiteText ); mRenderCanvas.drawText( String.format( "%d %s", (mMaxAxis+mMinAxis)/2, mUnits.getHeightUnit() ) , 8, 5+mHeight/2, whiteText ); mRenderCanvas.drawText( String.format( "%d %s", mMaxAxis, mUnits.getHeightUnit() ), 8, 15, whiteText ); } private void drawSpeedsTexts() { mRenderCanvas.drawText( String.format( "%d %s", mMinAxis, mUnits.getSpeedUnit() ) , 8, mHeight, whiteText ); mRenderCanvas.drawText( String.format( "%d %s", (mMaxAxis+mMinAxis)/2, mUnits.getSpeedUnit() ) , 8, 3+mHeight/2, whiteText ); mRenderCanvas.drawText( String.format( "%d %s", mMaxAxis, mUnits.getSpeedUnit() ) , 8, 7+whiteText.getTextSize(), whiteText ); } private void drawGraphType() { //float density = Resources.getSystem().getDisplayMetrics().density; String text; switch( mGraphType ) { case( TIMESPEEDGRAPH ): text = mContext.getResources().getString( R.string.graphtype_timespeed ); break; case( DISTANCESPEEDGRAPH ): text = mContext.getResources().getString( R.string.graphtype_distancespeed ); break; case( TIMEALTITUDEGRAPH ): text = mContext.getResources().getString( R.string.graphtype_timealtitude ); break; case( DISTANCEALTITUDEGRAPH ): text = mContext.getResources().getString( R.string.graphtype_distancealtitude ); break; default: text = "UNKNOWN GRAPH TYPE"; break; } mRenderCanvas.drawText( text, 5+mWidth/2, 5+mHeight/8, dkgrayLargeType ); } private void drawTimeTexts() { DateFormat timeInstance = android.text.format.DateFormat.getTimeFormat(this.getContext().getApplicationContext()); String start = timeInstance.format( new Date( mStartTime ) ); String half = timeInstance.format( new Date( (mEndTime+mStartTime)/2 ) ); String end = timeInstance.format( new Date( mEndTime ) ); Path yAxis; yAxis = new Path(); yAxis.moveTo( 5, 5+mHeight/2 ); yAxis.lineTo( 5, 5 ); mRenderCanvas.drawTextOnPath( String.format( start ), yAxis, 0, whiteCenteredText.getTextSize(), whiteCenteredText ); yAxis = new Path(); yAxis.moveTo( 5+mWidth/2 , 5+mHeight/2 ); yAxis.lineTo( 5+mWidth/2 , 5 ); mRenderCanvas.drawTextOnPath( String.format( half ), yAxis, 0, -3, whiteCenteredText ); yAxis = new Path(); yAxis.moveTo( 5+mWidth-1 , 5+mHeight/2 ); yAxis.lineTo( 5+mWidth-1 , 5 ); mRenderCanvas.drawTextOnPath( String.format( end ), yAxis, 0, -3, whiteCenteredText ); } private void drawDistanceTexts() { String start = String.format( "%.0f %s", mUnits.conversionFromMeter(0), mUnits.getDistanceUnit() ) ; String half = String.format( "%.0f %s", mUnits.conversionFromMeter(mDistance)/2, mUnits.getDistanceUnit() ) ; String end = String.format( "%.0f %s", mUnits.conversionFromMeter(mDistance) , mUnits.getDistanceUnit() ) ; Path yAxis; yAxis = new Path(); yAxis.moveTo( 5, 5+mHeight/2 ); yAxis.lineTo( 5, 5 ); mRenderCanvas.drawTextOnPath( String.format( start ), yAxis, 0, whiteText.getTextSize(), whiteCenteredText ); yAxis = new Path(); yAxis.moveTo( 5+mWidth/2 , 5+mHeight/2 ); yAxis.lineTo( 5+mWidth/2 , 5 ); mRenderCanvas.drawTextOnPath( String.format( half ), yAxis, 0, -3, whiteCenteredText ); yAxis = new Path(); yAxis.moveTo( 5+mWidth-1 , 5+mHeight/2 ); yAxis.lineTo( 5+mWidth-1 , 5 ); mRenderCanvas.drawTextOnPath( String.format( end ), yAxis, 0, -3, whiteCenteredText ); } private double translateValue( double val ) { switch( mGraphType ) { case( TIMESPEEDGRAPH ): case( DISTANCESPEEDGRAPH ): val = mUnits.conversionFromMetersPerSecond( val ); break; case( TIMEALTITUDEGRAPH ): case( DISTANCEALTITUDEGRAPH ): val = mUnits.conversionFromMeterToHeight( val ); break; default: break; } return val; } private void drawGraph( double[][] values, int[][] valueDepth ) { // Matrix // Horizontals mRenderCanvas.drawLine( 5, 5 , 5+mWidth, 5 , ltgreyMatrixDashed ); // top mRenderCanvas.drawLine( 5, 5+mHeight/4 , 5+mWidth, 5+mHeight/4 , ltgreyMatrixDashed ); // 2nd mRenderCanvas.drawLine( 5, 5+mHeight/2 , 5+mWidth, 5+mHeight/2 , ltgreyMatrixDashed ); // middle mRenderCanvas.drawLine( 5, 5+mHeight/4*3, 5+mWidth, 5+mHeight/4*3, ltgreyMatrixDashed ); // 3rd // Verticals mRenderCanvas.drawLine( 5+mWidth/4 , 5, 5+mWidth/4 , 5+mHeight, ltgreyMatrixDashed ); // 2nd mRenderCanvas.drawLine( 5+mWidth/2 , 5, 5+mWidth/2 , 5+mHeight, ltgreyMatrixDashed ); // middle mRenderCanvas.drawLine( 5+mWidth/4*3, 5, 5+mWidth/4*3, 5+mHeight, ltgreyMatrixDashed ); // 3rd mRenderCanvas.drawLine( 5+mWidth-1 , 5, 5+mWidth-1 , 5+mHeight, ltgreyMatrixDashed ); // right // The line Path mPath; int emptyValues = 0; mPath = new Path(); for( int p=0;p<values.length;p++) { int start = 0; while( valueDepth[p][start] == 0 && start < values[p].length-1 ) { start++; } mPath.moveTo( (float)start+5, 5f+ (float) ( mHeight - ( ( values[p][start]-mMinAxis )*mHeight ) / ( mMaxAxis-mMinAxis ) ) ); for( int x=start;x<values[p].length;x++) { double y = mHeight - ( ( values[p][x]-mMinAxis )*mHeight ) / ( mMaxAxis-mMinAxis ) ; if( valueDepth[p][x] > 0 ) { if( emptyValues > mWidth/10 ) { mPath.moveTo( (float)x+5, (float) y+5 ); } else { mPath.lineTo( (float)x+5, (float) y+5 ); } emptyValues = 0; } else { emptyValues++; } } } mRenderCanvas.drawPath( mPath, greenGraphLine ); // Axis's mRenderCanvas.drawLine( 5, 5 , 5 , 5+mHeight, dkgreyMatrixLine ); mRenderCanvas.drawLine( 5, 5+mHeight, 5+mWidth, 5+mHeight, dkgreyMatrixLine ); } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.utils; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.util.Log; /** * Work around based on input from the comment section of * <a href="http://code.google.com/p/android/issues/detail?can=2&q=6191&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars&id=6191">Issue 6191</a> * * @version $Id$ * @author rene (c) May 8, 2010, Sogeti B.V. */ public class ViewFlipper extends android.widget.ViewFlipper { private static final String TAG = "OGT.ViewFlipper"; public ViewFlipper(Context context) { super( context ); } public ViewFlipper(Context context, AttributeSet attrs) { super( context, attrs ); } /** * On api level 7 unexpected exception occur during orientation switching. * These are java.lang.IllegalArgumentException: Receiver not registered: android.widget.ViewFlipper$id * exceptions. On level 7, 8 and 9 devices these are ignored. */ @Override protected void onDetachedFromWindow() { if( Build.VERSION.SDK_INT > 7 ) { try { super.onDetachedFromWindow(); } catch( IllegalArgumentException e ) { Log.w( TAG, "Android project issue 6191 workaround." ); /* Quick catch and continue on api level 7+, the Eclair 2.1 / 2.2 */ } finally { super.stopFlipping(); } } else { super.onDetachedFromWindow(); } } }
Java
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Jul 9, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.tasks; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.util.Constants; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.HttpClient; import org.apache.ogt.http.client.methods.HttpPost; import org.apache.ogt.http.entity.mime.MultipartEntity; import org.apache.ogt.http.entity.mime.content.FileBody; import org.apache.ogt.http.entity.mime.content.StringBody; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.util.EntityUtils; import android.content.Context; import android.net.Uri; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; /** * ???? * * @version $Id:$ * @author rene (c) Jul 9, 2011, Sogeti B.V. */ public class JogmapSharing extends GpxCreator { private static final String TAG = "OGT.JogmapSharing"; private String jogmapResponseText; public JogmapSharing(Context context, Uri trackUri, String chosenBaseFileName, boolean attachments, ProgressListener listener) { super(context, trackUri, chosenBaseFileName, attachments, listener); } @Override protected Uri doInBackground(Void... params) { Uri result = super.doInBackground(params); sendToJogmap(result); return result; } @Override protected void onPostExecute(Uri resultFilename) { super.onPostExecute(resultFilename); CharSequence text = mContext.getString(R.string.osm_success) + jogmapResponseText; Toast toast = Toast.makeText(mContext, text, Toast.LENGTH_LONG); toast.show(); } private void sendToJogmap(Uri fileUri) { String authCode = PreferenceManager.getDefaultSharedPreferences(mContext).getString(Constants.JOGRUNNER_AUTH, ""); File gpxFile = new File(fileUri.getEncodedPath()); HttpClient httpclient = new DefaultHttpClient(); URI jogmap = null; int statusCode = 0; HttpEntity responseEntity = null; try { jogmap = new URI(mContext.getString(R.string.jogmap_post_url)); HttpPost method = new HttpPost(jogmap); MultipartEntity entity = new MultipartEntity(); entity.addPart("id", new StringBody(authCode)); entity.addPart("mFile", new FileBody(gpxFile)); method.setEntity(entity); HttpResponse response = httpclient.execute(method); statusCode = response.getStatusLine().getStatusCode(); responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); jogmapResponseText = XmlCreator.convertStreamToString(stream); } catch (IOException e) { String text = mContext.getString(R.string.jogmap_failed) + e.getLocalizedMessage(); handleError(mContext.getString(R.string.jogmap_task), e, text); } catch (URISyntaxException e) { String text = mContext.getString(R.string.jogmap_failed) + e.getLocalizedMessage(); handleError(mContext.getString(R.string.jogmap_task), e, text); } finally { if (responseEntity != null) { try { EntityUtils.consume(responseEntity); } catch (IOException e) { Log.e(TAG, "Failed to close the content stream", e); } } } if (statusCode != 200) { Log.e(TAG, "Wrong status code " + statusCode); jogmapResponseText = mContext.getString(R.string.jogmap_failed) + jogmapResponseText; handleError(mContext.getString(R.string.jogmap_task), new HttpException("Unexpected status reported by Jogmap"), jogmapResponseText); } } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.tasks; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.nio.channels.FileChannel; import java.util.Date; import java.util.concurrent.CancellationException; import java.util.concurrent.Executor; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.db.GPStracking.Media; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints; import nl.sogeti.android.gpstracker.util.Constants; import org.xmlpull.v1.XmlSerializer; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Environment; import android.util.Log; import android.view.Window; /** * Async XML creation task Execute without parameters (Void) Update posted with * single Integer And result is a filename in a String * * @version $Id$ * @author rene (c) May 29, 2011, Sogeti B.V. */ public abstract class XmlCreator extends AsyncTask<Void, Integer, Uri> { private String TAG = "OGT.XmlCreator"; private String mExportDirectoryPath; private boolean mNeedsBundling; String mChosenName; private ProgressListener mProgressListener; protected Context mContext; protected Uri mTrackUri; String mFileName; private String mErrorText; private Exception mException; private String mTask; public ProgressAdmin mProgressAdmin; XmlCreator(Context context, Uri trackUri, String chosenFileName, ProgressListener listener) { mChosenName = chosenFileName; mContext = context; mTrackUri = trackUri; mProgressListener = listener; mProgressAdmin = new ProgressAdmin(); String trackName = extractCleanTrackName(); mFileName = cleanFilename(mChosenName, trackName); } public void executeOn(Executor executor) { if (Build.VERSION.SDK_INT >= 11) { executeOnExecutor(executor); } else { execute(); } } private String extractCleanTrackName() { Cursor trackCursor = null; ContentResolver resolver = mContext.getContentResolver(); String trackName = "Untitled"; try { trackCursor = resolver.query(mTrackUri, new String[] { Tracks.NAME }, null, null, null); if (trackCursor.moveToLast()) { trackName = cleanFilename(trackCursor.getString(0), trackName); } } finally { if (trackCursor != null) { trackCursor.close(); } } return trackName; } /** * Calculated the total progress sum expected from a export to file This is * the sum of the number of waypoints and media entries times 100. The whole * number is doubled when compression is needed. */ public void determineProgressGoal() { if (mProgressListener != null) { Uri allWaypointsUri = Uri.withAppendedPath(mTrackUri, "waypoints"); Uri allMediaUri = Uri.withAppendedPath(mTrackUri, "media"); Cursor cursor = null; ContentResolver resolver = mContext.getContentResolver(); try { cursor = resolver.query(allWaypointsUri, new String[] { "count(" + Waypoints.TABLE + "." + Waypoints._ID + ")" }, null, null, null); if (cursor.moveToLast()) { mProgressAdmin.setWaypointCount(cursor.getInt(0)); } cursor.close(); cursor = resolver.query(allMediaUri, new String[] { "count(" + Media.TABLE + "." + Media._ID + ")" }, null, null, null); if (cursor.moveToLast()) { mProgressAdmin.setMediaCount(cursor.getInt(0)); } cursor.close(); cursor = resolver.query(allMediaUri, new String[] { "count(" + Tracks._ID + ")" }, Media.URI + " LIKE ? and " + Media.URI + " NOT LIKE ?", new String[] { "file://%", "%txt" }, null); if (cursor.moveToLast()) { mProgressAdmin.setCompress( cursor.getInt(0) > 0 ); } } finally { if (cursor != null) { cursor.close(); } } } else { Log.w(TAG, "Exporting " + mTrackUri + " without progress!"); } } /** * Removes all non-word chars (\W) from the text * * @param fileName * @param defaultName * @return a string larger then 0 with either word chars remaining from the * input or the default provided */ public static String cleanFilename(String fileName, String defaultName) { if (fileName == null || "".equals(fileName)) { fileName = defaultName; } else { fileName = fileName.replaceAll("\\W", ""); fileName = (fileName.length() > 0) ? fileName : defaultName; } return fileName; } /** * Includes media into the export directory and returns the relative path of * the media * * @param inputFilePath * @return file path relative to the export dir * @throws IOException */ protected String includeMediaFile(String inputFilePath) throws IOException { mNeedsBundling = true; File source = new File(inputFilePath); File target = new File(mExportDirectoryPath + "/" + source.getName()); // Log.d( TAG, String.format( "Copy %s to %s", source, target ) ); if (source.exists()) { FileInputStream fileInputStream = new FileInputStream(source); FileChannel inChannel = fileInputStream.getChannel(); FileOutputStream fileOutputStream = new FileOutputStream(target); FileChannel outChannel = fileOutputStream.getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); if (fileInputStream != null) fileInputStream.close(); if (fileOutputStream != null) fileOutputStream.close(); } } else { Log.w( TAG, "Failed to add file to new XML export. Missing: "+inputFilePath ); } mProgressAdmin.addMediaProgress(); return target.getName(); } /** * Just to start failing early * * @throws IOException */ protected void verifySdCardAvailibility() throws IOException { String state = Environment.getExternalStorageState(); if (!Environment.MEDIA_MOUNTED.equals(state)) { throw new IOException("The ExternalStorage is not mounted, unable to export files for sharing."); } } /** * Create a zip of the export directory based on the given filename * * @param fileName The directory to be replaced by a zipped file of the same * name * @param extension * @return full path of the build zip file * @throws IOException */ protected String bundlingMediaAndXml(String fileName, String extension) throws IOException { String zipFilePath; if (fileName.endsWith(".zip") || fileName.endsWith(extension)) { zipFilePath = Constants.getSdCardDirectory(mContext) + fileName; } else { zipFilePath = Constants.getSdCardDirectory(mContext) + fileName + extension; } String[] filenames = new File(mExportDirectoryPath).list(); byte[] buf = new byte[1024]; ZipOutputStream zos = null; try { zos = new ZipOutputStream(new FileOutputStream(zipFilePath)); for (int i = 0; i < filenames.length; i++) { String entryFilePath = mExportDirectoryPath + "/" + filenames[i]; FileInputStream in = new FileInputStream(entryFilePath); zos.putNextEntry(new ZipEntry(filenames[i])); int len; while ((len = in.read(buf)) >= 0) { zos.write(buf, 0, len); } zos.closeEntry(); in.close(); mProgressAdmin.addCompressProgress(); } } finally { if (zos != null) { zos.close(); } } deleteRecursive(new File(mExportDirectoryPath)); return zipFilePath; } public static boolean deleteRecursive(File file) { if (file.isDirectory()) { String[] children = file.list(); for (int i = 0; i < children.length; i++) { boolean success = deleteRecursive(new File(file, children[i])); if (!success) { return false; } } } return file.delete(); } public void setExportDirectoryPath(String exportDirectoryPath) { this.mExportDirectoryPath = exportDirectoryPath; } public String getExportDirectoryPath() { return mExportDirectoryPath; } public void quickTag(XmlSerializer serializer, String ns, String tag, String content) throws IllegalArgumentException, IllegalStateException, IOException { if( tag == null) { tag = ""; } if( content == null) { content = ""; } serializer.text("\n"); serializer.startTag(ns, tag); serializer.text(content); serializer.endTag(ns, tag); } public boolean needsBundling() { return mNeedsBundling; } public static String convertStreamToString(InputStream is) throws IOException { String result = ""; /* * To convert the InputStream to String we use the Reader.read(char[] * buffer) method. We iterate until the Reader return -1 which means * there's no more data to read. We use the StringWriter class to produce * the string. */ if (is != null) { Writer writer = new StringWriter(); char[] buffer = new char[8192]; try { Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { is.close(); } result = writer.toString(); } return result; } public static InputStream convertStreamToLoggedStream(String tag, InputStream is) throws IOException { String result = ""; /* * To convert the InputStream to String we use the Reader.read(char[] * buffer) method. We iterate until the Reader return -1 which means * there's no more data to read. We use the StringWriter class to produce * the string. */ if (is != null) { Writer writer = new StringWriter(); char[] buffer = new char[8192]; try { Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { is.close(); } result = writer.toString(); } InputStream in = new ByteArrayInputStream(result.getBytes("UTF-8")); return in; } protected abstract String getContentType(); protected void handleError(String task, Exception e, String text) { Log.e(TAG, "Unable to save ", e); mTask = task; mException = e; mErrorText = text; cancel(false); throw new CancellationException(text); } @Override protected void onPreExecute() { if(mProgressListener!= null) { mProgressListener.started(); } } @Override protected void onProgressUpdate(Integer... progress) { if(mProgressListener!= null) { mProgressListener.setProgress(mProgressAdmin.getProgress()); } } @Override protected void onPostExecute(Uri resultFilename) { if(mProgressListener!= null) { mProgressListener.finished(resultFilename); } } @Override protected void onCancelled() { if(mProgressListener!= null) { mProgressListener.finished(null); mProgressListener.showError(mTask, mErrorText, mException); } } public class ProgressAdmin { long lastUpdate; private boolean compressCount; private boolean compressProgress; private boolean uploadCount; private boolean uploadProgress; private int mediaCount; private int mediaProgress; private int waypointCount; private int waypointProgress; private long photoUploadCount ; private long photoUploadProgress ; public void addMediaProgress() { mediaProgress ++; } public void addCompressProgress() { compressProgress = true; } public void addUploadProgress() { uploadProgress = true; } public void addPhotoUploadProgress(long length) { photoUploadProgress += length; } /** * Get the progress on scale 0 ... Window.PROGRESS_END * * @return Returns the progress as a int. */ public int getProgress() { int blocks = 0; if( waypointCount > 0 ){ blocks++; } if( mediaCount > 0 ){ blocks++; } if( compressCount ){ blocks++; } if( uploadCount ){ blocks++; } if( photoUploadCount > 0 ){ blocks++; } int progress; if( blocks > 0 ) { int blockSize = Window.PROGRESS_END / blocks; progress = waypointCount > 0 ? blockSize * waypointProgress / waypointCount : 0; progress += mediaCount > 0 ? blockSize * mediaProgress / mediaCount : 0; progress += compressProgress ? blockSize : 0; progress += uploadProgress ? blockSize : 0; progress += photoUploadCount > 0 ? blockSize * photoUploadProgress / photoUploadCount : 0; } else { progress = 0; } //Log.d( TAG, "Progress updated to "+progress); return progress; } public void setWaypointCount(int waypoint) { waypointCount = waypoint; considerPublishProgress(); } public void setMediaCount(int media) { mediaCount = media; considerPublishProgress(); } public void setCompress( boolean compress) { compressCount = compress; considerPublishProgress(); } public void setUpload( boolean upload) { uploadCount = upload; considerPublishProgress(); } public void setPhotoUpload(long length) { photoUploadCount += length; considerPublishProgress(); } public void addWaypointProgress(int i) { waypointProgress += i; considerPublishProgress(); } public void considerPublishProgress() { long now = new Date().getTime(); if( now - lastUpdate > 1000 ) { lastUpdate = now; publishProgress(); } } } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.tasks; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.db.GPStracking; import nl.sogeti.android.gpstracker.db.GPStracking.Media; import nl.sogeti.android.gpstracker.db.GPStracking.Segments; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints; import nl.sogeti.android.gpstracker.util.Constants; import org.xmlpull.v1.XmlSerializer; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.provider.MediaStore.MediaColumns; import android.util.Log; import android.util.Xml; /** * Create a GPX version of a stored track * * @version $Id$ * @author rene (c) Mar 22, 2009, Sogeti B.V. */ public class GpxCreator extends XmlCreator { public static final String NS_SCHEMA = "http://www.w3.org/2001/XMLSchema-instance"; public static final String NS_GPX_11 = "http://www.topografix.com/GPX/1/1"; public static final String NS_GPX_10 = "http://www.topografix.com/GPX/1/0"; public static final String NS_OGT_10 = "http://gpstracker.android.sogeti.nl/GPX/1/0"; public static final SimpleDateFormat ZULU_DATE_FORMATER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); static { TimeZone utc = TimeZone.getTimeZone("UTC"); ZULU_DATE_FORMATER.setTimeZone(utc); // ZULU_DATE_FORMAT format ends with Z for UTC so make that true } private String TAG = "OGT.GpxCreator"; private boolean includeAttachments; protected String mName; public GpxCreator(Context context, Uri trackUri, String chosenBaseFileName, boolean attachments, ProgressListener listener) { super(context, trackUri, chosenBaseFileName, listener); includeAttachments = attachments; } @Override protected Uri doInBackground(Void... params) { determineProgressGoal(); Uri resultFilename = exportGpx(); return resultFilename; } protected Uri exportGpx() { String xmlFilePath; if (mFileName.endsWith(".gpx") || mFileName.endsWith(".xml")) { setExportDirectoryPath(Constants.getSdCardDirectory(mContext) + mFileName.substring(0, mFileName.length() - 4)); xmlFilePath = getExportDirectoryPath() + "/" + mFileName; } else { setExportDirectoryPath(Constants.getSdCardDirectory(mContext) + mFileName); xmlFilePath = getExportDirectoryPath() + "/" + mFileName + ".gpx"; } new File(getExportDirectoryPath()).mkdirs(); String resultFilename = null; FileOutputStream fos = null; BufferedOutputStream buf = null; try { verifySdCardAvailibility(); XmlSerializer serializer = Xml.newSerializer(); File xmlFile = new File(xmlFilePath); fos = new FileOutputStream(xmlFile); buf = new BufferedOutputStream(fos, 8 * 8192); serializer.setOutput(buf, "UTF-8"); serializeTrack(mTrackUri, serializer); buf.close(); buf = null; fos.close(); fos = null; if (needsBundling()) { resultFilename = bundlingMediaAndXml(xmlFile.getParentFile().getName(), ".zip"); } else { File finalFile = new File(Constants.getSdCardDirectory(mContext) + xmlFile.getName()); xmlFile.renameTo(finalFile); resultFilename = finalFile.getAbsolutePath(); XmlCreator.deleteRecursive(xmlFile.getParentFile()); } mFileName = new File(resultFilename).getName(); } catch (FileNotFoundException e) { String text = mContext.getString(R.string.ticker_failed) + " \"" + xmlFilePath + "\" " + mContext.getString(R.string.error_filenotfound); handleError(mContext.getString(R.string.taskerror_gpx_write), e, text); } catch (IllegalArgumentException e) { String text = mContext.getString(R.string.ticker_failed) + " \"" + xmlFilePath + "\" " + mContext.getString(R.string.error_filename); handleError(mContext.getString(R.string.taskerror_gpx_write), e, text); } catch (IllegalStateException e) { String text = mContext.getString(R.string.ticker_failed) + " \"" + xmlFilePath + "\" " + mContext.getString(R.string.error_buildxml); handleError(mContext.getString(R.string.taskerror_gpx_write), e, text); } catch (IOException e) { String text = mContext.getString(R.string.ticker_failed) + " \"" + xmlFilePath + "\" " + mContext.getString(R.string.error_writesdcard); handleError(mContext.getString(R.string.taskerror_gpx_write), e, text); } finally { if (buf != null) { try { buf.close(); } catch (IOException e) { Log.e(TAG, "Failed to close buf after completion, ignoring.", e); } } if (fos != null) { try { fos.close(); } catch (IOException e) { Log.e(TAG, "Failed to close fos after completion, ignoring.", e); } } } return Uri.fromFile(new File(resultFilename)); } private void serializeTrack(Uri trackUri, XmlSerializer serializer) throws IllegalArgumentException, IllegalStateException, IOException { if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } serializer.startDocument("UTF-8", true); serializer.setPrefix("xsi", NS_SCHEMA); serializer.setPrefix("gpx10", NS_GPX_10); serializer.setPrefix("ogt10", NS_OGT_10); serializer.text("\n"); serializer.startTag("", "gpx"); serializer.attribute(null, "version", "1.1"); serializer.attribute(null, "creator", "nl.sogeti.android.gpstracker"); serializer.attribute(NS_SCHEMA, "schemaLocation", NS_GPX_11 + " http://www.topografix.com/gpx/1/1/gpx.xsd"); serializer.attribute(null, "xmlns", NS_GPX_11); // <metadata/> Big header of the track serializeTrackHeader(mContext, serializer, trackUri); // <wpt/> [0...] Waypoints if (includeAttachments) { serializeWaypoints(mContext, serializer, Uri.withAppendedPath(trackUri, "/media")); } // <trk/> [0...] Track serializer.text("\n"); serializer.startTag("", "trk"); serializer.text("\n"); serializer.startTag("", "name"); serializer.text(mName); serializer.endTag("", "name"); // The list of segments in the track serializeSegments(serializer, Uri.withAppendedPath(trackUri, "segments")); serializer.text("\n"); serializer.endTag("", "trk"); serializer.text("\n"); serializer.endTag("", "gpx"); serializer.endDocument(); } private void serializeTrackHeader(Context context, XmlSerializer serializer, Uri trackUri) throws IOException { if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } ContentResolver resolver = context.getContentResolver(); Cursor trackCursor = null; String databaseName = null; try { trackCursor = resolver.query(trackUri, new String[] { Tracks._ID, Tracks.NAME, Tracks.CREATION_TIME }, null, null, null); if (trackCursor.moveToFirst()) { databaseName = trackCursor.getString(1); serializer.text("\n"); serializer.startTag("", "metadata"); serializer.text("\n"); serializer.startTag("", "time"); Date time = new Date(trackCursor.getLong(2)); synchronized (ZULU_DATE_FORMATER) { serializer.text(ZULU_DATE_FORMATER.format(time)); } serializer.endTag("", "time"); serializer.text("\n"); serializer.endTag("", "metadata"); } } finally { if (trackCursor != null) { trackCursor.close(); } } if (mName == null) { mName = "Untitled"; } if (databaseName != null && !databaseName.equals("")) { mName = databaseName; } if (mChosenName != null && !mChosenName.equals("")) { mName = mChosenName; } } private void serializeSegments(XmlSerializer serializer, Uri segments) throws IOException { if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } Cursor segmentCursor = null; ContentResolver resolver = mContext.getContentResolver(); try { segmentCursor = resolver.query(segments, new String[] { Segments._ID }, null, null, null); if (segmentCursor.moveToFirst()) { do { Uri waypoints = Uri.withAppendedPath(segments, segmentCursor.getLong(0) + "/waypoints"); serializer.text("\n"); serializer.startTag("", "trkseg"); serializeTrackPoints(serializer, waypoints); serializer.text("\n"); serializer.endTag("", "trkseg"); } while (segmentCursor.moveToNext()); } } finally { if (segmentCursor != null) { segmentCursor.close(); } } } private void serializeTrackPoints(XmlSerializer serializer, Uri waypoints) throws IOException { if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } Cursor waypointsCursor = null; ContentResolver resolver = mContext.getContentResolver(); try { waypointsCursor = resolver.query(waypoints, new String[] { Waypoints.LONGITUDE, Waypoints.LATITUDE, Waypoints.TIME, Waypoints.ALTITUDE, Waypoints._ID, Waypoints.SPEED, Waypoints.ACCURACY, Waypoints.BEARING }, null, null, null); if (waypointsCursor.moveToFirst()) { do { mProgressAdmin.addWaypointProgress(1); serializer.text("\n"); serializer.startTag("", "trkpt"); serializer.attribute(null, "lat", Double.toString(waypointsCursor.getDouble(1))); serializer.attribute(null, "lon", Double.toString(waypointsCursor.getDouble(0))); serializer.text("\n"); serializer.startTag("", "ele"); serializer.text(Double.toString(waypointsCursor.getDouble(3))); serializer.endTag("", "ele"); serializer.text("\n"); serializer.startTag("", "time"); Date time = new Date(waypointsCursor.getLong(2)); synchronized (ZULU_DATE_FORMATER) { serializer.text(ZULU_DATE_FORMATER.format(time)); } serializer.endTag("", "time"); serializer.text("\n"); serializer.startTag("", "extensions"); double speed = waypointsCursor.getDouble(5); double accuracy = waypointsCursor.getDouble(6); double bearing = waypointsCursor.getDouble(7); if (speed > 0.0) { quickTag(serializer, NS_GPX_10, "speed", Double.toString(speed)); } if (accuracy > 0.0) { quickTag(serializer, NS_OGT_10, "accuracy", Double.toString(accuracy)); } if (bearing != 0.0) { quickTag(serializer, NS_GPX_10, "course", Double.toString(bearing)); } serializer.endTag("", "extensions"); serializer.text("\n"); serializer.endTag("", "trkpt"); } while (waypointsCursor.moveToNext()); } } finally { if (waypointsCursor != null) { waypointsCursor.close(); } } } private void serializeWaypoints(Context context, XmlSerializer serializer, Uri media) throws IOException { if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } Cursor mediaCursor = null; Cursor waypointCursor = null; BufferedReader buf = null; ContentResolver resolver = context.getContentResolver(); try { mediaCursor = resolver.query(media, new String[] { Media.URI, Media.TRACK, Media.SEGMENT, Media.WAYPOINT }, null, null, null); if (mediaCursor.moveToFirst()) { do { Uri waypointUri = Waypoints.buildUri(mediaCursor.getLong(1), mediaCursor.getLong(2), mediaCursor.getLong(3)); waypointCursor = resolver.query(waypointUri, new String[] { Waypoints.LATITUDE, Waypoints.LONGITUDE, Waypoints.ALTITUDE, Waypoints.TIME }, null, null, null); serializer.text("\n"); serializer.startTag("", "wpt"); if (waypointCursor != null && waypointCursor.moveToFirst()) { serializer.attribute(null, "lat", Double.toString(waypointCursor.getDouble(0))); serializer.attribute(null, "lon", Double.toString(waypointCursor.getDouble(1))); serializer.text("\n"); serializer.startTag("", "ele"); serializer.text(Double.toString(waypointCursor.getDouble(2))); serializer.endTag("", "ele"); serializer.text("\n"); serializer.startTag("", "time"); Date time = new Date(waypointCursor.getLong(3)); synchronized (ZULU_DATE_FORMATER) { serializer.text(ZULU_DATE_FORMATER.format(time)); } serializer.endTag("", "time"); } if (waypointCursor != null) { waypointCursor.close(); waypointCursor = null; } Uri mediaUri = Uri.parse(mediaCursor.getString(0)); if (mediaUri.getScheme().equals("file")) { if (mediaUri.getLastPathSegment().endsWith("3gp")) { String fileName = includeMediaFile(mediaUri.getLastPathSegment()); quickTag(serializer, "", "name", fileName); serializer.startTag("", "link"); serializer.attribute(null, "href", fileName); quickTag(serializer, "", "text", fileName); serializer.endTag("", "link"); } else if (mediaUri.getLastPathSegment().endsWith("jpg")) { String mediaPathPrefix = Constants.getSdCardDirectory(mContext); String fileName = includeMediaFile(mediaPathPrefix + mediaUri.getLastPathSegment()); quickTag(serializer, "", "name", fileName); serializer.startTag("", "link"); serializer.attribute(null, "href", fileName); quickTag(serializer, "", "text", fileName); serializer.endTag("", "link"); } else if (mediaUri.getLastPathSegment().endsWith("txt")) { quickTag(serializer, "", "name", mediaUri.getLastPathSegment()); serializer.startTag("", "desc"); if (buf != null) { buf.close(); } buf = new BufferedReader(new FileReader(mediaUri.getEncodedPath())); String line; while ((line = buf.readLine()) != null) { serializer.text(line); serializer.text("\n"); } serializer.endTag("", "desc"); } } else if (mediaUri.getScheme().equals("content")) { if ((GPStracking.AUTHORITY + ".string").equals(mediaUri.getAuthority())) { quickTag(serializer, "", "name", mediaUri.getLastPathSegment()); } else if (mediaUri.getAuthority().equals("media")) { Cursor mediaItemCursor = null; try { mediaItemCursor = resolver.query(mediaUri, new String[] { MediaColumns.DATA, MediaColumns.DISPLAY_NAME }, null, null, null); if (mediaItemCursor.moveToFirst()) { String fileName = includeMediaFile(mediaItemCursor.getString(0)); quickTag(serializer, "", "name", fileName); serializer.startTag("", "link"); serializer.attribute(null, "href", fileName); quickTag(serializer, "", "text", mediaItemCursor.getString(1)); serializer.endTag("", "link"); } } finally { if (mediaItemCursor != null) { mediaItemCursor.close(); } } } } serializer.text("\n"); serializer.endTag("", "wpt"); } while (mediaCursor.moveToNext()); } } finally { if (mediaCursor != null) { mediaCursor.close(); } if (waypointCursor != null) { waypointCursor.close(); } if (buf != null) buf.close(); } } @Override protected String getContentType() { return needsBundling() ? "application/zip" : "text/xml"; } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.tasks; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import java.util.Vector; import java.util.concurrent.CancellationException; import java.util.concurrent.Executor; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints; import nl.sogeti.android.gpstracker.util.ProgressFilterInputStream; import nl.sogeti.android.gpstracker.util.UnicodeReader; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.util.Log; import android.view.Window; public class GpxParser extends AsyncTask<Uri, Void, Uri> { private static final String LATITUDE_ATRIBUTE = "lat"; private static final String LONGITUDE_ATTRIBUTE = "lon"; private static final String TRACK_ELEMENT = "trkpt"; private static final String SEGMENT_ELEMENT = "trkseg"; private static final String NAME_ELEMENT = "name"; private static final String TIME_ELEMENT = "time"; private static final String ELEVATION_ELEMENT = "ele"; private static final String COURSE_ELEMENT = "course"; private static final String ACCURACY_ELEMENT = "accuracy"; private static final String SPEED_ELEMENT = "speed"; public static final SimpleDateFormat ZULU_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); public static final SimpleDateFormat ZULU_DATE_FORMAT_MS = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); public static final SimpleDateFormat ZULU_DATE_FORMAT_BC = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss 'UTC'"); protected static final int DEFAULT_UNKNOWN_FILESIZE = 1024 * 1024 * 10; private static final String TAG = "OGT.GpxParser"; static { TimeZone utc = TimeZone.getTimeZone("UTC"); ZULU_DATE_FORMAT.setTimeZone(utc); // ZULU_DATE_FORMAT format ends with Z for UTC so make that true ZULU_DATE_FORMAT_MS.setTimeZone(utc); } private ContentResolver mContentResolver; protected String mErrorDialogMessage; protected Exception mErrorDialogException; protected Context mContext; private ProgressListener mProgressListener; protected ProgressAdmin mProgressAdmin; public GpxParser(Context context, ProgressListener progressListener) { mContext = context; mProgressListener = progressListener; mContentResolver = mContext.getContentResolver(); } public void executeOn(Executor executor) { if (Build.VERSION.SDK_INT >= 11) { executeOnExecutor(executor); } else { execute(); } } public void determineProgressGoal(Uri importFileUri) { mProgressAdmin = new ProgressAdmin(); mProgressAdmin.setContentLength(DEFAULT_UNKNOWN_FILESIZE); if (importFileUri != null && importFileUri.getScheme().equals("file")) { File file = new File(importFileUri.getPath()); mProgressAdmin.setContentLength(file.length()); } } public Uri importUri(Uri importFileUri) { Uri result = null; String trackName = null; InputStream fis = null; if (importFileUri.getScheme().equals("file")) { trackName = importFileUri.getLastPathSegment(); } try { fis = mContentResolver.openInputStream(importFileUri); } catch (IOException e) { handleError(e, mContext.getString(R.string.error_importgpx_io)); } result = importTrack( fis, trackName); return result; } /** * Read a stream containing GPX XML into the OGT content provider * * @param fis opened stream the read from, will be closed after this call * @param trackName * @return */ public Uri importTrack( InputStream fis, String trackName ) { Uri trackUri = null; int eventType; ContentValues lastPosition = null; Vector<ContentValues> bulk = new Vector<ContentValues>(); boolean speed = false; boolean accuracy = false; boolean bearing = false; boolean elevation = false; boolean name = false; boolean time = false; Long importDate = Long.valueOf(new Date().getTime()); try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xmlParser = factory.newPullParser(); ProgressFilterInputStream pfis = new ProgressFilterInputStream(fis, mProgressAdmin); BufferedInputStream bis = new BufferedInputStream(pfis); UnicodeReader ur = new UnicodeReader(bis, "UTF-8"); xmlParser.setInput(ur); eventType = xmlParser.getEventType(); String attributeName; Uri segmentUri = null; while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { if (xmlParser.getName().equals(NAME_ELEMENT)) { name = true; } else { ContentValues trackContent = new ContentValues(); trackContent.put(Tracks.NAME, trackName); if (xmlParser.getName().equals("trk") && trackUri == null) { trackUri = startTrack(trackContent); } else if (xmlParser.getName().equals(SEGMENT_ELEMENT)) { segmentUri = startSegment(trackUri); } else if (xmlParser.getName().equals(TRACK_ELEMENT)) { lastPosition = new ContentValues(); for (int i = 0; i < 2; i++) { attributeName = xmlParser.getAttributeName(i); if (attributeName.equals(LATITUDE_ATRIBUTE)) { lastPosition.put(Waypoints.LATITUDE, Double.valueOf(xmlParser.getAttributeValue(i))); } else if (attributeName.equals(LONGITUDE_ATTRIBUTE)) { lastPosition.put(Waypoints.LONGITUDE, Double.valueOf(xmlParser.getAttributeValue(i))); } } } else if (xmlParser.getName().equals(SPEED_ELEMENT)) { speed = true; } else if (xmlParser.getName().equals(ACCURACY_ELEMENT)) { accuracy = true; } else if (xmlParser.getName().equals(COURSE_ELEMENT)) { bearing = true; } else if (xmlParser.getName().equals(ELEVATION_ELEMENT)) { elevation = true; } else if (xmlParser.getName().equals(TIME_ELEMENT)) { time = true; } } } else if (eventType == XmlPullParser.END_TAG) { if (xmlParser.getName().equals(NAME_ELEMENT)) { name = false; } else if (xmlParser.getName().equals(SPEED_ELEMENT)) { speed = false; } else if (xmlParser.getName().equals(ACCURACY_ELEMENT)) { accuracy = false; } else if (xmlParser.getName().equals(COURSE_ELEMENT)) { bearing = false; } else if (xmlParser.getName().equals(ELEVATION_ELEMENT)) { elevation = false; } else if (xmlParser.getName().equals(TIME_ELEMENT)) { time = false; } else if (xmlParser.getName().equals(SEGMENT_ELEMENT)) { if (segmentUri == null) { segmentUri = startSegment( trackUri ); } mContentResolver.bulkInsert(Uri.withAppendedPath(segmentUri, "waypoints"), bulk.toArray(new ContentValues[bulk.size()])); bulk.clear(); } else if (xmlParser.getName().equals(TRACK_ELEMENT)) { if (!lastPosition.containsKey(Waypoints.TIME)) { lastPosition.put(Waypoints.TIME, importDate); } if (!lastPosition.containsKey(Waypoints.SPEED)) { lastPosition.put(Waypoints.SPEED, 0); } bulk.add(lastPosition); lastPosition = null; } } else if (eventType == XmlPullParser.TEXT) { String text = xmlParser.getText(); if (name) { ContentValues nameValues = new ContentValues(); nameValues.put(Tracks.NAME, text); if (trackUri == null) { trackUri = startTrack(new ContentValues()); } mContentResolver.update(trackUri, nameValues, null, null); } else if (lastPosition != null && speed) { lastPosition.put(Waypoints.SPEED, Double.parseDouble(text)); } else if (lastPosition != null && accuracy) { lastPosition.put(Waypoints.ACCURACY, Double.parseDouble(text)); } else if (lastPosition != null && bearing) { lastPosition.put(Waypoints.BEARING, Double.parseDouble(text)); } else if (lastPosition != null && elevation) { lastPosition.put(Waypoints.ALTITUDE, Double.parseDouble(text)); } else if (lastPosition != null && time) { lastPosition.put(Waypoints.TIME, parseXmlDateTime(text)); } } eventType = xmlParser.next(); } } catch (XmlPullParserException e) { handleError(e, mContext.getString(R.string.error_importgpx_xml)); } catch (IOException e) { handleError(e, mContext.getString(R.string.error_importgpx_io)); } finally { try { fis.close(); } catch (IOException e) { Log.w( TAG, "Failed closing inputstream"); } } return trackUri; } private Uri startSegment(Uri trackUri) { if (trackUri == null) { trackUri = startTrack(new ContentValues()); } return mContentResolver.insert(Uri.withAppendedPath(trackUri, "segments"), new ContentValues()); } private Uri startTrack(ContentValues trackContent) { return mContentResolver.insert(Tracks.CONTENT_URI, trackContent); } public static Long parseXmlDateTime(String text) { Long dateTime = 0L; try { if(text==null) { throw new ParseException("Unable to parse dateTime "+text+" of length ", 0); } int length = text.length(); switch (length) { case 20: synchronized (ZULU_DATE_FORMAT) { dateTime = Long.valueOf(ZULU_DATE_FORMAT.parse(text).getTime()); } break; case 23: synchronized (ZULU_DATE_FORMAT_BC) { dateTime = Long.valueOf(ZULU_DATE_FORMAT_BC.parse(text).getTime()); } break; case 24: synchronized (ZULU_DATE_FORMAT_MS) { dateTime = Long.valueOf(ZULU_DATE_FORMAT_MS.parse(text).getTime()); } break; default: throw new ParseException("Unable to parse dateTime "+text+" of length "+length, 0); } } catch (ParseException e) { Log.w(TAG, "Failed to parse a time-date", e); } return dateTime; } /** * * @param e * @param text */ protected void handleError(Exception dialogException, String dialogErrorMessage) { Log.e(TAG, "Unable to save ", dialogException); mErrorDialogException = dialogException; mErrorDialogMessage = dialogErrorMessage; cancel(false); throw new CancellationException(dialogErrorMessage); } @Override protected void onPreExecute() { mProgressListener.started(); } @Override protected Uri doInBackground(Uri... params) { Uri importUri = params[0]; determineProgressGoal( importUri); Uri result = importUri( importUri ); return result; } @Override protected void onProgressUpdate(Void... values) { mProgressListener.setProgress(mProgressAdmin.getProgress()); } @Override protected void onPostExecute(Uri result) { mProgressListener.finished(result); } @Override protected void onCancelled() { mProgressListener.showError(mContext.getString(R.string.taskerror_gpx_import), mErrorDialogMessage, mErrorDialogException); } public class ProgressAdmin { private long progressedBytes; private long contentLength; private int progress; private long lastUpdate; /** * Get the progress. * * @return Returns the progress as a int. */ public int getProgress() { return progress; } public void addBytesProgress(int addedBytes) { progressedBytes += addedBytes; progress = (int) (Window.PROGRESS_END * progressedBytes / contentLength); considerPublishProgress(); } public void setContentLength(long contentLength) { this.contentLength = contentLength; } public void considerPublishProgress() { long now = new Date().getTime(); if( now - lastUpdate > 1000 ) { lastUpdate = now; publishProgress(); } } } };
Java
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Jul 9, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.tasks; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.ShareTrack; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import android.content.Context; import android.net.Uri; /** * ???? * * @version $Id:$ * @author rene (c) Jul 9, 2011, Sogeti B.V. */ public class KmzSharing extends KmzCreator { public KmzSharing(Context context, Uri trackUri, String chosenFileName, ProgressListener listener) { super(context, trackUri, chosenFileName, listener); } @Override protected void onPostExecute(Uri resultFilename) { super.onPostExecute(resultFilename); ShareTrack.sendFile(mContext, resultFilename, mContext.getString(R.string.email_kmzbody), getContentType()); } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.tasks; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.db.GPStracking; import nl.sogeti.android.gpstracker.db.GPStracking.Media; import nl.sogeti.android.gpstracker.db.GPStracking.Segments; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints; import nl.sogeti.android.gpstracker.util.Constants; import org.xmlpull.v1.XmlSerializer; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.provider.MediaStore.MediaColumns; import android.util.Log; import android.util.Xml; /** * Create a KMZ version of a stored track * * @version $Id$ * @author rene (c) Mar 22, 2009, Sogeti B.V. */ public class KmzCreator extends XmlCreator { public static final String NS_SCHEMA = "http://www.w3.org/2001/XMLSchema-instance"; public static final String NS_KML_22 = "http://www.opengis.net/kml/2.2"; public static final SimpleDateFormat ZULU_DATE_FORMATER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); static { TimeZone utc = TimeZone.getTimeZone("UTC"); ZULU_DATE_FORMATER.setTimeZone(utc); // ZULU_DATE_FORMAT format ends with Z for UTC so make that true } private String TAG = "OGT.KmzCreator"; public KmzCreator(Context context, Uri trackUri, String chosenFileName, ProgressListener listener) { super(context, trackUri, chosenFileName, listener); } @Override protected Uri doInBackground(Void... params) { determineProgressGoal(); Uri resultFilename = exportKml(); return resultFilename; } private Uri exportKml() { if (mFileName.endsWith(".kmz") || mFileName.endsWith(".zip")) { setExportDirectoryPath(Constants.getSdCardDirectory(mContext) + mFileName.substring(0, mFileName.length() - 4)); } else { setExportDirectoryPath(Constants.getSdCardDirectory(mContext) + mFileName); } new File(getExportDirectoryPath()).mkdirs(); String xmlFilePath = getExportDirectoryPath() + "/doc.kml"; String resultFilename = null; FileOutputStream fos = null; BufferedOutputStream buf = null; try { verifySdCardAvailibility(); XmlSerializer serializer = Xml.newSerializer(); File xmlFile = new File(xmlFilePath); fos = new FileOutputStream(xmlFile); buf = new BufferedOutputStream(fos, 8192); serializer.setOutput(buf, "UTF-8"); serializeTrack(mTrackUri, mFileName, serializer); buf.close(); buf = null; fos.close(); fos = null; resultFilename = bundlingMediaAndXml(xmlFile.getParentFile().getName(), ".kmz"); mFileName = new File(resultFilename).getName(); } catch (IllegalArgumentException e) { String text = mContext.getString(R.string.ticker_failed) + " \"" + xmlFilePath + "\" " + mContext.getString(R.string.error_filename); handleError(mContext.getString(R.string.taskerror_kmz_write), e, text); } catch (IllegalStateException e) { String text = mContext.getString(R.string.ticker_failed) + " \"" + xmlFilePath + "\" " + mContext.getString(R.string.error_buildxml); handleError(mContext.getString(R.string.taskerror_kmz_write), e, text); } catch (IOException e) { String text = mContext.getString(R.string.ticker_failed) + " \"" + xmlFilePath + "\" " + mContext.getString(R.string.error_writesdcard); handleError(mContext.getString(R.string.taskerror_kmz_write), e, text); } finally { if (buf != null) { try { buf.close(); } catch (IOException e) { Log.e(TAG, "Failed to close buf after completion, ignoring.", e); } } if (fos != null) { try { fos.close(); } catch (IOException e) { Log.e(TAG, "Failed to close fos after completion, ignoring.", e); } } } return Uri.fromFile(new File(resultFilename)); } private void serializeTrack(Uri trackUri, String trackName, XmlSerializer serializer) throws IOException { serializer.startDocument("UTF-8", true); serializer.setPrefix("xsi", NS_SCHEMA); serializer.setPrefix("kml", NS_KML_22); serializer.startTag("", "kml"); serializer.attribute(NS_SCHEMA, "schemaLocation", NS_KML_22 + " http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd"); serializer.attribute(null, "xmlns", NS_KML_22); serializer.text("\n"); serializer.startTag("", "Document"); serializer.text("\n"); quickTag(serializer, "", "name", trackName); /* from <name/> upto <Folder/> */ serializeTrackHeader(serializer, trackUri); serializer.text("\n"); serializer.endTag("", "Document"); serializer.endTag("", "kml"); serializer.endDocument(); } private String serializeTrackHeader(XmlSerializer serializer, Uri trackUri) throws IOException { ContentResolver resolver = mContext.getContentResolver(); Cursor trackCursor = null; String name = null; try { trackCursor = resolver.query(trackUri, new String[] { Tracks.NAME }, null, null, null); if (trackCursor.moveToFirst()) { serializer.text("\n"); serializer.startTag("", "Style"); serializer.attribute(null, "id", "lineStyle"); serializer.startTag("", "LineStyle"); serializer.text("\n"); serializer.startTag("", "color"); serializer.text("99ffac59"); serializer.endTag("", "color"); serializer.text("\n"); serializer.startTag("", "width"); serializer.text("6"); serializer.endTag("", "width"); serializer.text("\n"); serializer.endTag("", "LineStyle"); serializer.text("\n"); serializer.endTag("", "Style"); serializer.text("\n"); serializer.startTag("", "Folder"); name = trackCursor.getString(0); serializer.text("\n"); quickTag(serializer, "", "name", name); serializer.text("\n"); serializer.startTag("", "open"); serializer.text("1"); serializer.endTag("", "open"); serializer.text("\n"); serializeSegments(serializer, Uri.withAppendedPath(trackUri, "segments")); serializer.text("\n"); serializer.endTag("", "Folder"); } } finally { if (trackCursor != null) { trackCursor.close(); } } return name; } /** * <pre> * &lt;Folder> * &lt;Placemark> * serializeSegmentToTimespan() * &lt;LineString> * serializeWaypoints() * &lt;/LineString> * &lt;/Placemark> * &lt;Placemark/> * &lt;Placemark/> * &lt;/Folder> * </pre> * * @param serializer * @param segments * @throws IOException */ private void serializeSegments(XmlSerializer serializer, Uri segments) throws IOException { Cursor segmentCursor = null; ContentResolver resolver = mContext.getContentResolver(); try { segmentCursor = resolver.query(segments, new String[] { Segments._ID }, null, null, null); if (segmentCursor.moveToFirst()) { do { Uri waypoints = Uri.withAppendedPath(segments, segmentCursor.getLong(0) + "/waypoints"); serializer.text("\n"); serializer.startTag("", "Folder"); serializer.text("\n"); serializer.startTag("", "name"); serializer.text(String.format("Segment %d", 1 + segmentCursor.getPosition())); serializer.endTag("", "name"); serializer.text("\n"); serializer.startTag("", "open"); serializer.text("1"); serializer.endTag("", "open"); /* Single <TimeSpan/> element */ serializeSegmentToTimespan(serializer, waypoints); serializer.text("\n"); serializer.startTag("", "Placemark"); serializer.text("\n"); serializer.startTag("", "name"); serializer.text("Path"); serializer.endTag("", "name"); serializer.text("\n"); serializer.startTag("", "styleUrl"); serializer.text("#lineStyle"); serializer.endTag("", "styleUrl"); serializer.text("\n"); serializer.startTag("", "LineString"); serializer.text("\n"); serializer.startTag("", "tessellate"); serializer.text("0"); serializer.endTag("", "tessellate"); serializer.text("\n"); serializer.startTag("", "altitudeMode"); serializer.text("clampToGround"); serializer.endTag("", "altitudeMode"); /* Single <coordinates/> element */ serializeWaypoints(serializer, waypoints); serializer.text("\n"); serializer.endTag("", "LineString"); serializer.text("\n"); serializer.endTag("", "Placemark"); serializeWaypointDescription(serializer, Uri.withAppendedPath(segments, "/" + segmentCursor.getLong(0) + "/media")); serializer.text("\n"); serializer.endTag("", "Folder"); } while (segmentCursor.moveToNext()); } } finally { if (segmentCursor != null) { segmentCursor.close(); } } } /** * &lt;TimeSpan>&lt;begin>...&lt;/begin>&lt;end>...&lt;/end>&lt;/TimeSpan> * * @param serializer * @param waypoints * @throws IOException */ private void serializeSegmentToTimespan(XmlSerializer serializer, Uri waypoints) throws IOException { Cursor waypointsCursor = null; Date segmentStartTime = null; Date segmentEndTime = null; ContentResolver resolver = mContext.getContentResolver(); try { waypointsCursor = resolver.query(waypoints, new String[] { Waypoints.TIME }, null, null, null); if (waypointsCursor.moveToFirst()) { segmentStartTime = new Date(waypointsCursor.getLong(0)); if (waypointsCursor.moveToLast()) { segmentEndTime = new Date(waypointsCursor.getLong(0)); serializer.text("\n"); serializer.startTag("", "TimeSpan"); serializer.text("\n"); serializer.startTag("", "begin"); synchronized (ZULU_DATE_FORMATER) { serializer.text(ZULU_DATE_FORMATER.format(segmentStartTime)); serializer.endTag("", "begin"); serializer.text("\n"); serializer.startTag("", "end"); serializer.text(ZULU_DATE_FORMATER.format(segmentEndTime)); } serializer.endTag("", "end"); serializer.text("\n"); serializer.endTag("", "TimeSpan"); } } } finally { if (waypointsCursor != null) { waypointsCursor.close(); } } } /** * &lt;coordinates>...&lt;/coordinates> * * @param serializer * @param waypoints * @throws IOException */ private void serializeWaypoints(XmlSerializer serializer, Uri waypoints) throws IOException { Cursor waypointsCursor = null; ContentResolver resolver = mContext.getContentResolver(); try { waypointsCursor = resolver.query(waypoints, new String[] { Waypoints.LONGITUDE, Waypoints.LATITUDE, Waypoints.ALTITUDE }, null, null, null); if (waypointsCursor.moveToFirst()) { serializer.text("\n"); serializer.startTag("", "coordinates"); do { mProgressAdmin.addWaypointProgress(1); // Single Coordinate tuple serializeCoordinates(serializer, waypointsCursor); serializer.text(" "); } while (waypointsCursor.moveToNext()); serializer.endTag("", "coordinates"); } } finally { if (waypointsCursor != null) { waypointsCursor.close(); } } } /** * lon,lat,alt tuple without trailing spaces * * @param serializer * @param waypointsCursor * @throws IOException */ private void serializeCoordinates(XmlSerializer serializer, Cursor waypointsCursor) throws IOException { serializer.text(Double.toString(waypointsCursor.getDouble(0))); serializer.text(","); serializer.text(Double.toString(waypointsCursor.getDouble(1))); serializer.text(","); serializer.text(Double.toString(waypointsCursor.getDouble(2))); } private void serializeWaypointDescription(XmlSerializer serializer, Uri media) throws IOException { String mediaPathPrefix = Constants.getSdCardDirectory(mContext); Cursor mediaCursor = null; ContentResolver resolver = mContext.getContentResolver(); BufferedReader buf = null; try { mediaCursor = resolver.query(media, new String[] { Media.URI, Media.TRACK, Media.SEGMENT, Media.WAYPOINT }, null, null, null); if (mediaCursor.moveToFirst()) { do { Uri mediaUri = Uri.parse(mediaCursor.getString(0)); Uri singleWaypointUri = Uri.withAppendedPath(Tracks.CONTENT_URI, mediaCursor.getLong(1) + "/segments/" + mediaCursor.getLong(2) + "/waypoints/" + mediaCursor.getLong(3)); String lastPathSegment = mediaUri.getLastPathSegment(); if (mediaUri.getScheme().equals("file")) { if (lastPathSegment.endsWith("3gp")) { String includedMediaFile = includeMediaFile(lastPathSegment); serializer.text("\n"); serializer.startTag("", "Placemark"); serializer.text("\n"); quickTag(serializer, "", "name", lastPathSegment); serializer.text("\n"); serializer.startTag("", "description"); String kmlAudioUnsupported = mContext.getString(R.string.kmlVideoUnsupported); serializer.text(String.format(kmlAudioUnsupported, includedMediaFile)); serializer.endTag("", "description"); serializeMediaPoint(serializer, singleWaypointUri); serializer.text("\n"); serializer.endTag("", "Placemark"); } else if (lastPathSegment.endsWith("jpg")) { String includedMediaFile = includeMediaFile(mediaPathPrefix + lastPathSegment); serializer.text("\n"); serializer.startTag("", "Placemark"); serializer.text("\n"); quickTag(serializer, "", "name", lastPathSegment); serializer.text("\n"); quickTag(serializer, "", "description", "<img src=\"" + includedMediaFile + "\" width=\"500px\"/><br/>" + lastPathSegment); serializer.text("\n"); serializeMediaPoint(serializer, singleWaypointUri); serializer.text("\n"); serializer.endTag("", "Placemark"); } else if (lastPathSegment.endsWith("txt")) { serializer.text("\n"); serializer.startTag("", "Placemark"); serializer.text("\n"); quickTag(serializer, "", "name", lastPathSegment); serializer.text("\n"); serializer.startTag("", "description"); if(buf != null ) buf.close(); buf = new BufferedReader(new FileReader(mediaUri.getEncodedPath())); String line; while ((line = buf.readLine()) != null) { serializer.text(line); serializer.text("\n"); } serializer.endTag("", "description"); serializeMediaPoint(serializer, singleWaypointUri); serializer.text("\n"); serializer.endTag("", "Placemark"); } } else if (mediaUri.getScheme().equals("content")) { if (mediaUri.getAuthority().equals(GPStracking.AUTHORITY + ".string")) { serializer.text("\n"); serializer.startTag("", "Placemark"); serializer.text("\n"); quickTag(serializer, "", "name", lastPathSegment); serializeMediaPoint(serializer, singleWaypointUri); serializer.text("\n"); serializer.endTag("", "Placemark"); } else if (mediaUri.getAuthority().equals("media")) { Cursor mediaItemCursor = null; try { mediaItemCursor = resolver.query(mediaUri, new String[] { MediaColumns.DATA, MediaColumns.DISPLAY_NAME }, null, null, null); if (mediaItemCursor.moveToFirst()) { String includedMediaFile = includeMediaFile(mediaItemCursor.getString(0)); serializer.text("\n"); serializer.startTag("", "Placemark"); serializer.text("\n"); quickTag(serializer, "", "name", mediaItemCursor.getString(1)); serializer.text("\n"); serializer.startTag("", "description"); String kmlAudioUnsupported = mContext.getString(R.string.kmlAudioUnsupported); serializer.text(String.format(kmlAudioUnsupported, includedMediaFile)); serializer.endTag("", "description"); serializeMediaPoint(serializer, singleWaypointUri); serializer.text("\n"); serializer.endTag("", "Placemark"); } } finally { if (mediaItemCursor != null) { mediaItemCursor.close(); } } } } } while (mediaCursor.moveToNext()); } } finally { if (mediaCursor != null) { mediaCursor.close(); } if(buf != null ) buf.close(); } } /** * &lt;Point>...&lt;/Point> &lt;shape>rectangle&lt;/shape> * * @param serializer * @param singleWaypointUri * @throws IllegalArgumentException * @throws IllegalStateException * @throws IOException */ private void serializeMediaPoint(XmlSerializer serializer, Uri singleWaypointUri) throws IllegalArgumentException, IllegalStateException, IOException { Cursor waypointsCursor = null; ContentResolver resolver = mContext.getContentResolver(); try { waypointsCursor = resolver.query(singleWaypointUri, new String[] { Waypoints.LONGITUDE, Waypoints.LATITUDE, Waypoints.ALTITUDE }, null, null, null); if (waypointsCursor.moveToFirst()) { serializer.text("\n"); serializer.startTag("", "Point"); serializer.text("\n"); serializer.startTag("", "coordinates"); serializeCoordinates(serializer, waypointsCursor); serializer.endTag("", "coordinates"); serializer.text("\n"); serializer.endTag("", "Point"); serializer.text("\n"); } } finally { if (waypointsCursor != null) { waypointsCursor.close(); } } } @Override protected String getContentType() { return "application/vnd.google-earth.kmz"; } @Override public boolean needsBundling() { return true; } }
Java
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Jul 9, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.tasks; import java.io.File; import java.io.IOException; import java.io.InputStream; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.ShareTrack; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.db.GPStracking; import nl.sogeti.android.gpstracker.db.GPStracking.Media; import nl.sogeti.android.gpstracker.db.GPStracking.MetaData; import nl.sogeti.android.gpstracker.oauth.PrepareRequestTokenActivity; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.viewer.map.LoggerMapHelper; import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.methods.HttpPost; import org.apache.ogt.http.entity.mime.HttpMultipartMode; import org.apache.ogt.http.entity.mime.MultipartEntity; import org.apache.ogt.http.entity.mime.content.FileBody; import org.apache.ogt.http.entity.mime.content.StringBody; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.util.EntityUtils; import android.app.Activity; import android.content.ContentResolver; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.database.Cursor; import android.net.Uri; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; /** * ???? * * @version $Id:$ * @author rene (c) Jul 9, 2011, Sogeti B.V. */ public class OsmSharing extends GpxCreator { public static final String OAUTH_TOKEN = "openstreetmap_oauth_token"; public static final String OAUTH_TOKEN_SECRET = "openstreetmap_oauth_secret"; private static final String TAG = "OGT.OsmSharing"; public static final String OSM_FILENAME = "OSM_Trace"; private String responseText; private Uri mFileUri; public OsmSharing(Activity context, Uri trackUri, boolean attachments, ProgressListener listener) { super(context, trackUri, OSM_FILENAME, attachments, listener); } public void resumeOsmSharing(Uri fileUri, Uri trackUri) { mFileUri = fileUri; mTrackUri = trackUri; execute(); } @Override protected Uri doInBackground(Void... params) { if( mFileUri == null ) { mFileUri = super.doInBackground(params); } sendToOsm(mFileUri, mTrackUri); return mFileUri; } @Override protected void onPostExecute(Uri resultFilename) { super.onPostExecute(resultFilename); CharSequence text = mContext.getString(R.string.osm_success) + responseText; Toast toast = Toast.makeText(mContext, text, Toast.LENGTH_LONG); toast.show(); } /** * POST a (GPX) file to the 0.6 API of the OpenStreetMap.org website * publishing this track to the public. * * @param fileUri * @param contentType */ private void sendToOsm(final Uri fileUri, final Uri trackUri) { CommonsHttpOAuthConsumer consumer = osmConnectionSetup(); if( consumer == null ) { requestOpenstreetmapOauthToken(); handleError(mContext.getString(R.string.osm_task), null, mContext.getString(R.string.osmauth_message)); } String visibility = PreferenceManager.getDefaultSharedPreferences(mContext).getString(Constants.OSM_VISIBILITY, "trackable"); File gpxFile = new File(fileUri.getEncodedPath()); String url = mContext.getString(R.string.osm_post_url); DefaultHttpClient httpclient = new DefaultHttpClient(); HttpResponse response = null; int statusCode = 0; Cursor metaData = null; String sources = null; HttpEntity responseEntity = null; try { metaData = mContext.getContentResolver().query(Uri.withAppendedPath(trackUri, "metadata"), new String[] { MetaData.VALUE }, MetaData.KEY + " = ? ", new String[] { Constants.DATASOURCES_KEY }, null); if (metaData.moveToFirst()) { sources = metaData.getString(0); } if (sources != null && sources.contains(LoggerMapHelper.GOOGLE_PROVIDER)) { throw new IOException("Unable to upload track with materials derived from Google Maps."); } // The POST to the create node HttpPost method = new HttpPost(url); String tags = mContext.getString(R.string.osm_tag) + " " +queryForNotes(); // Build the multipart body with the upload data MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("file", new FileBody(gpxFile)); entity.addPart("description", new StringBody( ShareTrack.queryForTrackName(mContext.getContentResolver(), mTrackUri))); entity.addPart("tags", new StringBody(tags)); entity.addPart("visibility", new StringBody(visibility)); method.setEntity(entity); // Execute the POST to OpenStreetMap consumer.sign(method); response = httpclient.execute(method); // Read the response statusCode = response.getStatusLine().getStatusCode(); responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); responseText = XmlCreator.convertStreamToString(stream); } catch (OAuthMessageSignerException e) { Editor editor = PreferenceManager.getDefaultSharedPreferences(mContext).edit(); editor.remove(OAUTH_TOKEN); editor.remove(OAUTH_TOKEN_SECRET); editor.commit(); responseText = mContext.getString(R.string.osm_failed) + e.getLocalizedMessage(); handleError(mContext.getString(R.string.osm_task), e, responseText); } catch (OAuthExpectationFailedException e) { Editor editor = PreferenceManager.getDefaultSharedPreferences(mContext).edit(); editor.remove(OAUTH_TOKEN); editor.remove(OAUTH_TOKEN_SECRET); editor.commit(); responseText = mContext.getString(R.string.osm_failed) + e.getLocalizedMessage(); handleError(mContext.getString(R.string.osm_task), e, responseText); } catch (OAuthCommunicationException e) { Editor editor = PreferenceManager.getDefaultSharedPreferences(mContext).edit(); editor.remove(OAUTH_TOKEN); editor.remove(OAUTH_TOKEN_SECRET); editor.commit(); responseText = mContext.getString(R.string.osm_failed) + e.getLocalizedMessage(); handleError(mContext.getString(R.string.osm_task), e, responseText); } catch (IOException e) { responseText = mContext.getString(R.string.osm_failed) + e.getLocalizedMessage(); handleError(mContext.getString(R.string.osm_task), e, responseText); } finally { if (responseEntity != null) { try { EntityUtils.consume(responseEntity); } catch (IOException e) { Log.e(TAG, "Failed to close the content stream", e); } } if (metaData != null) { metaData.close(); } } if (statusCode != 200) { Log.e(TAG, "Failed to upload to error code " + statusCode + " " + responseText); String text = mContext.getString(R.string.osm_failed) + responseText; if( statusCode == 401 ) { Editor editor = PreferenceManager.getDefaultSharedPreferences(mContext).edit(); editor.remove(OAUTH_TOKEN); editor.remove(OAUTH_TOKEN_SECRET); editor.commit(); } handleError(mContext.getString(R.string.osm_task), new HttpException("Unexpected status reported by OSM"), text); } } private CommonsHttpOAuthConsumer osmConnectionSetup() { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); String token = prefs.getString(OAUTH_TOKEN, ""); String secret = prefs.getString(OAUTH_TOKEN_SECRET, ""); boolean mAuthorized = !"".equals(token) && !"".equals(secret); CommonsHttpOAuthConsumer consumer = null; if (mAuthorized) { consumer = new CommonsHttpOAuthConsumer(mContext.getString(R.string.OSM_CONSUMER_KEY), mContext.getString(R.string.OSM_CONSUMER_SECRET)); consumer.setTokenWithSecret(token, secret); } return consumer; } private String queryForNotes() { StringBuilder tags = new StringBuilder(); ContentResolver resolver = mContext.getContentResolver(); Cursor mediaCursor = null; Uri mediaUri = Uri.withAppendedPath(mTrackUri, "media"); try { mediaCursor = resolver.query(mediaUri, new String[] { Media.URI }, null, null, null); if (mediaCursor.moveToFirst()) { do { Uri noteUri = Uri.parse(mediaCursor.getString(0)); if (noteUri.getScheme().equals("content") && noteUri.getAuthority().equals(GPStracking.AUTHORITY + ".string")) { String tag = noteUri.getLastPathSegment().trim(); if (!tag.contains(" ")) { if (tags.length() > 0) { tags.append(" "); } tags.append(tag); } } } while (mediaCursor.moveToNext()); } } finally { if (mediaCursor != null) { mediaCursor.close(); } } return tags.toString(); } public void requestOpenstreetmapOauthToken() { Intent intent = new Intent(mContext.getApplicationContext(), PrepareRequestTokenActivity.class); intent.putExtra(PrepareRequestTokenActivity.OAUTH_TOKEN_PREF, OAUTH_TOKEN); intent.putExtra(PrepareRequestTokenActivity.OAUTH_TOKEN_SECRET_PREF, OAUTH_TOKEN_SECRET); intent.putExtra(PrepareRequestTokenActivity.CONSUMER_KEY, mContext.getString(R.string.OSM_CONSUMER_KEY)); intent.putExtra(PrepareRequestTokenActivity.CONSUMER_SECRET, mContext.getString(R.string.OSM_CONSUMER_SECRET)); intent.putExtra(PrepareRequestTokenActivity.REQUEST_URL, Constants.OSM_REQUEST_URL); intent.putExtra(PrepareRequestTokenActivity.ACCESS_URL, Constants.OSM_ACCESS_URL); intent.putExtra(PrepareRequestTokenActivity.AUTHORIZE_URL, Constants.OSM_AUTHORIZE_URL); mContext.startActivity(intent); } }
Java
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Jul 9, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.tasks; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.ShareTrack; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import android.content.Context; import android.net.Uri; /** * ???? * * @version $Id:$ * @author rene (c) Jul 9, 2011, Sogeti B.V. */ public class GpxSharing extends GpxCreator { public GpxSharing(Context context, Uri trackUri, String chosenBaseFileName, boolean attachments, ProgressListener listener) { super(context, trackUri, chosenBaseFileName, attachments, listener); } @Override protected void onPostExecute(Uri resultFilename) { super.onPostExecute(resultFilename); ShareTrack.sendFile(mContext, resultFilename, mContext.getString(R.string.email_gpxbody), getContentType()); } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions; import java.util.List; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsService; import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsService.LocalBinder; import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsTracks; import nl.sogeti.android.gpstracker.db.GPStracking.MetaData; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.Pair; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.ComponentName; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnDismissListener; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.net.Uri; import android.os.Bundle; import android.os.IBinder; import android.preference.PreferenceManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.SpinnerAdapter; /** * Empty Activity that pops up the dialog to describe the track * * @version $Id: NameTrack.java 888 2011-03-14 19:44:44Z rcgroot@gmail.com $ * @author rene (c) Jul 27, 2010, Sogeti B.V. */ public class DescribeTrack extends Activity { private static final int DIALOG_TRACKDESCRIPTION = 42; protected static final String TAG = "OGT.DescribeTrack"; private static final String ACTIVITY_ID = "ACTIVITY_ID"; private static final String BUNDLE_ID = "BUNDLE_ID"; private Spinner mActivitySpinner; private Spinner mBundleSpinner; private EditText mDescriptionText; private CheckBox mPublicCheck; private Button mOkayButton; private boolean paused; private Uri mTrackUri; private ProgressBar mProgressSpinner; private AlertDialog mDialog; private BreadcrumbsService mService; boolean mBound = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setVisible(false); paused = false; mTrackUri = this.getIntent().getData(); Intent service = new Intent(this, BreadcrumbsService.class); startService(service); } @Override protected void onStart() { super.onStart(); Intent intent = new Intent(this, BreadcrumbsService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } /* * (non-Javadoc) * @see com.google.android.maps.MapActivity#onPause() */ @Override protected void onResume() { super.onResume(); if (mTrackUri != null) { showDialog(DIALOG_TRACKDESCRIPTION); } else { Log.e(TAG, "Describing track without a track URI supplied."); finish(); } } @Override protected void onPause() { super.onPause(); paused = true; } @Override protected void onStop() { if (mBound) { unbindService(mConnection); mBound = false; mService = null; } super.onStop(); } @Override protected void onDestroy() { if (isFinishing()) { Intent service = new Intent(this, BreadcrumbsService.class); stopService(service); } super.onDestroy(); } @Override protected Dialog onCreateDialog(int id) { LayoutInflater factory = null; View view = null; Builder builder = null; switch (id) { case DIALOG_TRACKDESCRIPTION: builder = new AlertDialog.Builder(this); factory = LayoutInflater.from(this); view = factory.inflate(R.layout.describedialog, null); mActivitySpinner = (Spinner) view.findViewById(R.id.activity); mBundleSpinner = (Spinner) view.findViewById(R.id.bundle); mDescriptionText = (EditText) view.findViewById(R.id.description); mPublicCheck = (CheckBox) view.findViewById(R.id.public_checkbox); mProgressSpinner = (ProgressBar) view.findViewById(R.id.progressSpinner); builder.setTitle(R.string.dialog_description_title).setMessage(R.string.dialog_description_message).setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.btn_okay, mTrackDescriptionDialogListener).setNegativeButton(R.string.btn_cancel, mTrackDescriptionDialogListener).setView(view); mDialog = builder.create(); setUiEnabled(); mDialog.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { if (!paused) { finish(); } } }); return mDialog; default: return super.onCreateDialog(id); } } @Override protected void onPrepareDialog(int id, Dialog dialog) { switch (id) { case DIALOG_TRACKDESCRIPTION: setUiEnabled(); connectBreadcrumbs(); break; default: super.onPrepareDialog(id, dialog); break; } } private void connectBreadcrumbs() { if (mService != null && !mService.isAuthorized()) { mService.collectBreadcrumbsOauthToken(); } } private void saveBreadcrumbsPreference(int activityPosition, int bundlePosition) { Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit(); editor.putInt(ACTIVITY_ID, activityPosition); editor.putInt(BUNDLE_ID, bundlePosition); editor.commit(); } private void loadBreadcrumbsPreference() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); int activityPos = prefs.getInt(ACTIVITY_ID, 0); activityPos = activityPos < mActivitySpinner.getCount() ? activityPos : 0; mActivitySpinner.setSelection(activityPos); int bundlePos = prefs.getInt(BUNDLE_ID, 0); bundlePos = bundlePos < mBundleSpinner.getCount() ? bundlePos : 0; mBundleSpinner.setSelection(bundlePos); } private ContentValues buildContentValues(String key, String value) { ContentValues contentValues = new ContentValues(); contentValues.put(MetaData.KEY, key); contentValues.put(MetaData.VALUE, value); return contentValues; } private void setUiEnabled() { boolean enabled = mService != null && mService.isAuthorized(); if (mProgressSpinner != null) { if (enabled) { mProgressSpinner.setVisibility(View.GONE); } else { mProgressSpinner.setVisibility(View.VISIBLE); } } if (mDialog != null) { mOkayButton = mDialog.getButton(AlertDialog.BUTTON_POSITIVE); } for (View view : new View[] { mActivitySpinner, mBundleSpinner, mDescriptionText, mPublicCheck, mOkayButton }) { if (view != null) { view.setEnabled(enabled); } } if (enabled) { mActivitySpinner.setAdapter(getActivityAdapter()); mBundleSpinner.setAdapter(getBundleAdapter()); loadBreadcrumbsPreference(); } } public SpinnerAdapter getActivityAdapter() { List<Pair<Integer, Integer>> activities = mService.getActivityList(); ArrayAdapter<Pair<Integer, Integer>> adapter = new ArrayAdapter<Pair<Integer, Integer>>(this, android.R.layout.simple_spinner_item, activities); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); return adapter; } public SpinnerAdapter getBundleAdapter() { List<Pair<Integer, Integer>> bundles = mService.getBundleList(); ArrayAdapter<Pair<Integer, Integer>> adapter = new ArrayAdapter<Pair<Integer, Integer>>(this, android.R.layout.simple_spinner_item, bundles); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); return adapter; } private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { // We've bound to LocalService, cast the IBinder and get LocalService instance LocalBinder binder = (LocalBinder) service; mService = binder.getService(); mBound = true; setUiEnabled(); } @Override public void onServiceDisconnected(ComponentName arg0) { mService = null; mBound = false; } }; private final DialogInterface.OnClickListener mTrackDescriptionDialogListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: Uri metadataUri = Uri.withAppendedPath(mTrackUri, "metadata"); Integer activityId = ((Pair<Integer, Integer>)mActivitySpinner.getSelectedItem()).second; Integer bundleId = ((Pair<Integer, Integer>)mBundleSpinner.getSelectedItem()).second; saveBreadcrumbsPreference(mActivitySpinner.getSelectedItemPosition(), mBundleSpinner.getSelectedItemPosition()); String description = mDescriptionText.getText().toString(); String isPublic = Boolean.toString(mPublicCheck.isChecked()); ContentValues[] metaValues = { buildContentValues(BreadcrumbsTracks.ACTIVITY_ID, activityId.toString()), buildContentValues(BreadcrumbsTracks.BUNDLE_ID, bundleId.toString()), buildContentValues(BreadcrumbsTracks.DESCRIPTION, description), buildContentValues(BreadcrumbsTracks.ISPUBLIC, isPublic), }; getContentResolver().bulkInsert(metadataUri, metaValues); Intent data = new Intent(); data.setData(mTrackUri); if (getIntent().getExtras() != null && getIntent().getExtras().containsKey(Constants.NAME)) { data.putExtra(Constants.NAME, getIntent().getExtras().getString(Constants.NAME)); } setResult(RESULT_OK, data); break; case DialogInterface.BUTTON_NEGATIVE: break; default: Log.e(TAG, "Unknown option ending dialog:" + which); break; } finish(); } }; }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.logger.GPSLoggerServiceManager; import nl.sogeti.android.gpstracker.util.Constants; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.ComponentName; import android.content.ContentUris; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnDismissListener; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; /** * Empty Activity that pops up the dialog to name the track * * @version $Id$ * @author rene (c) Jul 27, 2010, Sogeti B.V. */ public class ControlTracking extends Activity { private static final int DIALOG_LOGCONTROL = 26; private static final String TAG = "OGT.ControlTracking"; private GPSLoggerServiceManager mLoggerServiceManager; private Button start; private Button pause; private Button resume; private Button stop; private boolean paused; private final View.OnClickListener mLoggingControlListener = new View.OnClickListener() { @Override public void onClick( View v ) { int id = v.getId(); Intent intent = new Intent(); switch( id ) { case R.id.logcontrol_start: long loggerTrackId = mLoggerServiceManager.startGPSLogging( null ); // Start a naming of the track Intent namingIntent = new Intent( ControlTracking.this, NameTrack.class ); namingIntent.setData( ContentUris.withAppendedId( Tracks.CONTENT_URI, loggerTrackId ) ); startActivity( namingIntent ); // Create data for the caller that a new track has been started ComponentName caller = ControlTracking.this.getCallingActivity(); if( caller != null ) { intent.setData( ContentUris.withAppendedId( Tracks.CONTENT_URI, loggerTrackId ) ); setResult( RESULT_OK, intent ); } break; case R.id.logcontrol_pause: mLoggerServiceManager.pauseGPSLogging(); setResult( RESULT_OK, intent ); break; case R.id.logcontrol_resume: mLoggerServiceManager.resumeGPSLogging(); setResult( RESULT_OK, intent ); break; case R.id.logcontrol_stop: mLoggerServiceManager.stopGPSLogging(); setResult( RESULT_OK, intent ); break; default: setResult( RESULT_CANCELED, intent ); break; } finish(); } }; private OnClickListener mDialogClickListener = new OnClickListener() { @Override public void onClick( DialogInterface dialog, int which ) { setResult( RESULT_CANCELED, new Intent() ); finish(); } }; @Override protected void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); this.setVisible( false ); paused = false; mLoggerServiceManager = new GPSLoggerServiceManager( this ); } @Override protected void onResume() { super.onResume(); mLoggerServiceManager.startup( this, new Runnable() { @Override public void run() { showDialog( DIALOG_LOGCONTROL ); } } ); } @Override protected void onPause() { super.onPause(); mLoggerServiceManager.shutdown( this ); paused = true; } @Override protected Dialog onCreateDialog( int id ) { Dialog dialog = null; LayoutInflater factory = null; View view = null; Builder builder = null; switch( id ) { case DIALOG_LOGCONTROL: builder = new AlertDialog.Builder( this ); factory = LayoutInflater.from( this ); view = factory.inflate( R.layout.logcontrol, null ); builder.setTitle( R.string.dialog_tracking_title ). setIcon( android.R.drawable.ic_dialog_alert ). setNegativeButton( R.string.btn_cancel, mDialogClickListener ). setView( view ); dialog = builder.create(); start = (Button) view.findViewById( R.id.logcontrol_start ); pause = (Button) view.findViewById( R.id.logcontrol_pause ); resume = (Button) view.findViewById( R.id.logcontrol_resume ); stop = (Button) view.findViewById( R.id.logcontrol_stop ); start.setOnClickListener( mLoggingControlListener ); pause.setOnClickListener( mLoggingControlListener ); resume.setOnClickListener( mLoggingControlListener ); stop.setOnClickListener( mLoggingControlListener ); dialog.setOnDismissListener( new OnDismissListener() { @Override public void onDismiss( DialogInterface dialog ) { if( !paused ) { finish(); } } }); return dialog; default: return super.onCreateDialog( id ); } } /* * (non-Javadoc) * @see android.app.Activity#onPrepareDialog(int, android.app.Dialog) */ @Override protected void onPrepareDialog( int id, Dialog dialog ) { switch( id ) { case DIALOG_LOGCONTROL: updateDialogState( mLoggerServiceManager.getLoggingState() ); break; default: break; } super.onPrepareDialog( id, dialog ); } private void updateDialogState( int state ) { switch( state ) { case Constants.STOPPED: start.setEnabled( true ); pause.setEnabled( false ); resume.setEnabled( false ); stop.setEnabled( false ); break; case Constants.LOGGING: start.setEnabled( false ); pause.setEnabled( true ); resume.setEnabled( false ); stop.setEnabled( true ); break; case Constants.PAUSED: start.setEnabled( false ); pause.setEnabled( false ); resume.setEnabled( true ); stop.setEnabled( true ); break; default: Log.w( TAG, String.format( "State %d of logging, enabling and hope for the best....", state ) ); start.setEnabled( false ); pause.setEnabled( false ); resume.setEnabled( false ); stop.setEnabled( false ); break; } } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.util.Calendar; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.logger.GPSLoggerServiceManager; import nl.sogeti.android.gpstracker.util.Constants; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnDismissListener; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapFactory.Options; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; /** * Empty Activity that pops up the dialog to add a note to the most current * point in the logger service * * @version $Id$ * @author rene (c) Jul 27, 2010, Sogeti B.V. */ public class InsertNote extends Activity { private static final int DIALOG_INSERTNOTE = 27; private static final String TAG = "OGT.InsertNote"; private static final int MENU_PICTURE = 9; private static final int MENU_VOICE = 11; private static final int MENU_VIDEO = 12; private static final int DIALOG_TEXT = 32; private static final int DIALOG_NAME = 33; private GPSLoggerServiceManager mLoggerServiceManager; /** * Action to take when the LoggerService is bound */ private Runnable mServiceBindAction; private boolean paused; private Button name; private Button text; private Button voice; private Button picture; private Button video; private EditText mNoteNameView; private EditText mNoteTextView; private final OnClickListener mNoteTextDialogListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String noteText = mNoteTextView.getText().toString(); Calendar c = Calendar.getInstance(); String newName = String.format("Textnote_%tY-%tm-%td_%tH%tM%tS.txt", c, c, c, c, c, c); File file = new File(Constants.getSdCardDirectory(InsertNote.this) + newName); FileWriter filewriter = null; try { file.getParentFile().mkdirs(); file.createNewFile(); filewriter = new FileWriter(file); filewriter.append(noteText); filewriter.flush(); } catch (IOException e) { Log.e(TAG, "Note storing failed", e); CharSequence text = e.getLocalizedMessage(); Toast toast = Toast.makeText(InsertNote.this, text, Toast.LENGTH_LONG); toast.show(); } finally { if (filewriter != null) { try { filewriter.close(); } catch (IOException e) { /* */ } } } InsertNote.this.mLoggerServiceManager.storeMediaUri(Uri.fromFile(file)); setResult(RESULT_CANCELED, new Intent()); finish(); } }; private final OnClickListener mNoteNameDialogListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String name = mNoteNameView.getText().toString(); Uri media = Uri.withAppendedPath(Constants.NAME_URI, Uri.encode(name)); InsertNote.this.mLoggerServiceManager.storeMediaUri(media); setResult(RESULT_CANCELED, new Intent()); finish(); } }; private final View.OnClickListener mNoteInsertListener = new View.OnClickListener() { @Override public void onClick(View v) { int id = v.getId(); switch (id) { case R.id.noteinsert_picture: addPicture(); break; case R.id.noteinsert_video: addVideo(); break; case R.id.noteinsert_voice: addVoice(); break; case R.id.noteinsert_text: showDialog(DIALOG_TEXT); break; case R.id.noteinsert_name: showDialog(DIALOG_NAME); break; default: setResult(RESULT_CANCELED, new Intent()); finish(); break; } } }; private OnClickListener mDialogClickListener = new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { setResult(RESULT_CANCELED, new Intent()); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setVisible(false); paused = false; mLoggerServiceManager = new GPSLoggerServiceManager(this); } @Override protected void onResume() { super.onResume(); if (mServiceBindAction == null) { mServiceBindAction = new Runnable() { @Override public void run() { showDialog(DIALOG_INSERTNOTE); } }; } ; mLoggerServiceManager.startup(this, mServiceBindAction); } @Override protected void onPause() { super.onPause(); mLoggerServiceManager.shutdown(this); paused = true; } /* * (non-Javadoc) * @see android.app.Activity#onActivityResult(int, int, * android.content.Intent) */ @Override protected void onActivityResult(final int requestCode, final int resultCode, final Intent intent) { super.onActivityResult(requestCode, resultCode, intent); mServiceBindAction = new Runnable() { @Override public void run() { if (resultCode != RESULT_CANCELED) { File file; Uri uri; File newFile; String newName; Uri fileUri; android.net.Uri.Builder builder; boolean isLocal = false; switch (requestCode) { case MENU_PICTURE: file = new File(Constants.getSdCardTmpFile(InsertNote.this)); Calendar c = Calendar.getInstance(); newName = String.format("Picture_%tY-%tm-%td_%tH%tM%tS.jpg", c, c, c, c, c, c); newFile = new File(Constants.getSdCardDirectory(InsertNote.this) + newName); file.getParentFile().mkdirs(); isLocal = file.renameTo(newFile); // if (!isLocal) { Log.w(TAG, "Failed rename will try copy image: " + file.getAbsolutePath()); isLocal = copyFile(file, newFile); } if (isLocal) { System.gc(); Options opts = new Options(); opts.inJustDecodeBounds = true; Bitmap bm = BitmapFactory.decodeFile(newFile.getAbsolutePath(), opts); String height, width; if (bm != null) { height = Integer.toString(bm.getHeight()); width = Integer.toString(bm.getWidth()); } else { height = Integer.toString(opts.outHeight); width = Integer.toString(opts.outWidth); } bm = null; builder = new Uri.Builder(); fileUri = builder.scheme("file").appendEncodedPath("/").appendEncodedPath(newFile.getAbsolutePath()) .appendQueryParameter("width", width).appendQueryParameter("height", height).build(); InsertNote.this.mLoggerServiceManager.storeMediaUri(fileUri); } else { Log.e(TAG, "Failed either rename or copy image: " + file.getAbsolutePath()); } break; case MENU_VIDEO: file = new File(Constants.getSdCardTmpFile(InsertNote.this)); c = Calendar.getInstance(); newName = String.format("Video_%tY%tm%td_%tH%tM%tS.3gp", c, c, c, c, c, c); newFile = new File(Constants.getSdCardDirectory(InsertNote.this) + newName); file.getParentFile().mkdirs(); isLocal = file.renameTo(newFile); if (!isLocal) { Log.w(TAG, "Failed rename will try copy video: " + file.getAbsolutePath()); isLocal = copyFile(file, newFile); } if (isLocal) { builder = new Uri.Builder(); fileUri = builder.scheme("file").appendPath(newFile.getAbsolutePath()).build(); InsertNote.this.mLoggerServiceManager.storeMediaUri(fileUri); } else { Log.e(TAG, "Failed either rename or copy video: " + file.getAbsolutePath()); } break; case MENU_VOICE: uri = Uri.parse(intent.getDataString()); InsertNote.this.mLoggerServiceManager.storeMediaUri(uri); break; default: Log.e(TAG, "Returned form unknow activity: " + requestCode); break; } } else { Log.w(TAG, "Received unexpected resultcode " + resultCode); } setResult(resultCode, new Intent()); finish(); } }; } @Override protected Dialog onCreateDialog(int id) { Dialog dialog = null; LayoutInflater factory = null; View view = null; Builder builder = null; switch (id) { case DIALOG_INSERTNOTE: builder = new AlertDialog.Builder(this); factory = LayoutInflater.from(this); view = factory.inflate(R.layout.insertnote, null); builder.setTitle(R.string.menu_insertnote).setIcon(android.R.drawable.ic_dialog_alert).setNegativeButton(R.string.btn_cancel, mDialogClickListener) .setView(view); dialog = builder.create(); name = (Button) view.findViewById(R.id.noteinsert_name); text = (Button) view.findViewById(R.id.noteinsert_text); voice = (Button) view.findViewById(R.id.noteinsert_voice); picture = (Button) view.findViewById(R.id.noteinsert_picture); video = (Button) view.findViewById(R.id.noteinsert_video); name.setOnClickListener(mNoteInsertListener); text.setOnClickListener(mNoteInsertListener); voice.setOnClickListener(mNoteInsertListener); picture.setOnClickListener(mNoteInsertListener); video.setOnClickListener(mNoteInsertListener); dialog.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { if (!paused) { finish(); } } }); return dialog; case DIALOG_TEXT: builder = new AlertDialog.Builder(this); factory = LayoutInflater.from(this); view = factory.inflate(R.layout.notetextdialog, null); mNoteTextView = (EditText) view.findViewById(R.id.notetext); builder.setTitle(R.string.dialog_notetext_title).setMessage(R.string.dialog_notetext_message).setIcon(android.R.drawable.ic_dialog_map) .setPositiveButton(R.string.btn_okay, mNoteTextDialogListener).setNegativeButton(R.string.btn_cancel, null).setView(view); dialog = builder.create(); return dialog; case DIALOG_NAME: builder = new AlertDialog.Builder(this); factory = LayoutInflater.from(this); view = factory.inflate(R.layout.notenamedialog, null); mNoteNameView = (EditText) view.findViewById(R.id.notename); builder.setTitle(R.string.dialog_notename_title).setMessage(R.string.dialog_notename_message).setIcon(android.R.drawable.ic_dialog_map) .setPositiveButton(R.string.btn_okay, mNoteNameDialogListener).setNegativeButton(R.string.btn_cancel, null).setView(view); dialog = builder.create(); return dialog; default: return super.onCreateDialog(id); } } /* * (non-Javadoc) * @see android.app.Activity#onPrepareDialog(int, android.app.Dialog) */ @Override protected void onPrepareDialog(int id, Dialog dialog) { switch (id) { case DIALOG_INSERTNOTE: boolean prepared = mLoggerServiceManager.isMediaPrepared() && mLoggerServiceManager.getLoggingState() == Constants.LOGGING; name = (Button) dialog.findViewById(R.id.noteinsert_name); text = (Button) dialog.findViewById(R.id.noteinsert_text); voice = (Button) dialog.findViewById(R.id.noteinsert_voice); picture = (Button) dialog.findViewById(R.id.noteinsert_picture); video = (Button) dialog.findViewById(R.id.noteinsert_video); name.setEnabled(prepared); text.setEnabled(prepared); voice.setEnabled(prepared); picture.setEnabled(prepared); video.setEnabled(prepared); break; default: break; } super.onPrepareDialog(id, dialog); } /*** * Collecting additional data */ private void addPicture() { Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); File file = new File(Constants.getSdCardTmpFile(this)); // Log.d( TAG, "Picture requested at: " + file ); i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); i.putExtra(android.provider.MediaStore.EXTRA_VIDEO_QUALITY, 1); startActivityForResult(i, MENU_PICTURE); } /*** * Collecting additional data */ private void addVideo() { Intent i = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE); File file = new File(Constants.getSdCardTmpFile(this)); i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); i.putExtra(android.provider.MediaStore.EXTRA_VIDEO_QUALITY, 1); try { startActivityForResult(i, MENU_VIDEO); } catch (ActivityNotFoundException e) { Log.e(TAG, "Unable to start Activity to record video", e); } } private void addVoice() { Intent intent = new Intent(android.provider.MediaStore.Audio.Media.RECORD_SOUND_ACTION); try { startActivityForResult(intent, MENU_VOICE); } catch (ActivityNotFoundException e) { Log.e(TAG, "Unable to start Activity to record audio", e); } } private static boolean copyFile(File fileIn, File fileOut) { boolean succes = false; FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream(fileIn); out = new FileOutputStream(fileOut); byte[] buf = new byte[8192]; int i = 0; while ((i = in.read(buf)) != -1) { out.write(buf, 0, i); } succes = true; } catch (IOException e) { Log.e(TAG, "File copy failed", e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { Log.w(TAG, "File close after copy failed", e); } } if (in != null) { try { out.close(); } catch (IOException e) { Log.w(TAG, "File close after copy failed", e); } } } return succes; } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.tasks.GpxCreator; import nl.sogeti.android.gpstracker.actions.tasks.GpxSharing; import nl.sogeti.android.gpstracker.actions.tasks.JogmapSharing; import nl.sogeti.android.gpstracker.actions.tasks.KmzCreator; import nl.sogeti.android.gpstracker.actions.tasks.KmzSharing; import nl.sogeti.android.gpstracker.actions.tasks.OsmSharing; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.actions.utils.StatisticsCalulator; import nl.sogeti.android.gpstracker.actions.utils.StatisticsDelegate; import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsService; import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsService.LocalBinder; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.UnitsI18n; import nl.sogeti.android.gpstracker.viewer.map.LoggerMap; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.IBinder; import android.preference.PreferenceManager; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.RemoteViews; import android.widget.Spinner; import android.widget.Toast; public class ShareTrack extends Activity implements StatisticsDelegate { private static final String TAG = "OGT.ShareTrack"; private static final int EXPORT_TYPE_KMZ = 0; private static final int EXPORT_TYPE_GPX = 1; private static final int EXPORT_TYPE_TEXTLINE = 2; private static final int EXPORT_TARGET_SAVE = 0; private static final int EXPORT_TARGET_SEND = 1; private static final int EXPORT_TARGET_JOGRUN = 2; private static final int EXPORT_TARGET_OSM = 3; private static final int EXPORT_TARGET_BREADCRUMBS = 4; private static final int EXPORT_TARGET_TWITTER = 0; private static final int EXPORT_TARGET_SMS = 1; private static final int EXPORT_TARGET_TEXT = 2; private static final int PROGRESS_STEPS = 10; private static final int DIALOG_ERROR = Menu.FIRST + 28; private static final int DIALOG_CONNECTBREADCRUMBS = Menu.FIRST + 29; private static final int DESCRIBE = 312; private static File sTempBitmap; private RemoteViews mContentView; private int barProgress = 0; private Notification mNotification; private NotificationManager mNotificationManager; private EditText mFileNameView; private EditText mTweetView; private Spinner mShareTypeSpinner; private Spinner mShareTargetSpinner; private Uri mTrackUri; private BreadcrumbsService mService; boolean mBound = false; private String mErrorDialogMessage; private Throwable mErrorDialogException; private ImageView mImageView; private ImageButton mCloseImageView; private Uri mImageUri; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sharedialog); Intent service = new Intent(this, BreadcrumbsService.class); startService(service); mTrackUri = getIntent().getData(); mFileNameView = (EditText) findViewById(R.id.fileNameField); mTweetView = (EditText) findViewById(R.id.tweetField); mImageView = (ImageView) findViewById(R.id.imageView); mCloseImageView = (ImageButton) findViewById(R.id.closeImageView); mShareTypeSpinner = (Spinner) findViewById(R.id.shareTypeSpinner); ArrayAdapter<CharSequence> shareTypeAdapter = ArrayAdapter.createFromResource(this, R.array.sharetype_choices, android.R.layout.simple_spinner_item); shareTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mShareTypeSpinner.setAdapter(shareTypeAdapter); mShareTargetSpinner = (Spinner) findViewById(R.id.shareTargetSpinner); mShareTargetSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView< ? > arg0, View arg1, int position, long arg3) { if (mShareTypeSpinner.getSelectedItemPosition() == EXPORT_TYPE_GPX && position == EXPORT_TARGET_BREADCRUMBS) { boolean authorized = mService.isAuthorized(); if (!authorized) { showDialog(DIALOG_CONNECTBREADCRUMBS); } } else if (mShareTypeSpinner.getSelectedItemPosition() == EXPORT_TYPE_TEXTLINE && position != EXPORT_TARGET_SMS) { readScreenBitmap(); } else { removeScreenBitmap(); } } @Override public void onNothingSelected(AdapterView< ? > arg0) { /* NOOP */ } }); mShareTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView< ? > arg0, View arg1, int position, long arg3) { adjustTargetToType(position); } @Override public void onNothingSelected(AdapterView< ? > arg0) { /* NOOP */ } }); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); int lastType = prefs.getInt(Constants.EXPORT_TYPE, EXPORT_TYPE_KMZ); mShareTypeSpinner.setSelection(lastType); adjustTargetToType(lastType); mFileNameView.setText(queryForTrackName(getContentResolver(), mTrackUri)); Button okay = (Button) findViewById(R.id.okayshare_button); okay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.setEnabled(false); share(); } }); Button cancel = (Button) findViewById(R.id.cancelshare_button); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.setEnabled(false); ShareTrack.this.finish(); } }); } @Override protected void onStart() { super.onStart(); Intent intent = new Intent(this, BreadcrumbsService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } @Override protected void onResume() { super.onResume(); // Upgrade from stored OSM username/password to OAuth authorization SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if (prefs.contains(Constants.OSM_USERNAME) || prefs.contains(Constants.OSM_PASSWORD)) { Editor editor = prefs.edit(); editor.remove(Constants.OSM_USERNAME); editor.remove(Constants.OSM_PASSWORD); editor.commit(); } findViewById(R.id.okayshare_button).setEnabled(true); findViewById(R.id.cancelshare_button).setEnabled(true); } @Override protected void onStop() { if (mBound) { unbindService(mConnection); mBound = false; mService = null; } super.onStop(); } @Override protected void onDestroy() { if (isFinishing()) { Intent service = new Intent(this, BreadcrumbsService.class); stopService(service); } super.onDestroy(); } /** * @see android.app.Activity#onCreateDialog(int) */ @Override protected Dialog onCreateDialog(int id) { Dialog dialog = null; Builder builder = null; switch (id) { case DIALOG_ERROR: builder = new AlertDialog.Builder(this); String exceptionMessage = mErrorDialogException == null ? "" : " (" + mErrorDialogException.getMessage() + ") "; builder.setIcon(android.R.drawable.ic_dialog_alert).setTitle(android.R.string.dialog_alert_title).setMessage(mErrorDialogMessage + exceptionMessage) .setNeutralButton(android.R.string.cancel, null); dialog = builder.create(); return dialog; case DIALOG_CONNECTBREADCRUMBS: builder = new AlertDialog.Builder(this); builder.setTitle(R.string.dialog_breadcrumbsconnect).setMessage(R.string.dialog_breadcrumbsconnect_message).setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.btn_okay, mBreadcrumbsDialogListener).setNegativeButton(R.string.btn_cancel, null); dialog = builder.create(); return dialog; default: return super.onCreateDialog(id); } } /** * @see android.app.Activity#onPrepareDialog(int, android.app.Dialog) */ @Override protected void onPrepareDialog(int id, Dialog dialog) { super.onPrepareDialog(id, dialog); AlertDialog alert; switch (id) { case DIALOG_ERROR: alert = (AlertDialog) dialog; String exceptionMessage = mErrorDialogException == null ? "" : " (" + mErrorDialogException.getMessage() + ") "; alert.setMessage(mErrorDialogMessage + exceptionMessage); break; } } private void setGpxExportTargets() { ArrayAdapter<CharSequence> shareTargetAdapter = ArrayAdapter.createFromResource(this, R.array.sharegpxtarget_choices, android.R.layout.simple_spinner_item); shareTargetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mShareTargetSpinner.setAdapter(shareTargetAdapter); int lastTarget = PreferenceManager.getDefaultSharedPreferences(this).getInt(Constants.EXPORT_GPXTARGET, EXPORT_TARGET_SEND); mShareTargetSpinner.setSelection(lastTarget); removeScreenBitmap(); } private void setKmzExportTargets() { ArrayAdapter<CharSequence> shareTargetAdapter = ArrayAdapter.createFromResource(this, R.array.sharekmztarget_choices, android.R.layout.simple_spinner_item); shareTargetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mShareTargetSpinner.setAdapter(shareTargetAdapter); int lastTarget = PreferenceManager.getDefaultSharedPreferences(this).getInt(Constants.EXPORT_KMZTARGET, EXPORT_TARGET_SEND); mShareTargetSpinner.setSelection(lastTarget); removeScreenBitmap(); } private void setTextLineExportTargets() { ArrayAdapter<CharSequence> shareTargetAdapter = ArrayAdapter.createFromResource(this, R.array.sharetexttarget_choices, android.R.layout.simple_spinner_item); shareTargetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mShareTargetSpinner.setAdapter(shareTargetAdapter); int lastTarget = PreferenceManager.getDefaultSharedPreferences(this).getInt(Constants.EXPORT_TXTTARGET, EXPORT_TARGET_TWITTER); mShareTargetSpinner.setSelection(lastTarget); } private void share() { String chosenFileName = mFileNameView.getText().toString(); String textLine = mTweetView.getText().toString(); int type = (int) mShareTypeSpinner.getSelectedItemId(); int target = (int) mShareTargetSpinner.getSelectedItemId(); Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit(); editor.putInt(Constants.EXPORT_TYPE, type); switch (type) { case EXPORT_TYPE_KMZ: editor.putInt(Constants.EXPORT_KMZTARGET, target); editor.commit(); exportKmz(chosenFileName, target); break; case EXPORT_TYPE_GPX: editor.putInt(Constants.EXPORT_GPXTARGET, target); editor.commit(); exportGpx(chosenFileName, target); break; case EXPORT_TYPE_TEXTLINE: editor.putInt(Constants.EXPORT_TXTTARGET, target); editor.commit(); exportTextLine(textLine, target); break; default: Log.e(TAG, "Failed to determine sharing type" + type); break; } } protected void exportKmz(String chosenFileName, int target) { switch (target) { case EXPORT_TARGET_SEND: new KmzSharing(this, mTrackUri, chosenFileName, new ShareProgressListener(chosenFileName)).execute(); break; case EXPORT_TARGET_SAVE: new KmzCreator(this, mTrackUri, chosenFileName, new ShareProgressListener(chosenFileName)).execute(); break; default: Log.e(TAG, "Unable to determine target for sharing KMZ " + target); break; } ShareTrack.this.finish(); } protected void exportGpx(String chosenFileName, int target) { switch (target) { case EXPORT_TARGET_SAVE: new GpxCreator(this, mTrackUri, chosenFileName, true, new ShareProgressListener(chosenFileName)).execute(); ShareTrack.this.finish(); break; case EXPORT_TARGET_SEND: new GpxSharing(this, mTrackUri, chosenFileName, true, new ShareProgressListener(chosenFileName)).execute(); ShareTrack.this.finish(); break; case EXPORT_TARGET_JOGRUN: new JogmapSharing(this, mTrackUri, chosenFileName, false, new ShareProgressListener(chosenFileName)).execute(); ShareTrack.this.finish(); break; case EXPORT_TARGET_OSM: new OsmSharing(this, mTrackUri, false, new ShareProgressListener(OsmSharing.OSM_FILENAME)).execute(); ShareTrack.this.finish(); break; case EXPORT_TARGET_BREADCRUMBS: sendToBreadcrumbs(mTrackUri, chosenFileName); break; default: Log.e(TAG, "Unable to determine target for sharing GPX " + target); break; } } protected void exportTextLine(String message, int target) { String subject = "Open GPS Tracker"; switch (target) { case EXPORT_TARGET_TWITTER: sendTweet(message); break; case EXPORT_TARGET_SMS: sendSMS(message); ShareTrack.this.finish(); break; case EXPORT_TARGET_TEXT: sentGenericText(subject, message); ShareTrack.this.finish(); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != RESULT_CANCELED) { String name; switch (requestCode) { case DESCRIBE: Uri trackUri = data.getData(); if (data.getExtras() != null && data.getExtras().containsKey(Constants.NAME)) { name = data.getExtras().getString(Constants.NAME); } else { name = "shareToGobreadcrumbs"; } mService.startUploadTask(this, new ShareProgressListener(name), trackUri, name); finish(); break; default: super.onActivityResult(requestCode, resultCode, data); break; } } } private void sendTweet(String tweet) { final Intent intent = findTwitterClient(); intent.putExtra(Intent.EXTRA_TEXT, tweet); if (mImageUri != null) { intent.putExtra(Intent.EXTRA_STREAM, mImageUri); } startActivity(intent); ShareTrack.this.finish(); } private void sendSMS(String msg) { final Intent intent = new Intent(Intent.ACTION_VIEW); intent.setType("vnd.android-dir/mms-sms"); intent.putExtra("sms_body", msg); startActivity(intent); } private void sentGenericText(String subject, String msg) { final Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_SUBJECT, subject); intent.putExtra(Intent.EXTRA_TEXT, msg); if (mImageUri != null) { intent.putExtra(Intent.EXTRA_STREAM, mImageUri); } startActivity(intent); } private void sendToBreadcrumbs(Uri mTrackUri, String chosenFileName) { // Start a description of the track Intent namingIntent = new Intent(this, DescribeTrack.class); namingIntent.setData(mTrackUri); namingIntent.putExtra(Constants.NAME, chosenFileName); startActivityForResult(namingIntent, DESCRIBE); } private Intent findTwitterClient() { final String[] twitterApps = { // package // name "com.twitter.android", // official "com.twidroid", // twidroyd "com.handmark.tweetcaster", // Tweecaster "com.thedeck.android" // TweetDeck }; Intent tweetIntent = new Intent(Intent.ACTION_SEND); tweetIntent.setType("text/plain"); final PackageManager packageManager = getPackageManager(); List<ResolveInfo> list = packageManager.queryIntentActivities(tweetIntent, PackageManager.MATCH_DEFAULT_ONLY); for (int i = 0; i < twitterApps.length; i++) { for (ResolveInfo resolveInfo : list) { String p = resolveInfo.activityInfo.packageName; if (p != null && p.startsWith(twitterApps[i])) { tweetIntent.setPackage(p); } } } return tweetIntent; } private void createTweetText() { StatisticsCalulator calculator = new StatisticsCalulator(this, new UnitsI18n(this), this); findViewById(R.id.tweet_progress).setVisibility(View.VISIBLE); calculator.execute(mTrackUri); } @Override public void finishedCalculations(StatisticsCalulator calculated) { String name = queryForTrackName(getContentResolver(), mTrackUri); String distString = calculated.getDistanceText(); String avgSpeed = calculated.getAvgSpeedText(); String duration = calculated.getDurationText(); String tweetText = String.format(getString(R.string.tweettext, name, distString, avgSpeed, duration)); if (mTweetView.getText().toString().equals("")) { mTweetView.setText(tweetText); } findViewById(R.id.tweet_progress).setVisibility(View.GONE); } private void adjustTargetToType(int position) { switch (position) { case EXPORT_TYPE_KMZ: setKmzExportTargets(); mFileNameView.setVisibility(View.VISIBLE); mTweetView.setVisibility(View.GONE); break; case EXPORT_TYPE_GPX: setGpxExportTargets(); mFileNameView.setVisibility(View.VISIBLE); mTweetView.setVisibility(View.GONE); break; case EXPORT_TYPE_TEXTLINE: setTextLineExportTargets(); mFileNameView.setVisibility(View.GONE); mTweetView.setVisibility(View.VISIBLE); createTweetText(); break; default: break; } } public static void sendFile(Context context, Uri fileUri, String fileContentType, String body) { Intent sendActionIntent = new Intent(Intent.ACTION_SEND); sendActionIntent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.email_subject)); sendActionIntent.putExtra(Intent.EXTRA_TEXT, body); sendActionIntent.putExtra(Intent.EXTRA_STREAM, fileUri); sendActionIntent.setType(fileContentType); context.startActivity(Intent.createChooser(sendActionIntent, context.getString(R.string.sender_chooser))); } public static String queryForTrackName(ContentResolver resolver, Uri trackUri) { Cursor trackCursor = null; String name = null; try { trackCursor = resolver.query(trackUri, new String[] { Tracks.NAME }, null, null, null); if (trackCursor.moveToFirst()) { name = trackCursor.getString(0); } } finally { if (trackCursor != null) { trackCursor.close(); } } return name; } public static Uri storeScreenBitmap(Bitmap bm) { Uri fileUri = null; FileOutputStream stream = null; try { clearScreenBitmap(); sTempBitmap = File.createTempFile("shareimage", ".png"); fileUri = Uri.fromFile(sTempBitmap); stream = new FileOutputStream(sTempBitmap); bm.compress(CompressFormat.PNG, 100, stream); } catch (IOException e) { Log.e(TAG, "Bitmap extra storing failed", e); } finally { try { if (stream != null) { stream.close(); } } catch (IOException e) { Log.e(TAG, "Bitmap extra close failed", e); } } return fileUri; } public static void clearScreenBitmap() { if (sTempBitmap != null && sTempBitmap.exists()) { sTempBitmap.delete(); sTempBitmap = null; } } private void readScreenBitmap() { mImageView.setVisibility(View.GONE); mCloseImageView.setVisibility(View.GONE); if (getIntent().getExtras() != null && getIntent().hasExtra(Intent.EXTRA_STREAM)) { mImageUri = getIntent().getExtras().getParcelable(Intent.EXTRA_STREAM); if (mImageUri != null) { InputStream is = null; try { is = getContentResolver().openInputStream(mImageUri); mImageView.setImageBitmap(BitmapFactory.decodeStream(is)); mImageView.setVisibility(View.VISIBLE); mCloseImageView.setVisibility(View.VISIBLE); mCloseImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { removeScreenBitmap(); } }); } catch (FileNotFoundException e) { Log.e(TAG, "Failed reading image from file", e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { Log.e(TAG, "Failed close image from file", e); } } } } } } private void removeScreenBitmap() { mImageView.setVisibility(View.GONE); mCloseImageView.setVisibility(View.GONE); mImageUri = null; } private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { // We've bound to LocalService, cast the IBinder and get LocalService instance LocalBinder binder = (LocalBinder) service; mService = binder.getService(); mBound = true; } @Override public void onServiceDisconnected(ComponentName arg0) { mBound = false; mService = null; } }; private OnClickListener mBreadcrumbsDialogListener = new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mService.collectBreadcrumbsOauthToken(); } }; public class ShareProgressListener implements ProgressListener { private String mFileName; private int mProgress; public ShareProgressListener(String sharename) { mFileName = sharename; } public void startNotification() { String ns = Context.NOTIFICATION_SERVICE; mNotificationManager = (NotificationManager) ShareTrack.this.getSystemService(ns); int icon = android.R.drawable.ic_menu_save; CharSequence tickerText = getString(R.string.ticker_saving) + "\"" + mFileName + "\""; mNotification = new Notification(); PendingIntent contentIntent = PendingIntent.getActivity(ShareTrack.this, 0, new Intent(ShareTrack.this, LoggerMap.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK), PendingIntent.FLAG_UPDATE_CURRENT); mNotification.contentIntent = contentIntent; mNotification.tickerText = tickerText; mNotification.icon = icon; mNotification.flags |= Notification.FLAG_ONGOING_EVENT; mContentView = new RemoteViews(getPackageName(), R.layout.savenotificationprogress); mContentView.setImageViewResource(R.id.icon, icon); mContentView.setTextViewText(R.id.progresstext, tickerText); mNotification.contentView = mContentView; } private void updateNotification() { // Log.d( "TAG", "Progress " + progress + " of " + goal ); if (mProgress > 0 && mProgress < Window.PROGRESS_END) { if ((mProgress * PROGRESS_STEPS) / Window.PROGRESS_END != barProgress) { barProgress = (mProgress * PROGRESS_STEPS) / Window.PROGRESS_END; mContentView.setProgressBar(R.id.progress, Window.PROGRESS_END, mProgress, false); mNotificationManager.notify(R.layout.savenotificationprogress, mNotification); } } else if (mProgress == 0) { mContentView.setProgressBar(R.id.progress, Window.PROGRESS_END, mProgress, true); mNotificationManager.notify(R.layout.savenotificationprogress, mNotification); } else if (mProgress >= Window.PROGRESS_END) { mContentView.setProgressBar(R.id.progress, Window.PROGRESS_END, mProgress, false); mNotificationManager.notify(R.layout.savenotificationprogress, mNotification); } } public void endNotification(Uri file) { mNotificationManager.cancel(R.layout.savenotificationprogress); } @Override public void setIndeterminate(boolean indeterminate) { Log.w(TAG, "Unsupported indeterminate progress display"); } @Override public void started() { startNotification(); } @Override public void setProgress(int value) { mProgress = value; updateNotification(); } @Override public void finished(Uri result) { endNotification(result); } @Override public void showError(String task, String errorDialogMessage, Exception errorDialogException) { endNotification(null); mErrorDialogMessage = errorDialogMessage; mErrorDialogException = errorDialogException; if (!isFinishing()) { showDialog(DIALOG_ERROR); } else { Toast toast = Toast.makeText(ShareTrack.this, errorDialogMessage, Toast.LENGTH_LONG); toast.show(); } } } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.logger; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Date; import java.util.LinkedList; import java.util.Queue; import java.util.Timer; import java.util.TimerTask; import java.util.Vector; import java.util.concurrent.Semaphore; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.db.GPStracking.Media; import nl.sogeti.android.gpstracker.db.GPStracking.MetaData; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints; import nl.sogeti.android.gpstracker.streaming.StreamUtils; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.viewer.map.CommonLoggerMap; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.database.Cursor; import android.location.GpsSatellite; import android.location.GpsStatus; import android.location.GpsStatus.Listener; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationProvider; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.RingtoneManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.Message; import android.os.PowerManager; import android.os.RemoteException; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; /** * A system service as controlling the background logging of gps locations. * * @version $Id$ * @author rene (c) Jan 22, 2009, Sogeti B.V. */ public class GPSLoggerService extends Service implements LocationListener { private static final float FINE_DISTANCE = 5F; private static final long FINE_INTERVAL = 1000l; private static final float FINE_ACCURACY = 20f; private static final float NORMAL_DISTANCE = 10F; private static final long NORMAL_INTERVAL = 15000l; private static final float NORMAL_ACCURACY = 30f; private static final float COARSE_DISTANCE = 25F; private static final long COARSE_INTERVAL = 30000l; private static final float COARSE_ACCURACY = 75f; private static final float GLOBAL_DISTANCE = 500F; private static final long GLOBAL_INTERVAL = 300000l; private static final float GLOBAL_ACCURACY = 1000f; /** * <code>MAX_REASONABLE_SPEED</code> is about 324 kilometer per hour or 201 * mile per hour. */ private static final int MAX_REASONABLE_SPEED = 90; /** * <code>MAX_REASONABLE_ALTITUDECHANGE</code> between the last few waypoints * and a new one the difference should be less then 200 meter. */ private static final int MAX_REASONABLE_ALTITUDECHANGE = 200; private static final Boolean DEBUG = false; private static final boolean VERBOSE = false; private static final String TAG = "OGT.GPSLoggerService"; private static final String SERVICESTATE_DISTANCE = "SERVICESTATE_DISTANCE"; private static final String SERVICESTATE_STATE = "SERVICESTATE_STATE"; private static final String SERVICESTATE_PRECISION = "SERVICESTATE_PRECISION"; private static final String SERVICESTATE_SEGMENTID = "SERVICESTATE_SEGMENTID"; private static final String SERVICESTATE_TRACKID = "SERVICESTATE_TRACKID"; private static final int ADDGPSSTATUSLISTENER = 0; private static final int REQUEST_FINEGPS_LOCATIONUPDATES = 1; private static final int REQUEST_NORMALGPS_LOCATIONUPDATES = 2; private static final int REQUEST_COARSEGPS_LOCATIONUPDATES = 3; private static final int REQUEST_GLOBALNETWORK_LOCATIONUPDATES = 4; private static final int REQUEST_CUSTOMGPS_LOCATIONUPDATES = 5; private static final int STOPLOOPER = 6; private static final int GPSPROBLEM = 7; private static final int LOGGING_UNAVAILABLE = R.string.service_connectiondisabled; /** * DUP from android.app.Service.START_STICKY */ private static final int START_STICKY = 1; public static final String COMMAND = "nl.sogeti.android.gpstracker.extra.COMMAND"; public static final int EXTRA_COMMAND_START = 0; public static final int EXTRA_COMMAND_PAUSE = 1; public static final int EXTRA_COMMAND_RESUME = 2; public static final int EXTRA_COMMAND_STOP = 3; private LocationManager mLocationManager; private NotificationManager mNoticationManager; private PowerManager.WakeLock mWakeLock; private Handler mHandler; /** * If speeds should be checked to sane values */ private boolean mSpeedSanityCheck; /** * If broadcasts of location about should be sent to stream location */ private boolean mStreamBroadcast; private long mTrackId = -1; private long mSegmentId = -1; private long mWaypointId = -1; private int mPrecision; private int mLoggingState = Constants.STOPPED; private boolean mStartNextSegment; private String mSources; private Location mPreviousLocation; private float mDistance; private Notification mNotification; private Vector<Location> mWeakLocations; private Queue<Double> mAltitudes; /** * <code>mAcceptableAccuracy</code> indicates the maximum acceptable accuracy * of a waypoint in meters. */ private float mMaxAcceptableAccuracy = 20; private int mSatellites = 0; private boolean mShowingGpsDisabled; /** * Should the GPS Status monitor update the notification bar */ private boolean mStatusMonitor; /** * Time thread to runs tasks that check whether the GPS listener has received * enough to consider the GPS system alive. */ private Timer mHeartbeatTimer; /** * Listens to changes in preference to precision and sanity checks */ private OnSharedPreferenceChangeListener mSharedPreferenceChangeListener = new OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(Constants.PRECISION) || key.equals(Constants.LOGGING_DISTANCE) || key.equals(Constants.LOGGING_INTERVAL)) { sendRequestLocationUpdatesMessage(); crashProtectState(); updateNotification(); broadCastLoggingState(); } else if (key.equals(Constants.SPEEDSANITYCHECK)) { mSpeedSanityCheck = sharedPreferences.getBoolean(Constants.SPEEDSANITYCHECK, true); } else if (key.equals(Constants.STATUS_MONITOR)) { mLocationManager.removeGpsStatusListener(mStatusListener); sendRequestStatusUpdateMessage(); updateNotification(); } else if(key.equals(Constants.BROADCAST_STREAM) || key.equals("VOICEOVER_ENABLED") || key.equals("CUSTOMUPLOAD_ENABLED") ) { if (key.equals(Constants.BROADCAST_STREAM)) { mStreamBroadcast = sharedPreferences.getBoolean(Constants.BROADCAST_STREAM, false); } StreamUtils.shutdownStreams(GPSLoggerService.this); if( !mStreamBroadcast ) { StreamUtils.initStreams(GPSLoggerService.this); } } } }; @Override public void onLocationChanged(Location location) { if (VERBOSE) { Log.v(TAG, "onLocationChanged( Location " + location + " )"); } ; // Might be claiming GPS disabled but when we were paused this changed and this location proves so if (mShowingGpsDisabled) { notifyOnEnabledProviderNotification(R.string.service_gpsenabled); } Location filteredLocation = locationFilter(location); if (filteredLocation != null) { if (mStartNextSegment) { mStartNextSegment = false; // Obey the start segment if the previous location is unknown or far away if (mPreviousLocation == null || filteredLocation.distanceTo(mPreviousLocation) > 4 * mMaxAcceptableAccuracy) { startNewSegment(); } } else if( mPreviousLocation != null ) { mDistance += mPreviousLocation.distanceTo(filteredLocation); } storeLocation(filteredLocation); broadcastLocation(filteredLocation); mPreviousLocation = location; } } @Override public void onProviderDisabled(String provider) { if (DEBUG) { Log.d(TAG, "onProviderDisabled( String " + provider + " )"); } ; if (mPrecision != Constants.LOGGING_GLOBAL && provider.equals(LocationManager.GPS_PROVIDER)) { notifyOnDisabledProvider(R.string.service_gpsdisabled); } else if (mPrecision == Constants.LOGGING_GLOBAL && provider.equals(LocationManager.NETWORK_PROVIDER)) { notifyOnDisabledProvider(R.string.service_datadisabled); } } @Override public void onProviderEnabled(String provider) { if (DEBUG) { Log.d(TAG, "onProviderEnabled( String " + provider + " )"); } ; if (mPrecision != Constants.LOGGING_GLOBAL && provider.equals(LocationManager.GPS_PROVIDER)) { notifyOnEnabledProviderNotification(R.string.service_gpsenabled); mStartNextSegment = true; } else if (mPrecision == Constants.LOGGING_GLOBAL && provider.equals(LocationManager.NETWORK_PROVIDER)) { notifyOnEnabledProviderNotification(R.string.service_dataenabled); } } @Override public void onStatusChanged(String provider, int status, Bundle extras) { if (DEBUG) { Log.d(TAG, "onStatusChanged( String " + provider + ", int " + status + ", Bundle " + extras + " )"); } ; if (status == LocationProvider.OUT_OF_SERVICE) { Log.e(TAG, String.format("Provider %s changed to status %d", provider, status)); } } /** * Listens to GPS status changes */ private Listener mStatusListener = new GpsStatus.Listener() { @Override public synchronized void onGpsStatusChanged(int event) { switch (event) { case GpsStatus.GPS_EVENT_SATELLITE_STATUS: if (mStatusMonitor) { GpsStatus status = mLocationManager.getGpsStatus(null); mSatellites = 0; Iterable<GpsSatellite> list = status.getSatellites(); for (GpsSatellite satellite : list) { if (satellite.usedInFix()) { mSatellites++; } } updateNotification(); } break; case GpsStatus.GPS_EVENT_STOPPED: break; case GpsStatus.GPS_EVENT_STARTED: break; default: break; } } }; private IBinder mBinder = new IGPSLoggerServiceRemote.Stub() { @Override public int loggingState() throws RemoteException { return mLoggingState; } @Override public long startLogging() throws RemoteException { GPSLoggerService.this.startLogging(); return mTrackId; } @Override public void pauseLogging() throws RemoteException { GPSLoggerService.this.pauseLogging(); } @Override public long resumeLogging() throws RemoteException { GPSLoggerService.this.resumeLogging(); return mSegmentId; } @Override public void stopLogging() throws RemoteException { GPSLoggerService.this.stopLogging(); } @Override public Uri storeMediaUri(Uri mediaUri) throws RemoteException { GPSLoggerService.this.storeMediaUri(mediaUri); return null; } @Override public boolean isMediaPrepared() throws RemoteException { return GPSLoggerService.this.isMediaPrepared(); } @Override public void storeDerivedDataSource(String sourceName) throws RemoteException { GPSLoggerService.this.storeDerivedDataSource(sourceName); } @Override public Location getLastWaypoint() throws RemoteException { return GPSLoggerService.this.getLastWaypoint(); } @Override public float getTrackedDistance() throws RemoteException { return GPSLoggerService.this.getTrackedDistance(); } }; /** * Task that will be run periodically during active logging to verify that * the logging really happens and that the GPS hasn't silently stopped. */ private TimerTask mHeartbeat = null; /** * Task to determine if the GPS is alive */ class Heartbeat extends TimerTask { private String mProvider; public Heartbeat(String provider) { mProvider = provider; } @Override public void run() { if (isLogging()) { // Collect the last location from the last logged location or a more recent from the last weak location Location checkLocation = mPreviousLocation; synchronized (mWeakLocations) { if (!mWeakLocations.isEmpty()) { if (checkLocation == null) { checkLocation = mWeakLocations.lastElement(); } else { Location weakLocation = mWeakLocations.lastElement(); checkLocation = weakLocation.getTime() > checkLocation.getTime() ? weakLocation : checkLocation; } } } // Is the last known GPS location something nearby we are not told? Location managerLocation = mLocationManager.getLastKnownLocation(mProvider); if (managerLocation != null && checkLocation != null) { if (checkLocation.distanceTo(managerLocation) < 2 * mMaxAcceptableAccuracy) { checkLocation = managerLocation.getTime() > checkLocation.getTime() ? managerLocation : checkLocation; } } if (checkLocation == null || checkLocation.getTime() + mCheckPeriod < new Date().getTime()) { Log.w(TAG, "GPS system failed to produce a location during logging: " + checkLocation); mLoggingState = Constants.PAUSED; resumeLogging(); if (mStatusMonitor) { soundGpsSignalAlarm(); } } } } }; /** * Number of milliseconds that a functioning GPS system needs to provide a * location. Calculated to be either 120 seconds or 4 times the requested * period, whichever is larger. */ private long mCheckPeriod; private float mBroadcastDistance; private long mLastTimeBroadcast; private class GPSLoggerServiceThread extends Thread { public Semaphore ready = new Semaphore(0); GPSLoggerServiceThread() { this.setName("GPSLoggerServiceThread"); } @Override public void run() { Looper.prepare(); mHandler = new Handler() { @Override public void handleMessage(Message msg) { _handleMessage(msg); } }; ready.release(); // Signal the looper and handler are created Looper.loop(); } } /** * Called by the system when the service is first created. Do not call this * method directly. Be sure to call super.onCreate(). */ @Override public void onCreate() { super.onCreate(); if (DEBUG) { Log.d(TAG, "onCreate()"); } ; GPSLoggerServiceThread looper = new GPSLoggerServiceThread(); looper.start(); try { looper.ready.acquire(); } catch (InterruptedException e) { Log.e(TAG, "Interrupted during wait for the GPSLoggerServiceThread to start, prepare for trouble!", e); } mHeartbeatTimer = new Timer("heartbeat", true); mWeakLocations = new Vector<Location>(3); mAltitudes = new LinkedList<Double>(); mLoggingState = Constants.STOPPED; mStartNextSegment = false; mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); mNoticationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); stopNotification(); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); mSpeedSanityCheck = sharedPreferences.getBoolean(Constants.SPEEDSANITYCHECK, true); mStreamBroadcast = sharedPreferences.getBoolean(Constants.BROADCAST_STREAM, false); boolean startImmidiatly = PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Constants.LOGATSTARTUP, false); crashRestoreState(); if (startImmidiatly && mLoggingState == Constants.STOPPED) { startLogging(); ContentValues values = new ContentValues(); values.put(Tracks.NAME, "Recorded at startup"); getContentResolver().update(ContentUris.withAppendedId(Tracks.CONTENT_URI, mTrackId), values, null, null); } else { broadCastLoggingState(); } } /** * This is the old onStart method that will be called on the pre-2.0 * * @see android.app.Service#onStart(android.content.Intent, int) platform. On * 2.0 or later we override onStartCommand() so this method will not be * called. */ @Override public void onStart(Intent intent, int startId) { handleCommand(intent); } @Override public int onStartCommand(Intent intent, int flags, int startId) { handleCommand(intent); // We want this service to continue running until it is explicitly // stopped, so return sticky. return START_STICKY; } private void handleCommand(Intent intent) { if (DEBUG) { Log.d(TAG, "handleCommand(Intent " + intent + ")"); } ; if (intent != null && intent.hasExtra(COMMAND)) { switch (intent.getIntExtra(COMMAND, -1)) { case EXTRA_COMMAND_START: startLogging(); break; case EXTRA_COMMAND_PAUSE: pauseLogging(); break; case EXTRA_COMMAND_RESUME: resumeLogging(); break; case EXTRA_COMMAND_STOP: stopLogging(); break; default: break; } } } /** * (non-Javadoc) * * @see android.app.Service#onDestroy() */ @Override public void onDestroy() { if (DEBUG) { Log.d(TAG, "onDestroy()"); } ; super.onDestroy(); if (isLogging()) { Log.w(TAG, "Destroyin an activly logging service"); } mHeartbeatTimer.cancel(); mHeartbeatTimer.purge(); if (this.mWakeLock != null) { this.mWakeLock.release(); this.mWakeLock = null; } PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this.mSharedPreferenceChangeListener); mLocationManager.removeGpsStatusListener(mStatusListener); stopListening(); mNoticationManager.cancel(R.layout.map_widgets); Message msg = Message.obtain(); msg.what = STOPLOOPER; mHandler.sendMessage(msg); } private void crashProtectState() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); Editor editor = preferences.edit(); editor.putLong(SERVICESTATE_TRACKID, mTrackId); editor.putLong(SERVICESTATE_SEGMENTID, mSegmentId); editor.putInt(SERVICESTATE_PRECISION, mPrecision); editor.putInt(SERVICESTATE_STATE, mLoggingState); editor.putFloat(SERVICESTATE_DISTANCE, mDistance); editor.commit(); if (DEBUG) { Log.d(TAG, "crashProtectState()"); } ; } private synchronized void crashRestoreState() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); long previousState = preferences.getInt(SERVICESTATE_STATE, Constants.STOPPED); if (previousState == Constants.LOGGING || previousState == Constants.PAUSED) { Log.w(TAG, "Recovering from a crash or kill and restoring state."); startNotification(); mTrackId = preferences.getLong(SERVICESTATE_TRACKID, -1); mSegmentId = preferences.getLong(SERVICESTATE_SEGMENTID, -1); mPrecision = preferences.getInt(SERVICESTATE_PRECISION, -1); mDistance = preferences.getFloat(SERVICESTATE_DISTANCE, 0F); if (previousState == Constants.LOGGING) { mLoggingState = Constants.PAUSED; resumeLogging(); } else if (previousState == Constants.PAUSED) { mLoggingState = Constants.LOGGING; pauseLogging(); } } } /** * (non-Javadoc) * * @see android.app.Service#onBind(android.content.Intent) */ @Override public IBinder onBind(Intent intent) { return this.mBinder; } /** * (non-Javadoc) * * @see nl.sogeti.android.gpstracker.IGPSLoggerService#getLoggingState() */ protected boolean isLogging() { return this.mLoggingState == Constants.LOGGING; } /** * Provides the cached last stored waypoint it current logging is active alse * null. * * @return last waypoint location or null */ protected Location getLastWaypoint() { Location myLastWaypoint = null; if (isLogging()) { myLastWaypoint = mPreviousLocation; } return myLastWaypoint; } public float getTrackedDistance() { float distance = 0F; if (isLogging()) { distance = mDistance; } return distance; } protected boolean isMediaPrepared() { return !(mTrackId < 0 || mSegmentId < 0 || mWaypointId < 0); } /** * (non-Javadoc) * * @see nl.sogeti.android.gpstracker.IGPSLoggerService#startLogging() */ public synchronized void startLogging() { if (DEBUG) { Log.d(TAG, "startLogging()"); } ; if (this.mLoggingState == Constants.STOPPED) { startNewTrack(); sendRequestLocationUpdatesMessage(); sendRequestStatusUpdateMessage(); this.mLoggingState = Constants.LOGGING; updateWakeLock(); startNotification(); crashProtectState(); broadCastLoggingState(); } } public synchronized void pauseLogging() { if (DEBUG) { Log.d(TAG, "pauseLogging()"); } ; if (this.mLoggingState == Constants.LOGGING) { mLocationManager.removeGpsStatusListener(mStatusListener); stopListening(); mLoggingState = Constants.PAUSED; mPreviousLocation = null; updateWakeLock(); updateNotification(); mSatellites = 0; updateNotification(); crashProtectState(); broadCastLoggingState(); } } public synchronized void resumeLogging() { if (DEBUG) { Log.d(TAG, "resumeLogging()"); } ; if (this.mLoggingState == Constants.PAUSED) { if (mPrecision != Constants.LOGGING_GLOBAL) { mStartNextSegment = true; } sendRequestLocationUpdatesMessage(); sendRequestStatusUpdateMessage(); this.mLoggingState = Constants.LOGGING; updateWakeLock(); updateNotification(); crashProtectState(); broadCastLoggingState(); } } /** * (non-Javadoc) * * @see nl.sogeti.android.gpstracker.IGPSLoggerService#stopLogging() */ public synchronized void stopLogging() { if (DEBUG) { Log.d(TAG, "stopLogging()"); } ; mLoggingState = Constants.STOPPED; crashProtectState(); updateWakeLock(); PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this.mSharedPreferenceChangeListener); mLocationManager.removeGpsStatusListener(mStatusListener); stopListening(); stopNotification(); broadCastLoggingState(); } private void startListening(String provider, long intervaltime, float distance) { mLocationManager.removeUpdates(this); mLocationManager.requestLocationUpdates(provider, intervaltime, distance, this); mCheckPeriod = Math.max(12 * intervaltime, 120 * 1000); if (mHeartbeat != null) { mHeartbeat.cancel(); mHeartbeat = null; } mHeartbeat = new Heartbeat(provider); mHeartbeatTimer.schedule(mHeartbeat, mCheckPeriod, mCheckPeriod); } private void stopListening() { if (mHeartbeat != null) { mHeartbeat.cancel(); mHeartbeat = null; } mLocationManager.removeUpdates(this); } /** * (non-Javadoc) * * @see nl.sogeti.android.gpstracker.IGPSLoggerService#storeDerivedDataSource(java.lang.String) */ public void storeDerivedDataSource(String sourceName) { Uri trackMetaDataUri = Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/metadata"); if (mTrackId >= 0) { if (mSources == null) { Cursor metaData = null; String source = null; try { metaData = this.getContentResolver().query(trackMetaDataUri, new String[] { MetaData.VALUE }, MetaData.KEY + " = ? ", new String[] { Constants.DATASOURCES_KEY }, null); if (metaData.moveToFirst()) { source = metaData.getString(0); } } finally { if (metaData != null) { metaData.close(); } } if (source != null) { mSources = source; } else { mSources = sourceName; ContentValues args = new ContentValues(); args.put(MetaData.KEY, Constants.DATASOURCES_KEY); args.put(MetaData.VALUE, mSources); this.getContentResolver().insert(trackMetaDataUri, args); } } if (!mSources.contains(sourceName)) { mSources += "," + sourceName; ContentValues args = new ContentValues(); args.put(MetaData.VALUE, mSources); this.getContentResolver().update(trackMetaDataUri, args, MetaData.KEY + " = ? ", new String[] { Constants.DATASOURCES_KEY }); } } } private void startNotification() { mNoticationManager.cancel(R.layout.map_widgets); int icon = R.drawable.ic_maps_indicator_current_position; CharSequence tickerText = getResources().getString(R.string.service_start); long when = System.currentTimeMillis(); mNotification = new Notification(icon, tickerText, when); mNotification.flags |= Notification.FLAG_ONGOING_EVENT; updateNotification(); if (Build.VERSION.SDK_INT >= 5) { startForegroundReflected(R.layout.map_widgets, mNotification); } else { mNoticationManager.notify(R.layout.map_widgets, mNotification); } } private void updateNotification() { CharSequence contentTitle = getResources().getString(R.string.app_name); String precision = getResources().getStringArray(R.array.precision_choices)[mPrecision]; String state = getResources().getStringArray(R.array.state_choices)[mLoggingState - 1]; CharSequence contentText; switch (mPrecision) { case (Constants.LOGGING_GLOBAL): contentText = getResources().getString(R.string.service_networkstatus, state, precision); break; default: if (mStatusMonitor) { contentText = getResources().getString(R.string.service_gpsstatus, state, precision, mSatellites); } else { contentText = getResources().getString(R.string.service_gpsnostatus, state, precision); } break; } Intent notificationIntent = new Intent(this, CommonLoggerMap.class); notificationIntent.setData(ContentUris.withAppendedId(Tracks.CONTENT_URI, mTrackId)); mNotification.contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK); mNotification.setLatestEventInfo(this, contentTitle, contentText, mNotification.contentIntent); mNoticationManager.notify(R.layout.map_widgets, mNotification); } private void stopNotification() { if (Build.VERSION.SDK_INT >= 5) { stopForegroundReflected(true); } else { mNoticationManager.cancel(R.layout.map_widgets); } } private void notifyOnEnabledProviderNotification(int resId) { mNoticationManager.cancel(LOGGING_UNAVAILABLE); mShowingGpsDisabled = false; CharSequence text = this.getString(resId); Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG); toast.show(); } private void notifyOnPoorSignal(int resId) { int icon = R.drawable.ic_maps_indicator_current_position; CharSequence tickerText = getResources().getString(resId); long when = System.currentTimeMillis(); Notification signalNotification = new Notification(icon, tickerText, when); CharSequence contentTitle = getResources().getString(R.string.app_name); Intent notificationIntent = new Intent(this, CommonLoggerMap.class); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK); signalNotification.setLatestEventInfo(this, contentTitle, tickerText, contentIntent); signalNotification.flags |= Notification.FLAG_AUTO_CANCEL; mNoticationManager.notify(resId, signalNotification); } private void notifyOnDisabledProvider(int resId) { int icon = R.drawable.ic_maps_indicator_current_position; CharSequence tickerText = getResources().getString(resId); long when = System.currentTimeMillis(); Notification gpsNotification = new Notification(icon, tickerText, when); gpsNotification.flags |= Notification.FLAG_AUTO_CANCEL; CharSequence contentTitle = getResources().getString(R.string.app_name); CharSequence contentText = getResources().getString(resId); Intent notificationIntent = new Intent(this, CommonLoggerMap.class); notificationIntent.setData(ContentUris.withAppendedId(Tracks.CONTENT_URI, mTrackId)); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK); gpsNotification.setLatestEventInfo(this, contentTitle, contentText, contentIntent); mNoticationManager.notify(LOGGING_UNAVAILABLE, gpsNotification); mShowingGpsDisabled = true; } /** * Send a system broadcast to notify a change in the logging or precision */ private void broadCastLoggingState() { Intent broadcast = new Intent(Constants.LOGGING_STATE_CHANGED_ACTION); broadcast.putExtra(Constants.EXTRA_LOGGING_PRECISION, mPrecision); broadcast.putExtra(Constants.EXTRA_LOGGING_STATE, mLoggingState); this.getApplicationContext().sendBroadcast(broadcast); if( isLogging() ) { StreamUtils.initStreams(this); } else { StreamUtils.shutdownStreams(this); } } private void sendRequestStatusUpdateMessage() { mStatusMonitor = PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Constants.STATUS_MONITOR, false); Message msg = Message.obtain(); msg.what = ADDGPSSTATUSLISTENER; mHandler.sendMessage(msg); } private void sendRequestLocationUpdatesMessage() { stopListening(); mPrecision = Integer.valueOf(PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.PRECISION, "2")).intValue(); Message msg = Message.obtain(); switch (mPrecision) { case (Constants.LOGGING_FINE): // Fine msg.what = REQUEST_FINEGPS_LOCATIONUPDATES; mHandler.sendMessage(msg); break; case (Constants.LOGGING_NORMAL): // Normal msg.what = REQUEST_NORMALGPS_LOCATIONUPDATES; mHandler.sendMessage(msg); break; case (Constants.LOGGING_COARSE): // Coarse msg.what = REQUEST_COARSEGPS_LOCATIONUPDATES; mHandler.sendMessage(msg); break; case (Constants.LOGGING_GLOBAL): // Global msg.what = REQUEST_GLOBALNETWORK_LOCATIONUPDATES; mHandler.sendMessage(msg); break; case (Constants.LOGGING_CUSTOM): // Global msg.what = REQUEST_CUSTOMGPS_LOCATIONUPDATES; mHandler.sendMessage(msg); break; default: Log.e(TAG, "Unknown precision " + mPrecision); break; } } /** * Message handler method to do the work off-loaded by mHandler to * GPSLoggerServiceThread * * @param msg */ private void _handleMessage(Message msg) { if (DEBUG) { Log.d(TAG, "_handleMessage( Message " + msg + " )"); } ; long intervaltime = 0; float distance = 0; switch (msg.what) { case ADDGPSSTATUSLISTENER: this.mLocationManager.addGpsStatusListener(mStatusListener); break; case REQUEST_FINEGPS_LOCATIONUPDATES: mMaxAcceptableAccuracy = FINE_ACCURACY; intervaltime = FINE_INTERVAL; distance = FINE_DISTANCE; startListening(LocationManager.GPS_PROVIDER, intervaltime, distance); break; case REQUEST_NORMALGPS_LOCATIONUPDATES: mMaxAcceptableAccuracy = NORMAL_ACCURACY; intervaltime = NORMAL_INTERVAL; distance = NORMAL_DISTANCE; startListening(LocationManager.GPS_PROVIDER, intervaltime, distance); break; case REQUEST_COARSEGPS_LOCATIONUPDATES: mMaxAcceptableAccuracy = COARSE_ACCURACY; intervaltime = COARSE_INTERVAL; distance = COARSE_DISTANCE; startListening(LocationManager.GPS_PROVIDER, intervaltime, distance); break; case REQUEST_GLOBALNETWORK_LOCATIONUPDATES: mMaxAcceptableAccuracy = GLOBAL_ACCURACY; intervaltime = GLOBAL_INTERVAL; distance = GLOBAL_DISTANCE; startListening(LocationManager.NETWORK_PROVIDER, intervaltime, distance); if (!isNetworkConnected()) { notifyOnDisabledProvider(R.string.service_connectiondisabled); } break; case REQUEST_CUSTOMGPS_LOCATIONUPDATES: intervaltime = 60 * 1000 * Long.valueOf(PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.LOGGING_INTERVAL, "15000")); distance = Float.valueOf(PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.LOGGING_DISTANCE, "10")); mMaxAcceptableAccuracy = Math.max(10f, Math.min(distance, 50f)); startListening(LocationManager.GPS_PROVIDER, intervaltime, distance); break; case STOPLOOPER: mLocationManager.removeGpsStatusListener(mStatusListener); stopListening(); Looper.myLooper().quit(); break; case GPSPROBLEM: notifyOnPoorSignal(R.string.service_gpsproblem); break; } } private void updateWakeLock() { if (this.mLoggingState == Constants.LOGGING) { PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(mSharedPreferenceChangeListener); PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE); if (this.mWakeLock != null) { this.mWakeLock.release(); this.mWakeLock = null; } this.mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); this.mWakeLock.acquire(); } else { if (this.mWakeLock != null) { this.mWakeLock.release(); this.mWakeLock = null; } } } /** * Some GPS waypoints received are of to low a quality for tracking use. Here * we filter those out. * * @param proposedLocation * @return either the (cleaned) original or null when unacceptable */ public Location locationFilter(Location proposedLocation) { // Do no include log wrong 0.0 lat 0.0 long, skip to next value in while-loop if (proposedLocation != null && (proposedLocation.getLatitude() == 0.0d || proposedLocation.getLongitude() == 0.0d)) { Log.w(TAG, "A wrong location was received, 0.0 latitude and 0.0 longitude... "); proposedLocation = null; } // Do not log a waypoint which is more inaccurate then is configured to be acceptable if (proposedLocation != null && proposedLocation.getAccuracy() > mMaxAcceptableAccuracy) { Log.w(TAG, String.format("A weak location was received, lots of inaccuracy... (%f is more then max %f)", proposedLocation.getAccuracy(), mMaxAcceptableAccuracy)); proposedLocation = addBadLocation(proposedLocation); } // Do not log a waypoint which might be on any side of the previous waypoint if (proposedLocation != null && mPreviousLocation != null && proposedLocation.getAccuracy() > mPreviousLocation.distanceTo(proposedLocation)) { Log.w(TAG, String.format("A weak location was received, not quite clear from the previous waypoint... (%f more then max %f)", proposedLocation.getAccuracy(), mPreviousLocation.distanceTo(proposedLocation))); proposedLocation = addBadLocation(proposedLocation); } // Speed checks, check if the proposed location could be reached from the previous one in sane speed // Common to jump on network logging and sometimes jumps on Samsung Galaxy S type of devices if (mSpeedSanityCheck && proposedLocation != null && mPreviousLocation != null) { // To avoid near instant teleportation on network location or glitches cause continent hopping float meters = proposedLocation.distanceTo(mPreviousLocation); long seconds = (proposedLocation.getTime() - mPreviousLocation.getTime()) / 1000L; float speed = meters / seconds; if (speed > MAX_REASONABLE_SPEED) { Log.w(TAG, "A strange location was received, a really high speed of " + speed + " m/s, prob wrong..."); proposedLocation = addBadLocation(proposedLocation); // Might be a messed up Samsung Galaxy S GPS, reset the logging if (speed > 2 * MAX_REASONABLE_SPEED && mPrecision != Constants.LOGGING_GLOBAL) { Log.w(TAG, "A strange location was received on GPS, reset the GPS listeners"); stopListening(); mLocationManager.removeGpsStatusListener(mStatusListener); mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); sendRequestStatusUpdateMessage(); sendRequestLocationUpdatesMessage(); } } } // Remove speed if not sane if (mSpeedSanityCheck && proposedLocation != null && proposedLocation.getSpeed() > MAX_REASONABLE_SPEED) { Log.w(TAG, "A strange speed, a really high speed, prob wrong..."); proposedLocation.removeSpeed(); } // Remove altitude if not sane if (mSpeedSanityCheck && proposedLocation != null && proposedLocation.hasAltitude()) { if (!addSaneAltitude(proposedLocation.getAltitude())) { Log.w(TAG, "A strange altitude, a really big difference, prob wrong..."); proposedLocation.removeAltitude(); } } // Older bad locations will not be needed if (proposedLocation != null) { mWeakLocations.clear(); } return proposedLocation; } /** * Store a bad location, when to many bad locations are stored the the * storage is cleared and the least bad one is returned * * @param location bad location * @return null when the bad location is stored or the least bad one if the * storage was full */ private Location addBadLocation(Location location) { mWeakLocations.add(location); if (mWeakLocations.size() < 3) { location = null; } else { Location best = mWeakLocations.lastElement(); for (Location whimp : mWeakLocations) { if (whimp.hasAccuracy() && best.hasAccuracy() && whimp.getAccuracy() < best.getAccuracy()) { best = whimp; } else { if (whimp.hasAccuracy() && !best.hasAccuracy()) { best = whimp; } } } synchronized (mWeakLocations) { mWeakLocations.clear(); } location = best; } return location; } /** * Builds a bit of knowledge about altitudes to expect and return if the * added value is deemed sane. * * @param altitude * @return whether the altitude is considered sane */ private boolean addSaneAltitude(double altitude) { boolean sane = true; double avg = 0; int elements = 0; // Even insane altitude shifts increases alter perception mAltitudes.add(altitude); if (mAltitudes.size() > 3) { mAltitudes.poll(); } for (Double alt : mAltitudes) { avg += alt; elements++; } avg = avg / elements; sane = Math.abs(altitude - avg) < MAX_REASONABLE_ALTITUDECHANGE; return sane; } /** * Trigged by events that start a new track */ private void startNewTrack() { mDistance = 0; Uri newTrack = this.getContentResolver().insert(Tracks.CONTENT_URI, new ContentValues(0)); mTrackId = Long.valueOf(newTrack.getLastPathSegment()).longValue(); startNewSegment(); } /** * Trigged by events that start a new segment */ private void startNewSegment() { this.mPreviousLocation = null; Uri newSegment = this.getContentResolver().insert(Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/segments"), new ContentValues(0)); mSegmentId = Long.valueOf(newSegment.getLastPathSegment()).longValue(); crashProtectState(); } protected void storeMediaUri(Uri mediaUri) { if (isMediaPrepared()) { Uri mediaInsertUri = Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/segments/" + mSegmentId + "/waypoints/" + mWaypointId + "/media"); ContentValues args = new ContentValues(); args.put(Media.URI, mediaUri.toString()); this.getContentResolver().insert(mediaInsertUri, args); } else { Log.e(TAG, "No logging done under which to store the track"); } } /** * Use the ContentResolver mechanism to store a received location * * @param location */ public void storeLocation(Location location) { if (!isLogging()) { Log.e(TAG, String.format("Not logging but storing location %s, prepare to fail", location.toString())); } ContentValues args = new ContentValues(); args.put(Waypoints.LATITUDE, Double.valueOf(location.getLatitude())); args.put(Waypoints.LONGITUDE, Double.valueOf(location.getLongitude())); args.put(Waypoints.SPEED, Float.valueOf(location.getSpeed())); args.put(Waypoints.TIME, Long.valueOf(System.currentTimeMillis())); if (location.hasAccuracy()) { args.put(Waypoints.ACCURACY, Float.valueOf(location.getAccuracy())); } if (location.hasAltitude()) { args.put(Waypoints.ALTITUDE, Double.valueOf(location.getAltitude())); } if (location.hasBearing()) { args.put(Waypoints.BEARING, Float.valueOf(location.getBearing())); } Uri waypointInsertUri = Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/segments/" + mSegmentId + "/waypoints"); Uri inserted = this.getContentResolver().insert(waypointInsertUri, args); mWaypointId = Long.parseLong(inserted.getLastPathSegment()); } /** * Consult broadcast options and execute broadcast if necessary * * @param location */ public void broadcastLocation(Location location) { Intent intent = new Intent(Constants.STREAMBROADCAST); if (mStreamBroadcast) { final long minDistance = (long) PreferenceManager.getDefaultSharedPreferences(this).getFloat("streambroadcast_distance_meter", 5000F); final long minTime = 60000 * Long.parseLong(PreferenceManager.getDefaultSharedPreferences(this).getString("streambroadcast_time", "1")); final long nowTime = location.getTime(); if (mPreviousLocation != null) { mBroadcastDistance += location.distanceTo(mPreviousLocation); } if (mLastTimeBroadcast == 0) { mLastTimeBroadcast = nowTime; } long passedTime = (nowTime - mLastTimeBroadcast); intent.putExtra(Constants.EXTRA_DISTANCE, (int) mBroadcastDistance); intent.putExtra(Constants.EXTRA_TIME, (int) passedTime/60000); intent.putExtra(Constants.EXTRA_LOCATION, location); intent.putExtra(Constants.EXTRA_TRACK, ContentUris.withAppendedId(Tracks.CONTENT_URI, mTrackId)); boolean distanceBroadcast = minDistance > 0 && mBroadcastDistance >= minDistance; boolean timeBroadcast = minTime > 0 && passedTime >= minTime; if (distanceBroadcast || timeBroadcast) { if (distanceBroadcast) { mBroadcastDistance = 0; } if (timeBroadcast) { mLastTimeBroadcast = nowTime; } this.sendBroadcast(intent, "android.permission.ACCESS_FINE_LOCATION"); } } } private boolean isNetworkConnected() { ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = connMgr.getActiveNetworkInfo(); return (info != null && info.isConnected()); } private void soundGpsSignalAlarm() { Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); if (alert == null) { alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); if (alert == null) { alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE); } } MediaPlayer mMediaPlayer = new MediaPlayer(); try { mMediaPlayer.setDataSource(GPSLoggerService.this, alert); final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) { mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); mMediaPlayer.setLooping(false); mMediaPlayer.prepare(); mMediaPlayer.start(); } } catch (IllegalArgumentException e) { Log.e(TAG, "Problem setting data source for mediaplayer", e); } catch (SecurityException e) { Log.e(TAG, "Problem setting data source for mediaplayer", e); } catch (IllegalStateException e) { Log.e(TAG, "Problem with mediaplayer", e); } catch (IOException e) { Log.e(TAG, "Problem with mediaplayer", e); } Message msg = Message.obtain(); msg.what = GPSPROBLEM; mHandler.sendMessage(msg); } @SuppressWarnings("rawtypes") private void startForegroundReflected(int id, Notification notification) { Method mStartForeground; Class[] mStartForegroundSignature = new Class[] { int.class, Notification.class }; Object[] mStartForegroundArgs = new Object[2]; mStartForegroundArgs[0] = Integer.valueOf(id); mStartForegroundArgs[1] = notification; try { mStartForeground = getClass().getMethod("startForeground", mStartForegroundSignature); mStartForeground.invoke(this, mStartForegroundArgs); } catch (NoSuchMethodException e) { Log.e(TAG, "Failed starting foreground notification using reflection", e); } catch (IllegalArgumentException e) { Log.e(TAG, "Failed starting foreground notification using reflection", e); } catch (IllegalAccessException e) { Log.e(TAG, "Failed starting foreground notification using reflection", e); } catch (InvocationTargetException e) { Log.e(TAG, "Failed starting foreground notification using reflection", e); } } @SuppressWarnings("rawtypes") private void stopForegroundReflected(boolean b) { Class[] mStopForegroundSignature = new Class[] { boolean.class }; Method mStopForeground; Object[] mStopForegroundArgs = new Object[1]; mStopForegroundArgs[0] = Boolean.TRUE; try { mStopForeground = getClass().getMethod("stopForeground", mStopForegroundSignature); mStopForeground.invoke(this, mStopForegroundArgs); } catch (NoSuchMethodException e) { Log.e(TAG, "Failed stopping foreground notification using reflection", e); } catch (IllegalArgumentException e) { Log.e(TAG, "Failed stopping foreground notification using reflection", e); } catch (IllegalAccessException e) { Log.e(TAG, "Failed stopping foreground notification using reflection", e); } catch (InvocationTargetException e) { Log.e(TAG, "Failed stopping foreground notification using reflection", e); } } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.logger; import nl.sogeti.android.gpstracker.util.Constants; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.location.Location; import android.net.Uri; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; /** * Class to interact with the service that tracks and logs the locations * * @version $Id$ * @author rene (c) Jan 18, 2009, Sogeti B.V. */ public class GPSLoggerServiceManager { private static final String TAG = "OGT.GPSLoggerServiceManager"; private static final String REMOTE_EXCEPTION = "REMOTE_EXCEPTION"; private IGPSLoggerServiceRemote mGPSLoggerRemote; public final Object mStartLock = new Object(); private boolean mBound = false; /** * Class for interacting with the main interface of the service. */ private ServiceConnection mServiceConnection; private Runnable mOnServiceConnected; public GPSLoggerServiceManager(Context ctx) { ctx.startService(new Intent(Constants.SERVICENAME)); } public Location getLastWaypoint() { synchronized (mStartLock) { Location lastWaypoint = null; try { if( mBound ) { lastWaypoint = this.mGPSLoggerRemote.getLastWaypoint(); } else { Log.w( TAG, "Remote interface to logging service not found. Started: " + mBound ); } } catch (RemoteException e) { Log.e( TAG, "Could get lastWaypoint GPSLoggerService.", e ); } return lastWaypoint; } } public float getTrackedDistance() { synchronized (mStartLock) { float distance = 0F; try { if( mBound ) { distance = this.mGPSLoggerRemote.getTrackedDistance(); } else { Log.w( TAG, "Remote interface to logging service not found. Started: " + mBound ); } } catch (RemoteException e) { Log.e( TAG, "Could get tracked distance from GPSLoggerService.", e ); } return distance; } } public int getLoggingState() { synchronized (mStartLock) { int logging = Constants.UNKNOWN; try { if( mBound ) { logging = this.mGPSLoggerRemote.loggingState(); // Log.d( TAG, "mGPSLoggerRemote tells state to be "+logging ); } else { Log.w( TAG, "Remote interface to logging service not found. Started: " + mBound ); } } catch (RemoteException e) { Log.e( TAG, "Could stat GPSLoggerService.", e ); } return logging; } } public boolean isMediaPrepared() { synchronized (mStartLock) { boolean prepared = false; try { if( mBound ) { prepared = this.mGPSLoggerRemote.isMediaPrepared(); } else { Log.w( TAG, "Remote interface to logging service not found. Started: " + mBound ); } } catch (RemoteException e) { Log.e( TAG, "Could stat GPSLoggerService.", e ); } return prepared; } } public long startGPSLogging( String name ) { synchronized (mStartLock) { if( mBound ) { try { return this.mGPSLoggerRemote.startLogging(); } catch (RemoteException e) { Log.e( TAG, "Could not start GPSLoggerService.", e ); } } return -1; } } public void pauseGPSLogging() { synchronized (mStartLock) { if( mBound ) { try { this.mGPSLoggerRemote.pauseLogging(); } catch (RemoteException e) { Log.e( TAG, "Could not start GPSLoggerService.", e ); } } } } public long resumeGPSLogging() { synchronized (mStartLock) { if( mBound ) { try { return this.mGPSLoggerRemote.resumeLogging(); } catch (RemoteException e) { Log.e( TAG, "Could not start GPSLoggerService.", e ); } } return -1; } } public void stopGPSLogging() { synchronized (mStartLock) { if( mBound ) { try { this.mGPSLoggerRemote.stopLogging(); } catch (RemoteException e) { Log.e( GPSLoggerServiceManager.REMOTE_EXCEPTION, "Could not stop GPSLoggerService.", e ); } } else { Log.e( TAG, "No GPSLoggerRemote service connected to this manager" ); } } } public void storeDerivedDataSource( String datasource ) { synchronized (mStartLock) { if( mBound ) { try { this.mGPSLoggerRemote.storeDerivedDataSource( datasource ); } catch (RemoteException e) { Log.e( GPSLoggerServiceManager.REMOTE_EXCEPTION, "Could not send datasource to GPSLoggerService.", e ); } } else { Log.e( TAG, "No GPSLoggerRemote service connected to this manager" ); } } } public void storeMediaUri( Uri mediaUri ) { synchronized (mStartLock) { if( mBound ) { try { this.mGPSLoggerRemote.storeMediaUri( mediaUri ); } catch (RemoteException e) { Log.e( GPSLoggerServiceManager.REMOTE_EXCEPTION, "Could not send media to GPSLoggerService.", e ); } } else { Log.e( TAG, "No GPSLoggerRemote service connected to this manager" ); } } } /** * Means by which an Activity lifecycle aware object hints about binding and unbinding * * @param onServiceConnected Run on main thread after the service is bound */ public void startup( Context context, final Runnable onServiceConnected ) { // Log.d( TAG, "connectToGPSLoggerService()" ); synchronized (mStartLock) { if( !mBound ) { mOnServiceConnected = onServiceConnected; mServiceConnection = new ServiceConnection() { @Override public void onServiceConnected( ComponentName className, IBinder service ) { synchronized (mStartLock) { // Log.d( TAG, "onServiceConnected() "+ Thread.currentThread().getId() ); GPSLoggerServiceManager.this.mGPSLoggerRemote = IGPSLoggerServiceRemote.Stub.asInterface( service ); mBound = true; } if( mOnServiceConnected != null ) { mOnServiceConnected.run(); mOnServiceConnected = null; } } @Override public void onServiceDisconnected( ComponentName className ) { synchronized (mStartLock) { // Log.d( TAG, "onServiceDisconnected()"+ Thread.currentThread().getId() ); mBound = false; } } }; context.bindService( new Intent( Constants.SERVICENAME ), this.mServiceConnection, Context.BIND_AUTO_CREATE ); } else { Log.w( TAG, "Attempting to connect whilst already connected" ); } } } /** * Means by which an Activity lifecycle aware object hints about binding and unbinding */ public void shutdown(Context context) { // Log.d( TAG, "disconnectFromGPSLoggerService()" ); synchronized (mStartLock) { try { if( mBound ) { // Log.d( TAG, "unbindService()"+this.mServiceConnection ); context.unbindService( this.mServiceConnection ); GPSLoggerServiceManager.this.mGPSLoggerRemote = null; mServiceConnection = null; mBound = false; } } catch (IllegalArgumentException e) { Log.w( TAG, "Failed to unbind a service, prehaps the service disapearded?", e ); } } } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.streaming; import nl.sogeti.android.gpstracker.util.Constants; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; public class StreamUtils { @SuppressWarnings("unused") private static final String TAG = "OGT.StreamUtils"; /** * Initialize all appropriate stream listeners * @param ctx */ public static void initStreams(final Context ctx) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ctx); boolean streams_enabled = sharedPreferences.getBoolean(Constants.BROADCAST_STREAM, false); if (streams_enabled && sharedPreferences.getBoolean("VOICEOVER_ENABLED", false)) { VoiceOver.initStreaming(ctx); } if (streams_enabled && sharedPreferences.getBoolean("CUSTOMUPLOAD_ENABLED", false)) { CustomUpload.initStreaming(ctx); } } /** * Shutdown all stream listeners * * @param ctx */ public static void shutdownStreams(Context ctx) { VoiceOver.shutdownStreaming(ctx); CustomUpload.shutdownStreaming(ctx); } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.streaming; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.util.Constants; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.speech.tts.TextToSpeech; import android.util.Log; public class VoiceOver extends BroadcastReceiver implements TextToSpeech.OnInitListener { private static VoiceOver sVoiceOver = null; private static final String TAG = "OGT.VoiceOver"; public static synchronized void initStreaming(Context ctx) { if( sVoiceOver != null ) { shutdownStreaming(ctx); } sVoiceOver = new VoiceOver(ctx); IntentFilter filter = new IntentFilter(Constants.STREAMBROADCAST); ctx.registerReceiver(sVoiceOver, filter); } public static synchronized void shutdownStreaming(Context ctx) { if( sVoiceOver != null ) { ctx.unregisterReceiver(sVoiceOver); sVoiceOver.onShutdown(); sVoiceOver = null; } } private TextToSpeech mTextToSpeech; private int mVoiceStatus = -1; private Context mContext; public VoiceOver(Context ctx) { mContext = ctx.getApplicationContext(); mTextToSpeech = new TextToSpeech(mContext, this); } @Override public void onInit(int status) { mVoiceStatus = status; } private void onShutdown() { mVoiceStatus = -1; mTextToSpeech.shutdown(); } @Override public void onReceive(Context context, Intent intent) { if( mVoiceStatus == TextToSpeech.SUCCESS ) { int meters = intent.getIntExtra(Constants.EXTRA_DISTANCE, 0); int minutes = intent.getIntExtra(Constants.EXTRA_TIME, 0); String myText = context.getString(R.string.voiceover_speaking, minutes, meters); mTextToSpeech.speak(myText, TextToSpeech.QUEUE_ADD, null); } else { Log.w(TAG, "Voice stream failed TTS not ready"); } } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.streaming; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.LinkedList; import java.util.Queue; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.viewer.ApplicationPreferenceActivity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.StatusLine; import org.apache.ogt.http.client.ClientProtocolException; import org.apache.ogt.http.client.HttpClient; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.impl.client.DefaultHttpClient; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.location.Location; import android.net.Uri; import android.preference.PreferenceManager; import android.util.Log; public class CustomUpload extends BroadcastReceiver { private static final String CUSTOMUPLOAD_BACKLOG_DEFAULT = "20"; private static CustomUpload sCustomUpload = null; private static final String TAG = "OGT.CustomUpload"; private static final int NOTIFICATION_ID = R.string.customupload_failed; private static Queue<HttpGet> sRequestBacklog = new LinkedList<HttpGet>(); public static synchronized void initStreaming(Context ctx) { if( sCustomUpload != null ) { shutdownStreaming(ctx); } sCustomUpload = new CustomUpload(); sRequestBacklog = new LinkedList<HttpGet>(); IntentFilter filter = new IntentFilter(Constants.STREAMBROADCAST); ctx.registerReceiver(sCustomUpload, filter); } public static synchronized void shutdownStreaming(Context ctx) { if( sCustomUpload != null ) { ctx.unregisterReceiver(sCustomUpload); sCustomUpload.onShutdown(); sCustomUpload = null; } } private void onShutdown() { } @Override public void onReceive(Context context, Intent intent) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); String prefUrl = preferences.getString(ApplicationPreferenceActivity.CUSTOMUPLOAD_URL, "http://www.example.com"); Integer prefBacklog = Integer.valueOf( preferences.getString(ApplicationPreferenceActivity.CUSTOMUPLOAD_BACKLOG, CUSTOMUPLOAD_BACKLOG_DEFAULT) ); Location loc = intent.getParcelableExtra(Constants.EXTRA_LOCATION); Uri trackUri = intent.getParcelableExtra(Constants.EXTRA_TRACK); String buildUrl = prefUrl; buildUrl = buildUrl.replace("@LAT@", Double.toString(loc.getLatitude())); buildUrl = buildUrl.replace("@LON@", Double.toString(loc.getLongitude())); buildUrl = buildUrl.replace("@ID@", trackUri.getLastPathSegment()); buildUrl = buildUrl.replace("@TIME@", Long.toString(loc.getTime())); buildUrl = buildUrl.replace("@SPEED@", Float.toString(loc.getSpeed())); buildUrl = buildUrl.replace("@ACC@", Float.toString(loc.getAccuracy())); buildUrl = buildUrl.replace("@ALT@", Double.toString(loc.getAltitude())); buildUrl = buildUrl.replace("@BEAR@", Float.toString(loc.getBearing())); HttpClient client = new DefaultHttpClient(); URI uploadUri; try { uploadUri = new URI(buildUrl); HttpGet currentRequest = new HttpGet(uploadUri ); sRequestBacklog.add(currentRequest); if( sRequestBacklog.size() > prefBacklog ) { sRequestBacklog.poll(); } while( !sRequestBacklog.isEmpty() ) { HttpGet request = sRequestBacklog.peek(); HttpResponse response = client.execute(request); sRequestBacklog.poll(); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { throw new IOException("Invalid response from server: " + status.toString()); } clearNotification(context); } } catch (URISyntaxException e) { notifyError(context, e); } catch (ClientProtocolException e) { notifyError(context, e); } catch (IOException e) { notifyError(context, e); } } private void notifyError(Context context, Exception e) { Log.e( TAG, "Custom upload failed", e); String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns); int icon = R.drawable.ic_maps_indicator_current_position; CharSequence tickerText = context.getText(R.string.customupload_failed); long when = System.currentTimeMillis(); Notification notification = new Notification(icon, tickerText, when); Context appContext = context.getApplicationContext(); CharSequence contentTitle = tickerText; CharSequence contentText = e.getMessage(); Intent notificationIntent = new Intent(context, CustomUpload.class); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); notification.setLatestEventInfo(appContext, contentTitle, contentText, contentIntent); notification.flags = Notification.FLAG_AUTO_CANCEL; mNotificationManager.notify(NOTIFICATION_ID, notification); } private void clearNotification(Context context) { String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns); mNotificationManager.cancel(NOTIFICATION_ID); } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.breadcrumbs; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OptionalDataException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Observable; import java.util.Set; import nl.sogeti.android.gpstracker.adapter.BreadcrumbsAdapter; import nl.sogeti.android.gpstracker.db.GPStracking.MetaData; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.Pair; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.util.Log; /** * Model containing agregrated data retrieved from the GoBreadcrumbs.com API * * @version $Id:$ * @author rene (c) May 9, 2011, Sogeti B.V. */ public class BreadcrumbsTracks extends Observable { public static final String DESCRIPTION = "DESCRIPTION"; public static final String NAME = "NAME"; public static final String ENDTIME = "ENDTIME"; public static final String TRACK_ID = "BREADCRUMBS_TRACK_ID"; public static final String BUNDLE_ID = "BREADCRUMBS_BUNDLE_ID"; public static final String ACTIVITY_ID = "BREADCRUMBS_ACTIVITY_ID"; public static final String DIFFICULTY = "DIFFICULTY"; public static final String STARTTIME = "STARTTIME"; public static final String ISPUBLIC = "ISPUBLIC"; public static final String RATING = "RATING"; public static final String LATITUDE = "LATITUDE"; public static final String LONGITUDE = "LONGITUDE"; public static final String TOTALDISTANCE = "TOTALDISTANCE"; public static final String TOTALTIME = "TOTALTIME"; private static final String TAG = "OGT.BreadcrumbsTracks"; private static final Integer CACHE_VERSION = Integer.valueOf(3); private static final String BREADCRUMSB_BUNDLES_CACHE_FILE = "breadcrumbs_bundles_cache.data"; private static final String BREADCRUMSB_ACTIVITY_CACHE_FILE = "breadcrumbs_activity_cache.data"; /** * Time in milliseconds that a persisted breadcrumbs cache is used without a refresh */ private static final long CACHE_TIMEOUT = 1000 * 60;//1000*60*10 ; /** * Mapping from bundleId to a list of trackIds */ private static Map<Integer, List<Integer>> sBundlesWithTracks; /** * Map from activityId to a dictionary containing keys like NAME */ private static Map<Integer, Map<String, String>> sActivityMappings; /** * Map from bundleId to a dictionary containing keys like NAME and DESCRIPTION */ private static Map<Integer, Map<String, String>> sBundleMappings; /** * Map from trackId to a dictionary containing keys like NAME, ISPUBLIC, DESCRIPTION and more */ private static Map<Integer, Map<String, String>> sTrackMappings; /** * Cache of OGT Tracks that have a Breadcrumbs track id stored in the meta-data table */ private Map<Long, Integer> mSyncedTracks = null; private static Set<Pair<Integer, Integer>> sScheduledTracksLoading; static { BreadcrumbsTracks.initCacheVariables(); } private static void initCacheVariables() { sBundlesWithTracks = new LinkedHashMap<Integer, List<Integer>>(); sActivityMappings = new HashMap<Integer, Map<String, String>>(); sBundleMappings = new HashMap<Integer, Map<String, String>>(); sTrackMappings = new HashMap<Integer, Map<String, String>>(); sScheduledTracksLoading = new HashSet<Pair<Integer, Integer>>(); } private ContentResolver mResolver; /** * Constructor: create a new BreadcrumbsTracks. * * @param resolver Content resolver to obtain local Breadcrumbs references */ public BreadcrumbsTracks(ContentResolver resolver) { mResolver = resolver; } public void addActivity(Integer activityId, String activityName) { if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "addActivity(Integer " + activityId + " String " + activityName + ")"); } if (!sActivityMappings.containsKey(activityId)) { sActivityMappings.put(activityId, new HashMap<String, String>()); } sActivityMappings.get(activityId).put(NAME, activityName); setChanged(); notifyObservers(); } /** * Add bundle to the track list * * @param activityId * @param bundleId * @param bundleName * @param bundleDescription */ public void addBundle(Integer bundleId, String bundleName, String bundleDescription) { if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "addBundle(Integer " + bundleId + ", String " + bundleName + ", String " + bundleDescription + ")"); } if (!sBundleMappings.containsKey(bundleId)) { sBundleMappings.put(bundleId, new HashMap<String, String>()); } if (!sBundlesWithTracks.containsKey(bundleId)) { sBundlesWithTracks.put(bundleId, new ArrayList<Integer>()); } sBundleMappings.get(bundleId).put(NAME, bundleName); sBundleMappings.get(bundleId).put(DESCRIPTION, bundleDescription); setChanged(); notifyObservers(); } /** * Add track to tracklist * * @param trackId * @param trackName * @param bundleId * @param trackDescription * @param difficulty * @param startTime * @param endTime * @param isPublic * @param lat * @param lng * @param totalDistance * @param totalTime * @param trackRating */ public void addTrack(Integer trackId, String trackName, Integer bundleId, String trackDescription, String difficulty, String startTime, String endTime, String isPublic, Float lat, Float lng, Float totalDistance, Integer totalTime, String trackRating) { if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "addTrack(Integer " + trackId + ", String " + trackName + ", Integer " + bundleId + "..."); } if (!sBundlesWithTracks.containsKey(bundleId)) { sBundlesWithTracks.put(bundleId, new ArrayList<Integer>()); } if (!sBundlesWithTracks.get(bundleId).contains(trackId)) { sBundlesWithTracks.get(bundleId).add(trackId); sScheduledTracksLoading.remove(Pair.create(Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE, trackId)); } if (!sTrackMappings.containsKey(trackId)) { sTrackMappings.put(trackId, new HashMap<String, String>()); } putForTrack(trackId, NAME, trackName); putForTrack(trackId, ISPUBLIC, isPublic); putForTrack(trackId, STARTTIME, startTime); putForTrack(trackId, ENDTIME, endTime); putForTrack(trackId, DESCRIPTION, trackDescription); putForTrack(trackId, DIFFICULTY, difficulty); putForTrack(trackId, RATING, trackRating); putForTrack(trackId, LATITUDE, lat); putForTrack(trackId, LONGITUDE, lng); putForTrack(trackId, TOTALDISTANCE, totalDistance); putForTrack(trackId, TOTALTIME, totalTime); notifyObservers(); } public void addSyncedTrack(Long trackId, Integer bcTrackId) { if (mSyncedTracks == null) { isLocalTrackOnline(-1l); } mSyncedTracks.put(trackId, bcTrackId); setChanged(); notifyObservers(); } public void addTracksLoadingScheduled(Pair<Integer, Integer> item) { sScheduledTracksLoading.add(item); setChanged(); notifyObservers(); } /** * Cleans old bundles based a set of all bundles * * @param mBundleIds */ public void setAllBundleIds(Set<Integer> mBundleIds) { for (Integer oldBundleId : getAllBundleIds()) { if (!mBundleIds.contains(oldBundleId)) { removeBundle(oldBundleId); } } } public void setAllTracksForBundleId(Integer mBundleId, Set<Integer> updatedbcTracksIdList) { List<Integer> trackIdList = sBundlesWithTracks.get(mBundleId); for (int location = 0; location < trackIdList.size(); location++) { Integer oldTrackId = trackIdList.get(location); if (!updatedbcTracksIdList.contains(oldTrackId)) { removeTrack(mBundleId, oldTrackId); } } setChanged(); notifyObservers(); } private void putForTrack(Integer trackId, String key, Object value) { if (value != null) { sTrackMappings.get(trackId).put(key, value.toString()); } setChanged(); notifyObservers(); } /** * Remove a bundle * * @param deletedId */ public void removeBundle(Integer deletedId) { sBundleMappings.remove(deletedId); sBundlesWithTracks.remove(deletedId); setChanged(); notifyObservers(); } /** * Remove a track * * @param deletedId */ public void removeTrack(Integer bundleId, Integer trackId) { sTrackMappings.remove(trackId); if (sBundlesWithTracks.containsKey(bundleId)) { sBundlesWithTracks.get(bundleId).remove(trackId); } setChanged(); notifyObservers(); mResolver.delete(MetaData.CONTENT_URI, MetaData.TRACK + " = ? AND " + MetaData.KEY + " = ? ", new String[] { trackId.toString(), TRACK_ID }); if (mSyncedTracks != null && mSyncedTracks.containsKey(trackId)) { mSyncedTracks.remove(trackId); } } public int positions() { int size = 0; for (Integer bundleId : sBundlesWithTracks.keySet()) { // One row for the Bundle header size += 1; int bundleSize = sBundlesWithTracks.get(bundleId) != null ? sBundlesWithTracks.get(bundleId).size() : 0; // One row per track in each bundle size += bundleSize; } return size; } public Integer getBundleIdForTrackId(Integer trackId) { for (Integer bundlId : sBundlesWithTracks.keySet()) { List<Integer> trackIds = sBundlesWithTracks.get(bundlId); if (trackIds.contains(trackId)) { return bundlId; } } return null; } public Integer[] getAllActivityIds() { return sActivityMappings.keySet().toArray(new Integer[sActivityMappings.keySet().size()]); } /** * Get all bundles * * @return */ public Integer[] getAllBundleIds() { return sBundlesWithTracks.keySet().toArray(new Integer[sBundlesWithTracks.keySet().size()]); } /** * @param position list postition 0...n * @return a pair of a TYPE and an ID */ public List<Pair<Integer, Integer>> getAllItems() { List<Pair<Integer, Integer>> items = new LinkedList<Pair<Integer, Integer>>(); for (Integer bundleId : sBundlesWithTracks.keySet()) { items.add(Pair.create(Constants.BREADCRUMBS_BUNDLE_ITEM_VIEW_TYPE, bundleId)); for(Integer trackId : sBundlesWithTracks.get(bundleId)) { items.add(Pair.create(Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE, trackId)); } } return items; } public List<Pair<Integer, Integer>> getActivityList() { List<Pair<Integer, Integer>> items = new LinkedList<Pair<Integer, Integer>>(); for (Integer activityId : sActivityMappings.keySet()) { Pair<Integer, Integer> pair = Pair.create(Constants.BREADCRUMBS_ACTIVITY_ITEM_VIEW_TYPE, activityId); pair.overrideToString(getValueForItem(pair, NAME)); items.add(pair); } return items; } public List<Pair<Integer, Integer>> getBundleList() { List<Pair<Integer, Integer>> items = new LinkedList<Pair<Integer, Integer>>(); for (Integer bundleId : sBundleMappings.keySet()) { Pair<Integer, Integer> pair = Pair.create(Constants.BREADCRUMBS_BUNDLE_ITEM_VIEW_TYPE, bundleId); pair.overrideToString(getValueForItem(pair, NAME)); items.add(pair); } return items; } public String getValueForItem(Pair<Integer, Integer> item, String key) { String value = null; switch (item.first) { case Constants.BREADCRUMBS_BUNDLE_ITEM_VIEW_TYPE: value = sBundleMappings.get(item.second).get(key); break; case Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE: value = sTrackMappings.get(item.second).get(key); break; case Constants.BREADCRUMBS_ACTIVITY_ITEM_VIEW_TYPE: value = sActivityMappings.get(item.second).get(key); break; default: value = null; break; } return value; } private boolean isLocalTrackOnline(Long qtrackId) { if (mSyncedTracks == null) { mSyncedTracks = new HashMap<Long, Integer>(); Cursor cursor = null; try { cursor = mResolver.query(MetaData.CONTENT_URI, new String[] { MetaData.TRACK, MetaData.VALUE }, MetaData.KEY + " = ? ", new String[] { TRACK_ID }, null); if (cursor.moveToFirst()) { do { Long trackId = cursor.getLong(0); try { Integer bcTrackId = Integer.valueOf(cursor.getString(1)); mSyncedTracks.put(trackId, bcTrackId); } catch (NumberFormatException e) { Log.w(TAG, "Illigal value stored as track id", e); } } while (cursor.moveToNext()); } } finally { if (cursor != null) { cursor.close(); } } setChanged(); notifyObservers(); } boolean synced = mSyncedTracks.containsKey(qtrackId); return synced; } public boolean isLocalTrackSynced(Long qtrackId) { boolean uploaded = isLocalTrackOnline(qtrackId); boolean synced = sTrackMappings.containsKey(mSyncedTracks.get(qtrackId)); return uploaded && synced; } public boolean areTracksLoaded(Pair<Integer, Integer> item) { return sBundlesWithTracks.containsKey(item.second) && item.first == Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE; } public boolean areTracksLoadingScheduled(Pair<Integer, Integer> item) { return sScheduledTracksLoading.contains(item); } /** * Read the static breadcrumbs data from private file * * @param ctx * @return is refresh is needed */ @SuppressWarnings("unchecked") public boolean readCache(Context ctx) { FileInputStream fis = null; ObjectInputStream ois = null; Date bundlesPersisted = null, activitiesPersisted = null; Object[] cache; synchronized (BREADCRUMSB_BUNDLES_CACHE_FILE) { try { fis = ctx.openFileInput(BREADCRUMSB_BUNDLES_CACHE_FILE); ois = new ObjectInputStream(fis); cache = (Object[]) ois.readObject(); // new Object[] { CACHE_VERSION, new Date(), sActivitiesWithBundles, sBundlesWithTracks, sBundleMappings, sTrackMappings }; if (cache[0] instanceof Integer && CACHE_VERSION.equals(cache[0])) { bundlesPersisted = (Date) cache[1]; Map<Integer, List<Integer>> bundles = (Map<Integer, List<Integer>>) cache[2]; Map<Integer, Map<String, String>> bundlemappings = (Map<Integer, Map<String, String>>) cache[3]; Map<Integer, Map<String, String>> trackmappings = (Map<Integer, Map<String, String>>) cache[4]; sBundlesWithTracks = bundles != null ? bundles : sBundlesWithTracks; sBundleMappings = bundlemappings != null ? bundlemappings : sBundleMappings; sTrackMappings = trackmappings != null ? trackmappings : sTrackMappings; } else { clearPersistentCache(ctx); } fis = ctx.openFileInput(BREADCRUMSB_ACTIVITY_CACHE_FILE); ois = new ObjectInputStream(fis); cache = (Object[]) ois.readObject(); // new Object[] { CACHE_VERSION, new Date(), sActivityMappings }; if (cache[0] instanceof Integer && CACHE_VERSION.equals(cache[0])) { activitiesPersisted = (Date) cache[1]; Map<Integer, Map<String, String>> activitymappings = (Map<Integer, Map<String, String>>) cache[2]; sActivityMappings = activitymappings != null ? activitymappings : sActivityMappings; } else { clearPersistentCache(ctx); } } catch (OptionalDataException e) { clearPersistentCache(ctx); Log.w(TAG, "Unable to read persisted breadcrumbs cache", e); } catch (ClassNotFoundException e) { clearPersistentCache(ctx); Log.w(TAG, "Unable to read persisted breadcrumbs cache", e); } catch (IOException e) { clearPersistentCache(ctx); Log.w(TAG, "Unable to read persisted breadcrumbs cache", e); } catch (ClassCastException e) { clearPersistentCache(ctx); Log.w(TAG, "Unable to read persisted breadcrumbs cache", e); } catch (ArrayIndexOutOfBoundsException e) { clearPersistentCache(ctx); Log.w(TAG, "Unable to read persisted breadcrumbs cache", e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { Log.w(TAG, "Error closing file stream after reading cache", e); } } if (ois != null) { try { ois.close(); } catch (IOException e) { Log.w(TAG, "Error closing object stream after reading cache", e); } } } } setChanged(); notifyObservers(); boolean refreshNeeded = false; refreshNeeded = refreshNeeded || bundlesPersisted == null || activitiesPersisted == null; refreshNeeded = refreshNeeded || (activitiesPersisted.getTime() < new Date().getTime() - CACHE_TIMEOUT * 10); refreshNeeded = refreshNeeded || (bundlesPersisted.getTime() < new Date().getTime() - CACHE_TIMEOUT); return refreshNeeded; } public void persistCache(Context ctx) { FileOutputStream fos = null; ObjectOutputStream oos = null; Object[] cache; synchronized (BREADCRUMSB_BUNDLES_CACHE_FILE) { try { fos = ctx.openFileOutput(BREADCRUMSB_BUNDLES_CACHE_FILE, Context.MODE_PRIVATE); oos = new ObjectOutputStream(fos); cache = new Object[] { CACHE_VERSION, new Date(), sBundlesWithTracks, sBundleMappings, sTrackMappings }; oos.writeObject(cache); fos = ctx.openFileOutput(BREADCRUMSB_ACTIVITY_CACHE_FILE, Context.MODE_PRIVATE); oos = new ObjectOutputStream(fos); cache = new Object[] { CACHE_VERSION, new Date(), sActivityMappings }; oos.writeObject(cache); } catch (FileNotFoundException e) { Log.e(TAG, "Error in file stream during persist cache", e); } catch (IOException e) { Log.e(TAG, "Error in object stream during persist cache", e); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { Log.w(TAG, "Error closing file stream after writing cache", e); } } if (oos != null) { try { oos.close(); } catch (IOException e) { Log.w(TAG, "Error closing object stream after writing cache", e); } } } } } public void clearAllCache(Context ctx) { BreadcrumbsTracks.initCacheVariables(); setChanged(); clearPersistentCache(ctx); notifyObservers(); } public void clearPersistentCache(Context ctx) { Log.w(TAG, "Deleting old Breadcrumbs cache files"); synchronized (BREADCRUMSB_BUNDLES_CACHE_FILE) { ctx.deleteFile(BREADCRUMSB_ACTIVITY_CACHE_FILE); ctx.deleteFile(BREADCRUMSB_BUNDLES_CACHE_FILE); } } @Override public String toString() { return "BreadcrumbsTracks [mActivityMappings=" + sActivityMappings + ", mBundleMappings=" + sBundleMappings + ", mTrackMappings=" + sTrackMappings + ", mActivities=" + sActivityMappings + ", mBundles=" + sBundlesWithTracks + "]"; } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.breadcrumbs; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.tasks.XmlCreator; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.adapter.BreadcrumbsAdapter; import oauth.signpost.OAuthConsumer; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.client.methods.HttpUriRequest; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.util.EntityUtils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import android.content.Context; import android.util.Log; /** * An asynchronous task that communicates with Twitter to retrieve a request * token. (OAuthGetRequestToken) After receiving the request token from Twitter, * pop a browser to the user to authorize the Request Token. * (OAuthAuthorizeToken) */ public class GetBreadcrumbsBundlesTask extends BreadcrumbsTask { final String TAG = "OGT.GetBreadcrumbsBundlesTask"; private OAuthConsumer mConsumer; private DefaultHttpClient mHttpclient; private Set<Integer> mBundleIds; private LinkedList<Object[]> mBundles; /** * We pass the OAuth consumer and provider. * * @param mContext Required to be able to start the intent to launch the * browser. * @param httpclient * @param listener * @param provider The OAuthProvider object * @param mConsumer The OAuthConsumer object */ public GetBreadcrumbsBundlesTask(Context context, BreadcrumbsService adapter, ProgressListener listener, DefaultHttpClient httpclient, OAuthConsumer consumer) { super(context, adapter, listener); mHttpclient = httpclient; mConsumer = consumer; } /** * Retrieve the OAuth Request Token and present a browser to the user to * authorize the token. */ @Override protected Void doInBackground(Void... params) { HttpEntity responseEntity = null; mBundleIds = new HashSet<Integer>(); mBundles = new LinkedList<Object[]>(); try { HttpUriRequest request = new HttpGet("http://api.gobreadcrumbs.com/v1/bundles.xml"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } mConsumer.sign(request); if( BreadcrumbsAdapter.DEBUG ) { Log.d( TAG, "Execute request: "+request.getURI() ); for( Header header : request.getAllHeaders() ) { Log.d( TAG, " with header: "+header.toString()); } } HttpResponse response = mHttpclient.execute(request); responseEntity = response.getEntity(); InputStream is = responseEntity.getContent(); InputStream stream = new BufferedInputStream(is, 8192); if( BreadcrumbsAdapter.DEBUG ) { stream = XmlCreator.convertStreamToLoggedStream(TAG, stream); } XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(stream, "UTF-8"); String tagName = null; int eventType = xpp.getEventType(); String bundleName = null, bundleDescription = null; Integer bundleId = null; while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { tagName = xpp.getName(); } else if (eventType == XmlPullParser.END_TAG) { if ("bundle".equals(xpp.getName()) && bundleId != null) { mBundles.add( new Object[]{bundleId, bundleName, bundleDescription} ); } tagName = null; } else if (eventType == XmlPullParser.TEXT) { if ("description".equals(tagName)) { bundleDescription = xpp.getText(); } else if ("id".equals(tagName)) { bundleId = Integer.parseInt(xpp.getText()); mBundleIds.add(bundleId); } else if ("name".equals(tagName)) { bundleName = xpp.getText(); } } eventType = xpp.next(); } } catch (OAuthMessageSignerException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "Failed to sign the request with authentication signature"); } catch (OAuthExpectationFailedException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "The request did not authenticate"); } catch (OAuthCommunicationException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "The authentication communication failed"); } catch (IOException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "A problem during communication"); } catch (XmlPullParserException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "A problem while reading the XML data"); } catch (IllegalStateException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "A problem during communication"); } finally { if (responseEntity != null) { try { EntityUtils.consume(responseEntity); } catch (IOException e) { Log.w(TAG, "Failed closing inputstream"); } } } return null; } @Override protected void updateTracksData(BreadcrumbsTracks tracks) { tracks.setAllBundleIds( mBundleIds ); for( Object[] bundle : mBundles ) { Integer bundleId = (Integer) bundle[0]; String bundleName = (String) bundle[1]; String bundleDescription = (String) bundle[2]; tracks.addBundle(bundleId, bundleName, bundleDescription); } } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.breadcrumbs; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.LinkedList; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.tasks.XmlCreator; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.adapter.BreadcrumbsAdapter; import nl.sogeti.android.gpstracker.util.Pair; import oauth.signpost.OAuthConsumer; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.client.methods.HttpUriRequest; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.util.EntityUtils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import android.content.Context; import android.util.Log; /** * An asynchronous task that communicates with Twitter to retrieve a request * token. (OAuthGetRequestToken) After receiving the request token from Twitter, * pop a browser to the user to authorize the Request Token. * (OAuthAuthorizeToken) */ public class GetBreadcrumbsActivitiesTask extends BreadcrumbsTask { private LinkedList<Pair<Integer, String>> mActivities; final String TAG = "OGT.GetBreadcrumbsActivitiesTask"; private OAuthConsumer mConsumer; private DefaultHttpClient mHttpClient; /** * We pass the OAuth consumer and provider. * * @param mContext Required to be able to start the intent to launch the * browser. * @param httpclient * @param provider The OAuthProvider object * @param mConsumer The OAuthConsumer object */ public GetBreadcrumbsActivitiesTask(Context context, BreadcrumbsService adapter, ProgressListener listener, DefaultHttpClient httpclient, OAuthConsumer consumer) { super(context, adapter, listener); mHttpClient = httpclient; mConsumer = consumer; } /** * Retrieve the OAuth Request Token and present a browser to the user to * authorize the token. */ @Override protected Void doInBackground(Void... params) { mActivities = new LinkedList<Pair<Integer,String>>(); HttpEntity responseEntity = null; try { HttpUriRequest request = new HttpGet("http://api.gobreadcrumbs.com/v1/activities.xml"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } mConsumer.sign(request); if( BreadcrumbsAdapter.DEBUG ) { Log.d( TAG, "Execute request: "+request.getURI() ); for( Header header : request.getAllHeaders() ) { Log.d( TAG, " with header: "+header.toString()); } } HttpResponse response = mHttpClient.execute(request); responseEntity = response.getEntity(); InputStream is = responseEntity.getContent(); InputStream stream = new BufferedInputStream(is, 8192); if( BreadcrumbsAdapter.DEBUG ) { stream = XmlCreator.convertStreamToLoggedStream(TAG, stream); } XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(stream, "UTF-8"); String tagName = null; int eventType = xpp.getEventType(); String activityName = null; Integer activityId = null; while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { tagName = xpp.getName(); } else if (eventType == XmlPullParser.END_TAG) { if ("activity".equals(xpp.getName()) && activityId != null && activityName != null) { mActivities.add(new Pair<Integer, String>(activityId, activityName)); } tagName = null; } else if (eventType == XmlPullParser.TEXT) { if ("id".equals(tagName)) { activityId = Integer.parseInt(xpp.getText()); } else if ("name".equals(tagName)) { activityName = xpp.getText(); } } eventType = xpp.next(); } } catch (OAuthMessageSignerException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_activity), e, "Failed to sign the request with authentication signature"); } catch (OAuthExpectationFailedException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_activity), e, "The request did not authenticate"); } catch (OAuthCommunicationException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_activity), e, "The authentication communication failed"); } catch (IOException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_activity), e, "A problem during communication"); } catch (XmlPullParserException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_activity), e, "A problem while reading the XML data"); } finally { if (responseEntity != null) { try { EntityUtils.consume(responseEntity); } catch (IOException e) { Log.e(TAG, "Failed to close the content stream", e); } } } return null; } @Override protected void updateTracksData( BreadcrumbsTracks tracks ) { for( Pair<Integer, String> activity : mActivities ) { tracks.addActivity(activity.first, activity.second); } } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.breadcrumbs; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.tasks.XmlCreator; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.adapter.BreadcrumbsAdapter; import oauth.signpost.OAuthConsumer; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.client.methods.HttpUriRequest; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.util.EntityUtils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import android.content.Context; import android.util.Log; /** * An asynchronous task that communicates with Twitter to retrieve a request * token. (OAuthGetRequestToken) After receiving the request token from Twitter, * pop a browser to the user to authorize the Request Token. * (OAuthAuthorizeToken) */ public class GetBreadcrumbsTracksTask extends BreadcrumbsTask { final String TAG = "OGT.GetBreadcrumbsTracksTask"; private OAuthConsumer mConsumer; private DefaultHttpClient mHttpclient; private Integer mBundleId; private LinkedList<Object[]> mTracks; /** * We pass the OAuth consumer and provider. * * @param mContext Required to be able to start the intent to launch the * browser. * @param httpclient * @param provider The OAuthProvider object * @param mConsumer The OAuthConsumer object */ public GetBreadcrumbsTracksTask(Context context, BreadcrumbsService adapter, ProgressListener listener, DefaultHttpClient httpclient, OAuthConsumer consumer, Integer bundleId) { super(context, adapter, listener); mHttpclient = httpclient; mConsumer = consumer; mBundleId = bundleId; } /** * Retrieve the OAuth Request Token and present a browser to the user to * authorize the token. */ @Override protected Void doInBackground(Void... params) { mTracks = new LinkedList<Object[]>(); HttpEntity responseEntity = null; try { HttpUriRequest request = new HttpGet("http://api.gobreadcrumbs.com/v1/bundles/"+mBundleId+"/tracks.xml"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } mConsumer.sign(request); if( BreadcrumbsAdapter.DEBUG ) { Log.d( TAG, "Execute request: "+request.getURI() ); for( Header header : request.getAllHeaders() ) { Log.d( TAG, " with header: "+header.toString()); } } HttpResponse response = mHttpclient.execute(request); responseEntity = response.getEntity(); InputStream is = responseEntity.getContent(); InputStream stream = new BufferedInputStream(is, 8192); if( BreadcrumbsAdapter.DEBUG ) { stream = XmlCreator.convertStreamToLoggedStream(TAG, stream); } XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(stream, "UTF-8"); String tagName = null; int eventType = xpp.getEventType(); String trackName = null, description = null, difficulty = null, startTime = null, endTime = null, trackRating = null, isPublic = null; Integer trackId = null, bundleId = null, totalTime = null; Float lat = null, lng = null, totalDistance = null; while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { tagName = xpp.getName(); } else if (eventType == XmlPullParser.END_TAG) { if ("track".equals(xpp.getName()) && trackId != null && bundleId != null) { mTracks.add(new Object[] { trackId, trackName, bundleId, description, difficulty, startTime, endTime, isPublic, lat, lng, totalDistance, totalTime, trackRating }); } tagName = null; } else if (eventType == XmlPullParser.TEXT) { if ("bundle-id".equals(tagName)) { bundleId = Integer.parseInt(xpp.getText()); } else if ("description".equals(tagName)) { description = xpp.getText(); } else if ("difficulty".equals(tagName)) { difficulty = xpp.getText(); } else if ("start-time".equals(tagName)) { startTime = xpp.getText(); } else if ("end-time".equals(tagName)) { endTime = xpp.getText(); } else if ("id".equals(tagName)) { trackId = Integer.parseInt(xpp.getText()); } else if ("is-public".equals(tagName)) { isPublic = xpp.getText(); } else if ("lat".equals(tagName)) { lat = Float.parseFloat(xpp.getText()); } else if ("lng".equals(tagName)) { lng = Float.parseFloat(xpp.getText()); } else if ("name".equals(tagName)) { trackName = xpp.getText(); } else if ("track-rating".equals(tagName)) { trackRating = xpp.getText(); } } eventType = xpp.next(); } } catch (OAuthMessageSignerException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_track), e, "Failed to sign the request with authentication signature"); } catch (OAuthExpectationFailedException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_track), e, "The request did not authenticate"); } catch (OAuthCommunicationException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_track), e, "The authentication communication failed"); } catch (IOException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_track), e, "A problem during communication"); } catch (XmlPullParserException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_track), e, "A problem while reading the XML data"); } finally { if (responseEntity != null) { try { EntityUtils.consume(responseEntity); } catch (IOException e) { Log.e(TAG, "Failed to close the content stream", e); } } } return null; } @Override protected void updateTracksData(BreadcrumbsTracks tracks) { Set<Integer> mTracksIds = new HashSet<Integer>() ; for (Object[] track : mTracks) { mTracksIds.add((Integer) track[0]); } tracks.setAllTracksForBundleId( mBundleId, mTracksIds ); for (Object[] track : mTracks) { Integer trackId = (Integer) track[0]; String trackName = (String) track[1]; Integer bundleId = (Integer) track[2]; String description = (String) track[3]; String difficulty = (String) track[4]; String startTime = (String) track[5]; String endTime = (String) track[6]; String isPublic = (String) track[7]; Float lat = (Float) track[8]; Float lng = (Float) track[9]; Float totalDistance = (Float) track[10]; Integer totalTime = (Integer) track[11]; String trackRating = (String) track[12]; tracks.addTrack(trackId, trackName, bundleId, description, difficulty, startTime, endTime, isPublic, lat, lng, totalDistance, totalTime, trackRating); } } }
Java
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Oct 20, 2012 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ */ package nl.sogeti.android.gpstracker.breadcrumbs; import java.util.List; import java.util.Observable; import java.util.Observer; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.oauth.PrepareRequestTokenActivity; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.Pair; import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; import org.apache.ogt.http.conn.ClientConnectionManager; import org.apache.ogt.http.conn.scheme.PlainSocketFactory; import org.apache.ogt.http.conn.scheme.Scheme; import org.apache.ogt.http.conn.scheme.SchemeRegistry; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.impl.conn.tsccm.ThreadSafeClientConnManager; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.net.Uri; import android.os.AsyncTask; import android.os.Binder; import android.os.Build; import android.os.IBinder; import android.preference.PreferenceManager; import android.util.Log; /** * ???? * * @version $Id:$ * @author rene (c) Oct 20, 2012, Sogeti B.V. */ public class BreadcrumbsService extends Service implements Observer, ProgressListener { public static final String OAUTH_TOKEN = "breadcrumbs_oauth_token"; public static final String OAUTH_TOKEN_SECRET = "breadcrumbs_oauth_secret"; private static final String TAG = "OGT.BreadcrumbsService"; public static final String NOTIFY_DATA_SET_CHANGED = "nl.sogeti.android.gpstracker.intent.action.NOTIFY_DATA_SET_CHANGED"; public static final String NOTIFY_PROGRESS_CHANGED = "nl.sogeti.android.gpstracker.intent.action.NOTIFY_PROGRESS_CHANGED"; public static final String PROGRESS_INDETERMINATE = null; public static final String PROGRESS = null; public static final String PROGRESS_STATE = null; public static final String PROGRESS_RESULT = null; public static final String PROGRESS_TASK = null; public static final String PROGRESS_MESSAGE = null; public static final int PROGRESS_STARTED = 1; public static final int PROGRESS_FINISHED = 2; public static final int PROGRESS_ERROR = 3; private final IBinder mBinder = new LocalBinder(); private BreadcrumbsTracks mTracks; private DefaultHttpClient mHttpClient; private OnSharedPreferenceChangeListener tokenChangedListener; private boolean mFinishing; boolean mAuthorized; ExecutorService mExecutor; @Override public void onCreate() { super.onCreate(); mExecutor = Executors.newFixedThreadPool(1); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); ClientConnectionManager cm = new ThreadSafeClientConnManager(schemeRegistry); mHttpClient = new DefaultHttpClient(cm); mTracks = new BreadcrumbsTracks(this.getContentResolver()); mTracks.addObserver(this); connectionSetup(); } @Override public void onDestroy() { if (tokenChangedListener != null) { PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(tokenChangedListener); } mAuthorized = false; mFinishing = true; new AsyncTask<Void, Void, Void>() { public void executeOn(Executor executor) { if (Build.VERSION.SDK_INT >= 11) { executeOnExecutor(executor); } else { execute(); } } @Override protected Void doInBackground(Void... params) { mHttpClient.getConnectionManager().shutdown(); mExecutor.shutdown(); mHttpClient = null; return null; } }.executeOn(mExecutor); mTracks.persistCache(this); super.onDestroy(); } /** * Class used for the client Binder. Because we know this service always runs in the same process as its clients, we don't need to deal with IPC. */ public class LocalBinder extends Binder { public BreadcrumbsService getService() { return BreadcrumbsService.this; } } /** * @see android.app.Service#onBind(android.content.Intent) */ @Override public IBinder onBind(Intent intent) { return mBinder; } private boolean connectionSetup() { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String token = prefs.getString(OAUTH_TOKEN, ""); String secret = prefs.getString(OAUTH_TOKEN_SECRET, ""); mAuthorized = !"".equals(token) && !"".equals(secret); if (mAuthorized) { CommonsHttpOAuthConsumer consumer = getOAuthConsumer(); if (mTracks.readCache(this)) { new GetBreadcrumbsActivitiesTask(this, this, this, mHttpClient, consumer).executeOn(mExecutor); new GetBreadcrumbsBundlesTask(this, this, this, mHttpClient, consumer).executeOn(mExecutor); } } return mAuthorized; } public CommonsHttpOAuthConsumer getOAuthConsumer() { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String token = prefs.getString(OAUTH_TOKEN, ""); String secret = prefs.getString(OAUTH_TOKEN_SECRET, ""); CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(this.getString(R.string.CONSUMER_KEY), this.getString(R.string.CONSUMER_SECRET)); consumer.setTokenWithSecret(token, secret); return consumer; } public void removeAuthentication() { Log.w(TAG, "Removing Breadcrumbs OAuth tokens"); Editor e = PreferenceManager.getDefaultSharedPreferences(this).edit(); e.remove(OAUTH_TOKEN); e.remove(OAUTH_TOKEN_SECRET); e.commit(); } /** * Use a locally stored token or start the request activity to collect one */ public void collectBreadcrumbsOauthToken() { if (!connectionSetup()) { tokenChangedListener = new OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (OAUTH_TOKEN.equals(key)) { PreferenceManager.getDefaultSharedPreferences(BreadcrumbsService.this).unregisterOnSharedPreferenceChangeListener(tokenChangedListener); connectionSetup(); } } }; PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(tokenChangedListener); Intent i = new Intent(this.getApplicationContext(), PrepareRequestTokenActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.putExtra(PrepareRequestTokenActivity.OAUTH_TOKEN_PREF, OAUTH_TOKEN); i.putExtra(PrepareRequestTokenActivity.OAUTH_TOKEN_SECRET_PREF, OAUTH_TOKEN_SECRET); i.putExtra(PrepareRequestTokenActivity.CONSUMER_KEY, this.getString(R.string.CONSUMER_KEY)); i.putExtra(PrepareRequestTokenActivity.CONSUMER_SECRET, this.getString(R.string.CONSUMER_SECRET)); i.putExtra(PrepareRequestTokenActivity.REQUEST_URL, Constants.REQUEST_URL); i.putExtra(PrepareRequestTokenActivity.ACCESS_URL, Constants.ACCESS_URL); i.putExtra(PrepareRequestTokenActivity.AUTHORIZE_URL, Constants.AUTHORIZE_URL); this.startActivity(i); } } public void startDownloadTask(Context context, ProgressListener listener, Pair<Integer, Integer> track) { new DownloadBreadcrumbsTrackTask(context, listener, this, mHttpClient, getOAuthConsumer(), track).executeOn(mExecutor); } public void startUploadTask(Context context, ProgressListener listener, Uri trackUri, String name) { new UploadBreadcrumbsTrackTask(context, this, listener, mHttpClient, getOAuthConsumer(), trackUri, name).executeOn(mExecutor); } public boolean isAuthorized() { return mAuthorized; } public void willDisplayItem(Pair<Integer, Integer> item) { if (item.first == Constants.BREADCRUMBS_BUNDLE_ITEM_VIEW_TYPE) { if (!mFinishing && !mTracks.areTracksLoaded(item) && !mTracks.areTracksLoadingScheduled(item)) { new GetBreadcrumbsTracksTask(this, this, this, mHttpClient, getOAuthConsumer(), item.second).executeOn(mExecutor); mTracks.addTracksLoadingScheduled(item); } } } public List<Pair<Integer, Integer>> getAllItems() { List<Pair<Integer, Integer>> items = mTracks.getAllItems(); return items; } public List<Pair<Integer, Integer>> getActivityList() { List<Pair<Integer, Integer>> activities = mTracks.getActivityList(); return activities; } public List<Pair<Integer, Integer>> getBundleList() { List<Pair<Integer, Integer>> bundles = mTracks.getBundleList(); return bundles; } public String getValueForItem(Pair<Integer, Integer> item, String name) { return mTracks.getValueForItem(item, name); } public void clearAllCache() { mTracks.clearAllCache(this); } protected BreadcrumbsTracks getBreadcrumbsTracks() { return mTracks; } public boolean isLocalTrackSynced(long trackId) { return mTracks.isLocalTrackSynced(trackId); } /**** * Observer interface */ @Override public void update(Observable observable, Object data) { Intent broadcast = new Intent(); broadcast.setAction(BreadcrumbsService.NOTIFY_DATA_SET_CHANGED); getApplicationContext().sendBroadcast(broadcast); } /**** * ProgressListener interface */ @Override public void setIndeterminate(boolean indeterminate) { Intent broadcast = new Intent(); broadcast.putExtra(BreadcrumbsService.PROGRESS_INDETERMINATE, indeterminate); broadcast.setAction(BreadcrumbsService.NOTIFY_PROGRESS_CHANGED); getApplicationContext().sendBroadcast(broadcast); } @Override public void started() { Intent broadcast = new Intent(); broadcast.putExtra(BreadcrumbsService.PROGRESS_STATE, BreadcrumbsService.PROGRESS_STARTED); broadcast.setAction(BreadcrumbsService.NOTIFY_PROGRESS_CHANGED); getApplicationContext().sendBroadcast(broadcast); } @Override public void setProgress(int value) { Intent broadcast = new Intent(); broadcast.putExtra(BreadcrumbsService.PROGRESS, value); broadcast.setAction(BreadcrumbsService.NOTIFY_PROGRESS_CHANGED); getApplicationContext().sendBroadcast(broadcast); } @Override public void finished(Uri result) { Intent broadcast = new Intent(); broadcast.putExtra(BreadcrumbsService.PROGRESS_STATE, BreadcrumbsService.PROGRESS_FINISHED); broadcast.putExtra(BreadcrumbsService.PROGRESS_RESULT, result); broadcast.setAction(BreadcrumbsService.NOTIFY_PROGRESS_CHANGED); getApplicationContext().sendBroadcast(broadcast); } @Override public void showError(String task, String errorMessage, Exception exception) { Intent broadcast = new Intent(); broadcast.putExtra(BreadcrumbsService.PROGRESS_STATE, BreadcrumbsService.PROGRESS_ERROR); broadcast.putExtra(BreadcrumbsService.PROGRESS_TASK, task); broadcast.putExtra(BreadcrumbsService.PROGRESS_MESSAGE, errorMessage); broadcast.putExtra(BreadcrumbsService.PROGRESS_RESULT, exception); broadcast.setAction(BreadcrumbsService.NOTIFY_PROGRESS_CHANGED); getApplicationContext().sendBroadcast(broadcast); } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.breadcrumbs; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.tasks.GpxCreator; import nl.sogeti.android.gpstracker.actions.tasks.XmlCreator; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.adapter.BreadcrumbsAdapter; import nl.sogeti.android.gpstracker.db.GPStracking.MetaData; import oauth.signpost.OAuthConsumer; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.HttpClient; import org.apache.ogt.http.client.methods.HttpPost; import org.apache.ogt.http.entity.mime.HttpMultipartMode; import org.apache.ogt.http.entity.mime.MultipartEntity; import org.apache.ogt.http.entity.mime.content.FileBody; import org.apache.ogt.http.entity.mime.content.StringBody; import org.apache.ogt.http.util.EntityUtils; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.util.Log; /** * An asynchronous task that communicates with Twitter to retrieve a request * token. (OAuthGetRequestToken) After receiving the request token from Twitter, * pop a browser to the user to authorize the Request Token. * (OAuthAuthorizeToken) */ public class UploadBreadcrumbsTrackTask extends GpxCreator { final String TAG = "OGT.UploadBreadcrumbsTrackTask"; private BreadcrumbsService mService; private OAuthConsumer mConsumer; private HttpClient mHttpClient; private String mActivityId; private String mBundleId; private String mDescription; private String mIsPublic; private String mBundleName; private String mBundleDescription; private boolean mIsBundleCreated; private List<File> mPhotoUploadQueue; /** * Constructor: create a new UploadBreadcrumbsTrackTask. * * @param context * @param adapter * @param listener * @param httpclient * @param consumer * @param trackUri * @param name */ public UploadBreadcrumbsTrackTask(Context context, BreadcrumbsService adapter, ProgressListener listener, HttpClient httpclient, OAuthConsumer consumer, Uri trackUri, String name) { super(context, trackUri, name, true, listener); mService = adapter; mHttpClient = httpclient; mConsumer = consumer; mPhotoUploadQueue = new LinkedList<File>(); } /** * Retrieve the OAuth Request Token and present a browser to the user to * authorize the token. */ @Override protected Uri doInBackground(Void... params) { // Leave room in the progressbar for uploading determineProgressGoal(); mProgressAdmin.setUpload(true); // Build GPX file Uri gpxFile = exportGpx(); if (isCancelled()) { String text = mContext.getString(R.string.ticker_failed) + " \"http://api.gobreadcrumbs.com/v1/tracks\" " + mContext.getString(R.string.error_buildxml); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), new IOException("Fail to execute request due to canceling"), text); } // Collect GPX Import option params mActivityId = null; mBundleId = null; mDescription = null; mIsPublic = null; Uri metadataUri = Uri.withAppendedPath(mTrackUri, "metadata"); Cursor cursor = null; try { cursor = mContext.getContentResolver().query(metadataUri, new String[] { MetaData.KEY, MetaData.VALUE }, null, null, null); if (cursor.moveToFirst()) { do { String key = cursor.getString(0); if (BreadcrumbsTracks.ACTIVITY_ID.equals(key)) { mActivityId = cursor.getString(1); } else if (BreadcrumbsTracks.BUNDLE_ID.equals(key)) { mBundleId = cursor.getString(1); } else if (BreadcrumbsTracks.DESCRIPTION.equals(key)) { mDescription = cursor.getString(1); } else if (BreadcrumbsTracks.ISPUBLIC.equals(key)) { mIsPublic = cursor.getString(1); } } while (cursor.moveToNext()); } } finally { if (cursor != null) { cursor.close(); } } if ("-1".equals(mActivityId)) { String text = "Unable to upload without a activity id stored in meta-data table"; IllegalStateException e = new IllegalStateException(text); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, text); } int statusCode = 0; String responseText = null; Uri trackUri = null; HttpEntity responseEntity = null; try { if ("-1".equals(mBundleId)) { mBundleDescription = "";//mContext.getString(R.string.breadcrumbs_bundledescription); mBundleName = mContext.getString(R.string.app_name); mBundleId = createOpenGpsTrackerBundle(); } String gpxString = XmlCreator.convertStreamToString(mContext.getContentResolver().openInputStream(gpxFile)); HttpPost method = new HttpPost("http://api.gobreadcrumbs.com:80/v1/tracks"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } // Build the multipart body with the upload data MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("import_type", new StringBody("GPX")); //entity.addPart("gpx", new FileBody(gpxFile)); entity.addPart("gpx", new StringBody(gpxString)); entity.addPart("bundle_id", new StringBody(mBundleId)); entity.addPart("activity_id", new StringBody(mActivityId)); entity.addPart("description", new StringBody(mDescription)); // entity.addPart("difficulty", new StringBody("3")); // entity.addPart("rating", new StringBody("4")); entity.addPart("public", new StringBody(mIsPublic)); method.setEntity(entity); // Execute the POST to OpenStreetMap mConsumer.sign(method); if( BreadcrumbsAdapter.DEBUG ) { Log.d( TAG, "HTTP Method "+method.getMethod() ); Log.d( TAG, "URI scheme "+method.getURI().getScheme() ); Log.d( TAG, "Host name "+method.getURI().getHost() ); Log.d( TAG, "Port "+method.getURI().getPort() ); Log.d( TAG, "Request path "+method.getURI().getPath()); Log.d( TAG, "Consumer Key: "+mConsumer.getConsumerKey()); Log.d( TAG, "Consumer Secret: "+mConsumer.getConsumerSecret()); Log.d( TAG, "Token: "+mConsumer.getToken()); Log.d( TAG, "Token Secret: "+mConsumer.getTokenSecret()); Log.d( TAG, "Execute request: "+method.getURI() ); for( Header header : method.getAllHeaders() ) { Log.d( TAG, " with header: "+header.toString()); } } HttpResponse response = mHttpClient.execute(method); mProgressAdmin.addUploadProgress(); statusCode = response.getStatusLine().getStatusCode(); responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); responseText = XmlCreator.convertStreamToString(stream); if( BreadcrumbsAdapter.DEBUG ) { Log.d( TAG, "Upload Response: "+responseText); } Pattern p = Pattern.compile(">([0-9]+)</id>"); Matcher m = p.matcher(responseText); if (m.find()) { Integer trackId = Integer.valueOf(m.group(1)); trackUri = Uri.parse("http://api.gobreadcrumbs.com/v1/tracks/" + trackId + "/placemarks.gpx"); for( File photo :mPhotoUploadQueue ) { uploadPhoto(photo, trackId); } } } catch (OAuthMessageSignerException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, "Failed to sign the request with authentication signature"); } catch (OAuthExpectationFailedException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, "The request did not authenticate"); } catch (OAuthCommunicationException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, "The authentication communication failed"); } catch (IOException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, "A problem during communication"); } finally { if (responseEntity != null) { try { EntityUtils.consume(responseEntity); } catch (IOException e) { Log.e(TAG, "Failed to close the content stream", e); } } } if (statusCode == 200 || statusCode == 201) { if (trackUri == null) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), new IOException("Unable to retrieve URI from response"), responseText); } } else { //mAdapter.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), new IOException("Status code: " + statusCode), responseText); } return trackUri; } private String createOpenGpsTrackerBundle() throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, IOException { HttpPost method = new HttpPost("http://api.gobreadcrumbs.com/v1/bundles.xml"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("name", new StringBody(mBundleName)); entity.addPart("activity_id", new StringBody(mActivityId)); entity.addPart("description", new StringBody(mBundleDescription)); method.setEntity(entity); mConsumer.sign(method); HttpResponse response = mHttpClient.execute(method); HttpEntity responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); String responseText = XmlCreator.convertStreamToString(stream); Pattern p = Pattern.compile(">([0-9]+)</id>"); Matcher m = p.matcher(responseText); String bundleId = null; if (m.find()) { bundleId = m.group(1); ContentValues values = new ContentValues(); values.put(MetaData.KEY, BreadcrumbsTracks.BUNDLE_ID); values.put(MetaData.VALUE, bundleId); Uri metadataUri = Uri.withAppendedPath(mTrackUri, "metadata"); mContext.getContentResolver().insert(metadataUri, values); mIsBundleCreated = true; } else { String text = "Unable to upload (yet) without a bunld id stored in meta-data table"; IllegalStateException e = new IllegalStateException(text); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, text); } return bundleId; } /** * Queue's media * * @param inputFilePath * @return file path relative to the export dir * @throws IOException */ @Override protected String includeMediaFile(String inputFilePath) throws IOException { File source = new File(inputFilePath); if (source.exists()) { mProgressAdmin.setPhotoUpload(source.length()); mPhotoUploadQueue.add(source); } return source.getName(); } private void uploadPhoto(File photo, Integer trackId) throws IOException, OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException { HttpPost request = new HttpPost("http://api.gobreadcrumbs.com/v1/photos.xml"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("name", new StringBody(photo.getName())); entity.addPart("track_id", new StringBody(Integer.toString(trackId))); //entity.addPart("description", new StringBody("")); entity.addPart("file", new FileBody(photo)); request.setEntity(entity); mConsumer.sign(request); if( BreadcrumbsAdapter.DEBUG ) { Log.d( TAG, "Execute request: "+request.getURI() ); for( Header header : request.getAllHeaders() ) { Log.d( TAG, " with header: "+header.toString()); } } HttpResponse response = mHttpClient.execute(request); HttpEntity responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); String responseText = XmlCreator.convertStreamToString(stream); mProgressAdmin.addPhotoUploadProgress(photo.length()); Log.i( TAG, "Uploaded photo "+responseText); } @Override protected void onPostExecute(Uri result) { BreadcrumbsTracks tracks = mService.getBreadcrumbsTracks(); Uri metadataUri = Uri.withAppendedPath(mTrackUri, "metadata"); List<String> segments = result.getPathSegments(); Integer bcTrackId = Integer.valueOf(segments.get(segments.size() - 2)); ArrayList<ContentValues> metaValues = new ArrayList<ContentValues>(); metaValues.add(buildContentValues(BreadcrumbsTracks.TRACK_ID, Long.toString(bcTrackId))); if (mDescription != null) { metaValues.add(buildContentValues(BreadcrumbsTracks.DESCRIPTION, mDescription)); } if (mIsPublic != null) { metaValues.add(buildContentValues(BreadcrumbsTracks.ISPUBLIC, mIsPublic)); } metaValues.add(buildContentValues(BreadcrumbsTracks.BUNDLE_ID, mBundleId)); metaValues.add(buildContentValues(BreadcrumbsTracks.ACTIVITY_ID, mActivityId)); // Store in OGT provider ContentResolver resolver = mContext.getContentResolver(); resolver.bulkInsert(metadataUri, metaValues.toArray(new ContentValues[1])); // Store in Breadcrumbs adapter tracks.addSyncedTrack(Long.valueOf(mTrackUri.getLastPathSegment()), bcTrackId); if( mIsBundleCreated ) { mService.getBreadcrumbsTracks().addBundle(Integer.parseInt(mBundleId), mBundleName, mBundleDescription); } //"http://api.gobreadcrumbs.com/v1/tracks/" + trackId + "/placemarks.gpx" mService.getBreadcrumbsTracks().addTrack(bcTrackId, mName, Integer.valueOf(mBundleId), mDescription, null, null, null, mIsPublic, null, null, null, null, null); super.onPostExecute(result); } private ContentValues buildContentValues(String key, String value) { ContentValues contentValues = new ContentValues(); contentValues.put(MetaData.KEY, key); contentValues.put(MetaData.VALUE, value); return contentValues; } }
Java
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) May 29, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.breadcrumbs; import java.util.concurrent.Executor; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import android.annotation.TargetApi; import android.content.Context; import android.os.AsyncTask; import android.os.Build; import android.util.Log; /** * ???? * * @version $Id:$ * @author rene (c) May 29, 2011, Sogeti B.V. */ public abstract class BreadcrumbsTask extends AsyncTask<Void, Void, Void> { private static final String TAG = "OGT.BreadcrumbsTask"; private ProgressListener mListener; private String mErrorText; private Exception mException; protected BreadcrumbsService mService; private String mTask; protected Context mContext; public BreadcrumbsTask(Context context, BreadcrumbsService adapter, ProgressListener listener) { mContext = context; mListener = listener; mService = adapter; } @TargetApi(11) public void executeOn(Executor executor) { if (Build.VERSION.SDK_INT >= 11) { executeOnExecutor(executor); } else { execute(); } } protected void handleError(String task, Exception e, String text) { Log.e(TAG, "Received error will cancel background task " + this.getClass().getName(), e); mService.removeAuthentication(); mTask = task; mException = e; mErrorText = text; cancel(true); } @Override protected void onPreExecute() { if (mListener != null) { mListener.setIndeterminate(true); mListener.started(); } } @Override protected void onPostExecute(Void result) { this.updateTracksData(mService.getBreadcrumbsTracks()); if (mListener != null) { mListener.finished(null); } } protected abstract void updateTracksData(BreadcrumbsTracks tracks); @Override protected void onCancelled() { if (mListener != null) { mListener.finished(null); } if (mListener != null && mErrorText != null && mException != null) { mListener.showError(mTask, mErrorText, mException); } else if (mException != null) { Log.e(TAG, "Incomplete error after cancellation:" + mErrorText, mException); } else { Log.e(TAG, "Incomplete error after cancellation:" + mErrorText); } } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.breadcrumbs; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.tasks.GpxParser; import nl.sogeti.android.gpstracker.actions.tasks.XmlCreator; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.adapter.BreadcrumbsAdapter; import nl.sogeti.android.gpstracker.db.GPStracking.MetaData; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.util.Pair; import oauth.signpost.OAuthConsumer; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.client.methods.HttpUriRequest; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.util.EntityUtils; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.net.Uri; import android.util.Log; /** * An asynchronous task that communicates with Twitter to retrieve a request * token. (OAuthGetRequestToken) After receiving the request token from Twitter, * pop a browser to the user to authorize the Request Token. * (OAuthAuthorizeToken) */ public class DownloadBreadcrumbsTrackTask extends GpxParser { final String TAG = "OGT.GetBreadcrumbsTracksTask"; private BreadcrumbsService mAdapter; private OAuthConsumer mConsumer; private DefaultHttpClient mHttpclient; private Pair<Integer, Integer> mTrack; /** * * Constructor: create a new DownloadBreadcrumbsTrackTask. * @param context * @param progressListener * @param adapter * @param httpclient * @param consumer * @param track */ public DownloadBreadcrumbsTrackTask(Context context, ProgressListener progressListener, BreadcrumbsService adapter, DefaultHttpClient httpclient, OAuthConsumer consumer, Pair<Integer, Integer> track) { super(context, progressListener); mAdapter = adapter; mHttpclient = httpclient; mConsumer = consumer; mTrack = track; } /** * Retrieve the OAuth Request Token and present a browser to the user to * authorize the token. */ @Override protected Uri doInBackground(Uri... params) { determineProgressGoal(null); Uri trackUri = null; String trackName = mAdapter.getBreadcrumbsTracks().getValueForItem(mTrack, BreadcrumbsTracks.NAME); HttpEntity responseEntity = null; try { HttpUriRequest request = new HttpGet("http://api.gobreadcrumbs.com/v1/tracks/" + mTrack.second + "/placemarks.gpx"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } mConsumer.sign(request); if( BreadcrumbsAdapter.DEBUG ) { Log.d( TAG, "Execute request: "+request.getURI() ); for( Header header : request.getAllHeaders() ) { Log.d( TAG, " with header: "+header.toString()); } } HttpResponse response = mHttpclient.execute(request); responseEntity = response.getEntity(); InputStream is = responseEntity.getContent(); InputStream stream = new BufferedInputStream(is, 8192); if( BreadcrumbsAdapter.DEBUG ) { stream = XmlCreator.convertStreamToLoggedStream(TAG, stream); } trackUri = importTrack(stream, trackName); } catch (OAuthMessageSignerException e) { handleError(e, mContext.getString(R.string.error_importgpx_xml)); } catch (OAuthExpectationFailedException e) { handleError(e, mContext.getString(R.string.error_importgpx_xml)); } catch (OAuthCommunicationException e) { handleError(e, mContext.getString(R.string.error_importgpx_xml)); } catch (IOException e) { handleError(e, mContext.getString(R.string.error_importgpx_xml)); } finally { if (responseEntity != null) { try { EntityUtils.consume(responseEntity); } catch (IOException e) { Log.e( TAG, "Failed to close the content stream", e); } } } return trackUri; } @Override protected void onPostExecute(Uri result) { super.onPostExecute(result); long ogtTrackId = Long.parseLong(result.getLastPathSegment()); Uri metadataUri = Uri.withAppendedPath(ContentUris.withAppendedId(Tracks.CONTENT_URI, ogtTrackId), "metadata"); BreadcrumbsTracks tracks = mAdapter.getBreadcrumbsTracks(); Integer bcTrackId = mTrack.second; Integer bcBundleId = tracks.getBundleIdForTrackId(bcTrackId); //TODO Integer bcActivityId = tracks.getActivityIdForBundleId(bcBundleId); String bcDifficulty = tracks.getValueForItem(mTrack, BreadcrumbsTracks.DIFFICULTY); String bcRating = tracks.getValueForItem(mTrack, BreadcrumbsTracks.RATING); String bcPublic = tracks.getValueForItem(mTrack, BreadcrumbsTracks.ISPUBLIC); String bcDescription = tracks.getValueForItem(mTrack, BreadcrumbsTracks.DESCRIPTION); ArrayList<ContentValues> metaValues = new ArrayList<ContentValues>(); if (bcTrackId != null) { metaValues.add(buildContentValues(BreadcrumbsTracks.TRACK_ID, Long.toString(bcTrackId))); } if (bcDescription != null) { metaValues.add(buildContentValues(BreadcrumbsTracks.DESCRIPTION, bcDescription)); } if (bcDifficulty != null) { metaValues.add(buildContentValues(BreadcrumbsTracks.DIFFICULTY, bcDifficulty)); } if (bcRating != null) { metaValues.add(buildContentValues(BreadcrumbsTracks.RATING, bcRating)); } if (bcPublic != null) { metaValues.add(buildContentValues(BreadcrumbsTracks.ISPUBLIC, bcPublic)); } if (bcBundleId != null) { metaValues.add(buildContentValues(BreadcrumbsTracks.BUNDLE_ID, Integer.toString(bcBundleId))); } // if (bcActivityId != null) // { // metaValues.add(buildContentValues(BreadcrumbsTracks.ACTIVITY_ID, Integer.toString(bcActivityId))); // } ContentResolver resolver = mContext.getContentResolver(); resolver.bulkInsert(metadataUri, metaValues.toArray(new ContentValues[1])); tracks.addSyncedTrack(ogtTrackId, mTrack.second); } private ContentValues buildContentValues(String key, String value) { ContentValues contentValues = new ContentValues(); contentValues.put(MetaData.KEY, key); contentValues.put(MetaData.VALUE, value); return contentValues; } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.oauth; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.util.Constants; import oauth.signpost.OAuthConsumer; import oauth.signpost.OAuthProvider; import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; import oauth.signpost.commonshttp.CommonsHttpOAuthProvider; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask.Status; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.widget.TextView; /** * Prepares a OAuthConsumer and OAuthProvider OAuthConsumer is configured with * the consumer key & consumer secret. Both key and secret are retrieved from * the extras in the Intent * * OAuthProvider is configured with the 3 * OAuth endpoints. These are retrieved from the extras in the Intent. * * Execute the OAuthRequestTokenTask to retrieve the request, * and authorize the request. After the request is authorized, a callback is * made here and this activity finishes to return to the last Activity on the * stack. */ public class PrepareRequestTokenActivity extends Activity { /** * Name of the Extra in the intent holding the consumer secret */ public static final String CONSUMER_SECRET = "CONSUMER_SECRET"; /** * Name of the Extra in the intent holding the consumer key */ public static final String CONSUMER_KEY = "CONSUMER_KEY"; /** * Name of the Extra in the intent holding the authorizationWebsiteUrl */ public static final String AUTHORIZE_URL = "AUTHORIZE_URL"; /** * Name of the Extra in the intent holding the accessTokenEndpointUrl */ public static final String ACCESS_URL = "ACCESS_URL"; /** * Name of the Extra in the intent holding the requestTokenEndpointUrl */ public static final String REQUEST_URL = "REQUEST_URL"; /** * String value of the key in the DefaultSharedPreferences * in which to store the permission token */ public static final String OAUTH_TOKEN_PREF = "OAUTH_TOKEN"; /** * String value of the key in the DefaultSharedPreferences * in which to store the permission secret */ public static final String OAUTH_TOKEN_SECRET_PREF = "OAUTH_TOKEN_SECRET"; final String TAG = "OGT.PrepareRequestTokenActivity"; private OAuthConsumer consumer; private OAuthProvider provider; private String mTokenKey; private String mSecretKey; private OAuthRequestTokenTask mTask; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.oauthentication); String key = getIntent().getStringExtra(CONSUMER_KEY); String secret = getIntent().getStringExtra(CONSUMER_SECRET); String requestUrl = getIntent().getStringExtra(REQUEST_URL); String accessUrl = getIntent().getStringExtra(ACCESS_URL); String authUrl = getIntent().getStringExtra(AUTHORIZE_URL); TextView tv = (TextView) findViewById(R.id.detail); tv.setText(requestUrl); mTokenKey = getIntent().getStringExtra(OAUTH_TOKEN_PREF); mSecretKey = getIntent().getStringExtra(OAUTH_TOKEN_SECRET_PREF); this.consumer = new CommonsHttpOAuthConsumer(key, secret); this.provider = new CommonsHttpOAuthProvider(requestUrl, accessUrl, authUrl); mTask = new OAuthRequestTokenTask(this, consumer, provider); mTask.execute(); } @Override protected void onResume() { super.onResume(); // Will not be called if onNewIntent() was called with callback scheme Status status = mTask.getStatus(); if( status != Status.RUNNING ) { finish(); } } /** * Called when the OAuthRequestTokenTask finishes (user has authorized the * request token). The callback URL will be intercepted here. */ @Override public void onNewIntent(Intent intent) { super.onNewIntent(intent); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); final Uri uri = intent.getData(); if (uri != null && uri.getScheme().equals(Constants.OAUTH_CALLBACK_SCHEME)) { Log.i(TAG, "Callback received : " + uri); Log.i(TAG, "Retrieving Access Token"); new RetrieveAccessTokenTask(this, consumer, provider, prefs, mTokenKey, mSecretKey).execute(uri); finish(); } } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.oauth; import oauth.signpost.OAuth; import oauth.signpost.OAuthConsumer; import oauth.signpost.OAuthProvider; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.net.Uri; import android.os.AsyncTask; import android.util.Log; public class RetrieveAccessTokenTask extends AsyncTask<Uri, Void, Void> { private static final String TAG = "OGT.RetrieveAccessTokenTask"; private OAuthProvider provider; private OAuthConsumer consumer; private SharedPreferences prefs; private String mTokenKey; private String mSecretKey; public RetrieveAccessTokenTask(Context context, OAuthConsumer consumer, OAuthProvider provider, SharedPreferences prefs, String tokenKey, String secretKey) { this.consumer = consumer; this.provider = provider; this.prefs = prefs; mTokenKey = tokenKey; mSecretKey = secretKey; } /** * Retrieve the oauth_verifier, and store the oauth and oauth_token_secret * for future API calls. */ @Override protected Void doInBackground(Uri... params) { final Uri uri = params[0]; final String oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER); try { provider.retrieveAccessToken(consumer, oauth_verifier); final Editor edit = prefs.edit(); edit.putString(mTokenKey, consumer.getToken()); edit.putString(mSecretKey, consumer.getTokenSecret()); edit.commit(); Log.i(TAG, "OAuth - Access Token Retrieved and stored to "+mTokenKey+" and "+mSecretKey); } catch (Exception e) { Log.e(TAG, "OAuth - Access Token Retrieval Error", e); } return null; } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.oauth; import nl.sogeti.android.gpstracker.util.Constants; import oauth.signpost.OAuthConsumer; import oauth.signpost.OAuthProvider; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.util.Log; /** * An asynchronous task that communicates with Twitter to retrieve a request * token. (OAuthGetRequestToken) After receiving the request token from Twitter, * pop a browser to the user to authorize the Request Token. * (OAuthAuthorizeToken) */ public class OAuthRequestTokenTask extends AsyncTask<Void, Void, Void> { final String TAG = "OGT.OAuthRequestTokenTask"; private Context context; private OAuthProvider provider; private OAuthConsumer consumer; /** * We pass the OAuth consumer and provider. * * @param context Required to be able to start the intent to launch the * browser. * @param provider The OAuthProvider object * @param consumer The OAuthConsumer object */ public OAuthRequestTokenTask(Context context, OAuthConsumer consumer, OAuthProvider provider) { this.context = context; this.consumer = consumer; this.provider = provider; } /** * Retrieve the OAuth Request Token and present a browser to the user to * authorize the token. */ @Override protected Void doInBackground(Void... params) { try { final String url = provider.retrieveRequestToken(consumer, Constants.OAUTH_CALLBACK_URL); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND); context.startActivity(intent); } catch (Exception e) { Log.e(TAG, "Failed to start token request ", e); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(Constants.OAUTH_CALLBACK_URL)); intent.putExtra("ERROR", e.toString()); context.startActivity(intent); } return null; } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.widget; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.ControlTracking; import nl.sogeti.android.gpstracker.actions.InsertNote; import nl.sogeti.android.gpstracker.util.Constants; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.util.Log; import android.view.View; import android.widget.RemoteViews; /** * An App Widget for on the home screen to control logging with a start, pause, * resume and stop * * @version $Id$ * @author grootren (c) Mar 8, 2011, Sogeti B.V. */ public class ControlWidgetProvider extends AppWidgetProvider { private static final int BUTTON_TRACKINGCONTROL = 2; private static final int BUTTON_INSERTNOTE = 3; private static final String TAG = "OGT.ControlWidgetProvider"; static final ComponentName THIS_APPWIDGET = new ComponentName("nl.sogeti.android.gpstracker", "nl.sogeti.android.gpstracker.widget.ControlWidgetProvider"); private static int mState; public ControlWidgetProvider() { super(); } @Override public void onEnabled(Context context) { // Log.d(TAG, "onEnabled() "); super.onEnabled(context); context.startService(new Intent(Constants.SERVICENAME)); } @Override public void onDisabled(Context context) { // Log.d(TAG, "onDisabled() "); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // Log.d(TAG, "onDisabled() "); // Update each requested appWidgetId RemoteViews view = buildUpdate(context, -1); for (int i = 0; i < appWidgetIds.length; i++) { appWidgetManager.updateAppWidget(appWidgetIds[i], view); } } /** * Load image for given widget and build {@link RemoteViews} for it. */ static RemoteViews buildUpdate(Context context, int appWidgetId) { RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.control_appwidget); views.setOnClickPendingIntent(R.id.widget_insertnote_enabled, getLaunchPendingIntent(context, appWidgetId, BUTTON_INSERTNOTE)); views.setOnClickPendingIntent(R.id.widget_trackingcontrol, getLaunchPendingIntent(context, appWidgetId, BUTTON_TRACKINGCONTROL)); updateButtons(views, context); return views; } /** * Load image for given widget and build {@link RemoteViews} for it. */ private static void updateButtons(RemoteViews views, Context context) { // Log.d(TAG, "Updated the remote views to state " + mState); switch (mState) { case Constants.LOGGING: setEnableInsertNote(views, true); break; case Constants.PAUSED: setEnableInsertNote(views, false); break; case Constants.STOPPED: setEnableInsertNote(views, false); break; case Constants.UNKNOWN: setEnableInsertNote(views, false); break; default: Log.w(TAG, "Unknown logging state for widget: " + mState); break; } } private static void setEnableInsertNote( RemoteViews views, boolean enabled ) { if( enabled ) { views.setViewVisibility(R.id.widget_insertnote_enabled, View.VISIBLE); views.setViewVisibility(R.id.widget_insertnote_disabled, View.GONE); } else { views.setViewVisibility(R.id.widget_insertnote_enabled, View.GONE); views.setViewVisibility(R.id.widget_insertnote_disabled, View.VISIBLE); } } /** * Creates PendingIntent to notify the widget of a button click. * * @param context * @param appWidgetId * @return */ private static PendingIntent getLaunchPendingIntent(Context context, int appWidgetId, int buttonId) { Intent launchIntent = new Intent(); launchIntent.setClass(context, ControlWidgetProvider.class); launchIntent.addCategory(Intent.CATEGORY_ALTERNATIVE); launchIntent.setData(Uri.parse("custom:" + buttonId)); PendingIntent pi = PendingIntent.getBroadcast(context, 0 /* no requestCode */, launchIntent, 0 /* * no * flags */); return pi; } /** * Receives and processes a button pressed intent or state change. * * @param context * @param intent Indicates the pressed button. */ @Override public void onReceive(Context context, Intent intent) { // Log.d(TAG, "Did recieve intent with action: " + intent.getAction()); super.onReceive(context, intent); String action = intent.getAction(); if (Constants.LOGGING_STATE_CHANGED_ACTION.equals(action)) { mState = intent.getIntExtra(Constants.EXTRA_LOGGING_STATE, Constants.UNKNOWN); updateWidget(context); } else if (intent.hasCategory(Intent.CATEGORY_ALTERNATIVE)) { Uri data = intent.getData(); int buttonId = Integer.parseInt(data.getSchemeSpecificPart()); if (buttonId == BUTTON_TRACKINGCONTROL) { Intent controlIntent = new Intent( context, ControlTracking.class ); controlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(controlIntent); } else if (buttonId == BUTTON_INSERTNOTE) { Intent noteIntent = new Intent( context, InsertNote.class ); noteIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity( noteIntent ); } } else { // Don't fall-through to updating the widget. The Intent // was something unrelated or that our super class took // care of. return; } // State changes fall through updateWidget(context); } /** * Updates the widget when something changes, or when a button is pushed. * * @param context */ public static void updateWidget(Context context) { RemoteViews views = buildUpdate(context, -1); // Update specific list of appWidgetIds if given, otherwise default to all final AppWidgetManager gm = AppWidgetManager.getInstance(context); gm.updateAppWidget(THIS_APPWIDGET, views); } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.db; import android.content.ContentUris; import android.net.Uri; import android.net.Uri.Builder; import android.provider.BaseColumns; /** * The GPStracking provider stores all static information about GPStracking. * * @version $Id$ * @author rene (c) Jan 22, 2009, Sogeti B.V. */ public final class GPStracking { /** The authority of this provider: nl.sogeti.android.gpstracker */ public static final String AUTHORITY = "nl.sogeti.android.gpstracker"; /** The content:// style Uri for this provider, content://nl.sogeti.android.gpstracker */ public static final Uri CONTENT_URI = Uri.parse( "content://" + GPStracking.AUTHORITY ); /** The name of the database file */ static final String DATABASE_NAME = "GPSLOG.db"; /** The version of the database schema */ static final int DATABASE_VERSION = 10; /** * This table contains tracks. * * @author rene */ public static final class Tracks extends TracksColumns implements android.provider.BaseColumns { /** The MIME type of a CONTENT_URI subdirectory of a single track. */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nl.sogeti.android.track"; /** The MIME type of CONTENT_URI providing a directory of tracks. */ public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nl.sogeti.android.track"; /** The content:// style URL for this provider, content://nl.sogeti.android.gpstracker/tracks */ public static final Uri CONTENT_URI = Uri.parse( "content://" + GPStracking.AUTHORITY + "/" + Tracks.TABLE ); /** The name of this table */ public static final String TABLE = "tracks"; static final String CREATE_STATEMENT = "CREATE TABLE " + Tracks.TABLE + "(" + " " + Tracks._ID + " " + Tracks._ID_TYPE + "," + " " + Tracks.NAME + " " + Tracks.NAME_TYPE + "," + " " + Tracks.CREATION_TIME + " " + Tracks.CREATION_TIME_TYPE + ");"; } /** * This table contains segments. * * @author rene */ public static final class Segments extends SegmentsColumns implements android.provider.BaseColumns { /** The MIME type of a CONTENT_URI subdirectory of a single segment. */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nl.sogeti.android.segment"; /** The MIME type of CONTENT_URI providing a directory of segments. */ public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nl.sogeti.android.segment"; /** The name of this table, segments */ public static final String TABLE = "segments"; static final String CREATE_STATMENT = "CREATE TABLE " + Segments.TABLE + "(" + " " + Segments._ID + " " + Segments._ID_TYPE + "," + " " + Segments.TRACK + " " + Segments.TRACK_TYPE + ");"; } /** * This table contains waypoints. * * @author rene */ public static final class Waypoints extends WaypointsColumns implements android.provider.BaseColumns { /** The MIME type of a CONTENT_URI subdirectory of a single waypoint. */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nl.sogeti.android.waypoint"; /** The MIME type of CONTENT_URI providing a directory of waypoints. */ public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nl.sogeti.android.waypoint"; /** The name of this table, waypoints */ public static final String TABLE = "waypoints"; static final String CREATE_STATEMENT = "CREATE TABLE " + Waypoints.TABLE + "(" + " " + BaseColumns._ID + " " + WaypointsColumns._ID_TYPE + "," + " " + WaypointsColumns.LATITUDE + " " + WaypointsColumns.LATITUDE_TYPE + "," + " " + WaypointsColumns.LONGITUDE + " " + WaypointsColumns.LONGITUDE_TYPE + "," + " " + WaypointsColumns.TIME + " " + WaypointsColumns.TIME_TYPE + "," + " " + WaypointsColumns.SPEED + " " + WaypointsColumns.SPEED + "," + " " + WaypointsColumns.SEGMENT + " " + WaypointsColumns.SEGMENT_TYPE + "," + " " + WaypointsColumns.ACCURACY + " " + WaypointsColumns.ACCURACY_TYPE + "," + " " + WaypointsColumns.ALTITUDE + " " + WaypointsColumns.ALTITUDE_TYPE + "," + " " + WaypointsColumns.BEARING + " " + WaypointsColumns.BEARING_TYPE + ");"; static final String[] UPGRADE_STATEMENT_7_TO_8 = { "ALTER TABLE " + Waypoints.TABLE + " ADD COLUMN " + WaypointsColumns.ACCURACY + " " + WaypointsColumns.ACCURACY_TYPE +";", "ALTER TABLE " + Waypoints.TABLE + " ADD COLUMN " + WaypointsColumns.ALTITUDE + " " + WaypointsColumns.ALTITUDE_TYPE +";", "ALTER TABLE " + Waypoints.TABLE + " ADD COLUMN " + WaypointsColumns.BEARING + " " + WaypointsColumns.BEARING_TYPE +";" }; /** * Build a waypoint Uri like: * content://nl.sogeti.android.gpstracker/tracks/2/segments/1/waypoints/52 * using the provided identifiers * * @param trackId * @param segmentId * @param waypointId * * @return */ public static Uri buildUri(long trackId, long segmentId, long waypointId) { Builder builder = Tracks.CONTENT_URI.buildUpon(); ContentUris.appendId(builder, trackId); builder.appendPath(Segments.TABLE); ContentUris.appendId(builder, segmentId); builder.appendPath(Waypoints.TABLE); ContentUris.appendId(builder, waypointId); return builder.build(); } } /** * This table contains media URI's. * * @author rene */ public static final class Media extends MediaColumns implements android.provider.BaseColumns { /** The MIME type of a CONTENT_URI subdirectory of a single media entry. */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nl.sogeti.android.media"; /** The MIME type of CONTENT_URI providing a directory of media entry. */ public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nl.sogeti.android.media"; /** The name of this table */ public static final String TABLE = "media"; static final String CREATE_STATEMENT = "CREATE TABLE " + Media.TABLE + "(" + " " + BaseColumns._ID + " " + MediaColumns._ID_TYPE + "," + " " + MediaColumns.TRACK + " " + MediaColumns.TRACK_TYPE + "," + " " + MediaColumns.SEGMENT + " " + MediaColumns.SEGMENT_TYPE + "," + " " + MediaColumns.WAYPOINT + " " + MediaColumns.WAYPOINT_TYPE + "," + " " + MediaColumns.URI + " " + MediaColumns.URI_TYPE + ");"; public static final Uri CONTENT_URI = Uri.parse( "content://" + GPStracking.AUTHORITY + "/" + Media.TABLE ); } /** * This table contains media URI's. * * @author rene */ public static final class MetaData extends MetaDataColumns implements android.provider.BaseColumns { /** The MIME type of a CONTENT_URI subdirectory of a single metadata entry. */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nl.sogeti.android.metadata"; /** The MIME type of CONTENT_URI providing a directory of media entry. */ public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nl.sogeti.android.metadata"; /** The name of this table */ public static final String TABLE = "metadata"; static final String CREATE_STATEMENT = "CREATE TABLE " + MetaData.TABLE + "(" + " " + BaseColumns._ID + " " + MetaDataColumns._ID_TYPE + "," + " " + MetaDataColumns.TRACK + " " + MetaDataColumns.TRACK_TYPE + "," + " " + MetaDataColumns.SEGMENT + " " + MetaDataColumns.SEGMENT_TYPE + "," + " " + MetaDataColumns.WAYPOINT + " " + MetaDataColumns.WAYPOINT_TYPE + "," + " " + MetaDataColumns.KEY + " " + MetaDataColumns.KEY_TYPE + "," + " " + MetaDataColumns.VALUE + " " + MetaDataColumns.VALUE_TYPE + ");"; /** * content://nl.sogeti.android.gpstracker/metadata */ public static final Uri CONTENT_URI = Uri.parse( "content://" + GPStracking.AUTHORITY + "/" + MetaData.TABLE ); } /** * Columns from the tracks table. * * @author rene */ public static class TracksColumns { public static final String NAME = "name"; public static final String CREATION_TIME = "creationtime"; static final String CREATION_TIME_TYPE = "INTEGER NOT NULL"; static final String NAME_TYPE = "TEXT"; static final String _ID_TYPE = "INTEGER PRIMARY KEY AUTOINCREMENT"; } /** * Columns from the segments table. * * @author rene */ public static class SegmentsColumns { /** The track _id to which this segment belongs */ public static final String TRACK = "track"; static final String TRACK_TYPE = "INTEGER NOT NULL"; static final String _ID_TYPE = "INTEGER PRIMARY KEY AUTOINCREMENT"; } /** * Columns from the waypoints table. * * @author rene */ public static class WaypointsColumns { /** The latitude */ public static final String LATITUDE = "latitude"; /** The longitude */ public static final String LONGITUDE = "longitude"; /** The recorded time */ public static final String TIME = "time"; /** The speed in meters per second */ public static final String SPEED = "speed"; /** The segment _id to which this segment belongs */ public static final String SEGMENT = "tracksegment"; /** The accuracy of the fix */ public static final String ACCURACY = "accuracy"; /** The altitude */ public static final String ALTITUDE = "altitude"; /** the bearing of the fix */ public static final String BEARING = "bearing"; static final String LATITUDE_TYPE = "REAL NOT NULL"; static final String LONGITUDE_TYPE = "REAL NOT NULL"; static final String TIME_TYPE = "INTEGER NOT NULL"; static final String SPEED_TYPE = "REAL NOT NULL"; static final String SEGMENT_TYPE = "INTEGER NOT NULL"; static final String ACCURACY_TYPE = "REAL"; static final String ALTITUDE_TYPE = "REAL"; static final String BEARING_TYPE = "REAL"; static final String _ID_TYPE = "INTEGER PRIMARY KEY AUTOINCREMENT"; } /** * Columns from the media table. * * @author rene */ public static class MediaColumns { /** The track _id to which this segment belongs */ public static final String TRACK = "track"; static final String TRACK_TYPE = "INTEGER NOT NULL"; public static final String SEGMENT = "segment"; static final String SEGMENT_TYPE = "INTEGER NOT NULL"; public static final String WAYPOINT = "waypoint"; static final String WAYPOINT_TYPE = "INTEGER NOT NULL"; public static final String URI = "uri"; static final String URI_TYPE = "TEXT"; static final String _ID_TYPE = "INTEGER PRIMARY KEY AUTOINCREMENT"; } /** * Columns from the media table. * * @author rene */ public static class MetaDataColumns { /** The track _id to which this segment belongs */ public static final String TRACK = "track"; static final String TRACK_TYPE = "INTEGER NOT NULL"; public static final String SEGMENT = "segment"; static final String SEGMENT_TYPE = "INTEGER"; public static final String WAYPOINT = "waypoint"; static final String WAYPOINT_TYPE = "INTEGER"; public static final String KEY = "key"; static final String KEY_TYPE = "TEXT NOT NULL"; public static final String VALUE = "value"; static final String VALUE_TYPE = "TEXT NOT NULL"; static final String _ID_TYPE = "INTEGER PRIMARY KEY AUTOINCREMENT"; } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.db; import java.util.Date; import nl.sogeti.android.gpstracker.db.GPStracking.Media; import nl.sogeti.android.gpstracker.db.GPStracking.MediaColumns; import nl.sogeti.android.gpstracker.db.GPStracking.MetaData; import nl.sogeti.android.gpstracker.db.GPStracking.Segments; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.db.GPStracking.TracksColumns; import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints; import nl.sogeti.android.gpstracker.db.GPStracking.WaypointsColumns; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.location.Location; import android.net.Uri; import android.util.Log; /** * Class to hold bare-metal database operations exposed as functionality blocks * To be used by database adapters, like a content provider, that implement a * required functionality set * * @version $Id$ * @author rene (c) Jan 22, 2009, Sogeti B.V. */ public class DatabaseHelper extends SQLiteOpenHelper { private Context mContext; private final static String TAG = "OGT.DatabaseHelper"; public DatabaseHelper(Context context) { super(context, GPStracking.DATABASE_NAME, null, GPStracking.DATABASE_VERSION); this.mContext = context; } /* * (non-Javadoc) * @see * android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite * .SQLiteDatabase) */ @Override public void onCreate(SQLiteDatabase db) { db.execSQL(Waypoints.CREATE_STATEMENT); db.execSQL(Segments.CREATE_STATMENT); db.execSQL(Tracks.CREATE_STATEMENT); db.execSQL(Media.CREATE_STATEMENT); db.execSQL(MetaData.CREATE_STATEMENT); } /** * Will update version 1 through 5 to version 8 * * @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, * int, int) * @see GPStracking.DATABASE_VERSION */ @Override public void onUpgrade(SQLiteDatabase db, int current, int targetVersion) { Log.i(TAG, "Upgrading db from " + current + " to " + targetVersion); if (current <= 5) // From 1-5 to 6 (these before are the same before) { current = 6; } if (current == 6) // From 6 to 7 ( no changes ) { current = 7; } if (current == 7) // From 7 to 8 ( more waypoints data ) { for (String statement : Waypoints.UPGRADE_STATEMENT_7_TO_8) { db.execSQL(statement); } current = 8; } if (current == 8) // From 8 to 9 ( media Uri data ) { db.execSQL(Media.CREATE_STATEMENT); current = 9; } if (current == 9) // From 9 to 10 ( metadata ) { db.execSQL(MetaData.CREATE_STATEMENT); current = 10; } } public void vacuum() { new Thread() { @Override public void run() { SQLiteDatabase sqldb = getWritableDatabase(); sqldb.execSQL("VACUUM"); } }.start(); } int bulkInsertWaypoint(long trackId, long segmentId, ContentValues[] valuesArray) { if (trackId < 0 || segmentId < 0) { throw new IllegalArgumentException("Track and segments may not the less then 0."); } int inserted = 0; SQLiteDatabase sqldb = getWritableDatabase(); sqldb.beginTransaction(); try { for (ContentValues args : valuesArray) { args.put(Waypoints.SEGMENT, segmentId); long id = sqldb.insert(Waypoints.TABLE, null, args); if (id >= 0) { inserted++; } } sqldb.setTransactionSuccessful(); } finally { if (sqldb.inTransaction()) { sqldb.endTransaction(); } } return inserted; } /** * Creates a waypoint under the current track segment with the current time * on which the waypoint is reached * * @param track track * @param segment segment * @param latitude latitude * @param longitude longitude * @param time time * @param speed the measured speed * @return */ long insertWaypoint(long trackId, long segmentId, Location location) { if (trackId < 0 || segmentId < 0) { throw new IllegalArgumentException("Track and segments may not the less then 0."); } SQLiteDatabase sqldb = getWritableDatabase(); ContentValues args = new ContentValues(); args.put(WaypointsColumns.SEGMENT, segmentId); args.put(WaypointsColumns.TIME, location.getTime()); args.put(WaypointsColumns.LATITUDE, location.getLatitude()); args.put(WaypointsColumns.LONGITUDE, location.getLongitude()); args.put(WaypointsColumns.SPEED, location.getSpeed()); args.put(WaypointsColumns.ACCURACY, location.getAccuracy()); args.put(WaypointsColumns.ALTITUDE, location.getAltitude()); args.put(WaypointsColumns.BEARING, location.getBearing()); long waypointId = sqldb.insert(Waypoints.TABLE, null, args); ContentResolver resolver = this.mContext.getContentResolver(); Uri notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments/" + segmentId + "/waypoints"); resolver.notifyChange(notifyUri, null); // Log.d( TAG, "Waypoint stored: "+notifyUri); return waypointId; } /** * Insert a URI for a given waypoint/segment/track in the media table * * @param trackId * @param segmentId * @param waypointId * @param mediaUri * @return */ long insertMedia(long trackId, long segmentId, long waypointId, String mediaUri) { if (trackId < 0 || segmentId < 0 || waypointId < 0) { throw new IllegalArgumentException("Track, segments and waypoint may not the less then 0."); } SQLiteDatabase sqldb = getWritableDatabase(); ContentValues args = new ContentValues(); args.put(MediaColumns.TRACK, trackId); args.put(MediaColumns.SEGMENT, segmentId); args.put(MediaColumns.WAYPOINT, waypointId); args.put(MediaColumns.URI, mediaUri); // Log.d( TAG, "Media stored in the datebase: "+mediaUri ); long mediaId = sqldb.insert(Media.TABLE, null, args); ContentResolver resolver = this.mContext.getContentResolver(); Uri notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments/" + segmentId + "/waypoints/" + waypointId + "/media"); resolver.notifyChange(notifyUri, null); // Log.d( TAG, "Notify: "+notifyUri ); resolver.notifyChange(Media.CONTENT_URI, null); // Log.d( TAG, "Notify: "+Media.CONTENT_URI ); return mediaId; } /** * Insert a key/value pair as meta-data for a track and optionally narrow the * scope by segment or segment/waypoint * * @param trackId * @param segmentId * @param waypointId * @param key * @param value * @return */ long insertOrUpdateMetaData(long trackId, long segmentId, long waypointId, String key, String value) { long metaDataId = -1; if (trackId < 0 && key != null && value != null) { throw new IllegalArgumentException("Track, key and value must be provided"); } if (waypointId >= 0 && segmentId < 0) { throw new IllegalArgumentException("Waypoint must have segment"); } ContentValues args = new ContentValues(); args.put(MetaData.TRACK, trackId); args.put(MetaData.SEGMENT, segmentId); args.put(MetaData.WAYPOINT, waypointId); args.put(MetaData.KEY, key); args.put(MetaData.VALUE, value); String whereClause = MetaData.TRACK + " = ? AND " + MetaData.SEGMENT + " = ? AND " + MetaData.WAYPOINT + " = ? AND " + MetaData.KEY + " = ?"; String[] whereArgs = new String[] { Long.toString(trackId), Long.toString(segmentId), Long.toString(waypointId), key }; SQLiteDatabase sqldb = getWritableDatabase(); int updated = sqldb.update(MetaData.TABLE, args, whereClause, whereArgs); if (updated == 0) { metaDataId = sqldb.insert(MetaData.TABLE, null, args); } else { Cursor c = null; try { c = sqldb.query(MetaData.TABLE, new String[] { MetaData._ID }, whereClause, whereArgs, null, null, null); if( c.moveToFirst() ) { metaDataId = c.getLong(0); } } finally { if (c != null) { c.close(); } } } ContentResolver resolver = this.mContext.getContentResolver(); Uri notifyUri; if (segmentId >= 0 && waypointId >= 0) { notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments/" + segmentId + "/waypoints/" + waypointId + "/metadata"); } else if (segmentId >= 0) { notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments/" + segmentId + "/metadata"); } else { notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/metadata"); } resolver.notifyChange(notifyUri, null); resolver.notifyChange(MetaData.CONTENT_URI, null); return metaDataId; } /** * Deletes a single track and all underlying segments, waypoints, media and * metadata * * @param trackId * @return */ int deleteTrack(long trackId) { SQLiteDatabase sqldb = getWritableDatabase(); int affected = 0; Cursor cursor = null; long segmentId = -1; long metadataId = -1; try { sqldb.beginTransaction(); // Iterate on each segement to delete each cursor = sqldb.query(Segments.TABLE, new String[] { Segments._ID }, Segments.TRACK + "= ?", new String[] { String.valueOf(trackId) }, null, null, null, null); if (cursor.moveToFirst()) { do { segmentId = cursor.getLong(0); affected += deleteSegment(sqldb, trackId, segmentId); } while (cursor.moveToNext()); } else { Log.e(TAG, "Did not find the last active segment"); } // Delete the track affected += sqldb.delete(Tracks.TABLE, Tracks._ID + "= ?", new String[] { String.valueOf(trackId) }); // Delete remaining meta-data affected += sqldb.delete(MetaData.TABLE, MetaData.TRACK + "= ?", new String[] { String.valueOf(trackId) }); cursor = sqldb.query(MetaData.TABLE, new String[] { MetaData._ID }, MetaData.TRACK + "= ?", new String[] { String.valueOf(trackId) }, null, null, null, null); if (cursor.moveToFirst()) { do { metadataId = cursor.getLong(0); affected += deleteMetaData(metadataId); } while (cursor.moveToNext()); } sqldb.setTransactionSuccessful(); } finally { if (cursor != null) { cursor.close(); } if (sqldb.inTransaction()) { sqldb.endTransaction(); } } ContentResolver resolver = this.mContext.getContentResolver(); resolver.notifyChange(Tracks.CONTENT_URI, null); resolver.notifyChange(ContentUris.withAppendedId(Tracks.CONTENT_URI, trackId), null); return affected; } /** * @param mediaId * @return */ int deleteMedia(long mediaId) { SQLiteDatabase sqldb = getWritableDatabase(); Cursor cursor = null; long trackId = -1; long segmentId = -1; long waypointId = -1; try { cursor = sqldb.query(Media.TABLE, new String[] { Media.TRACK, Media.SEGMENT, Media.WAYPOINT }, Media._ID + "= ?", new String[] { String.valueOf(mediaId) }, null, null, null, null); if (cursor.moveToFirst()) { trackId = cursor.getLong(0); segmentId = cursor.getLong(0); waypointId = cursor.getLong(0); } else { Log.e(TAG, "Did not find the media element to delete"); } } finally { if (cursor != null) { cursor.close(); } } int affected = sqldb.delete(Media.TABLE, Media._ID + "= ?", new String[] { String.valueOf(mediaId) }); ContentResolver resolver = this.mContext.getContentResolver(); Uri notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments/" + segmentId + "/waypoints/" + waypointId + "/media"); resolver.notifyChange(notifyUri, null); notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments/" + segmentId + "/media"); resolver.notifyChange(notifyUri, null); notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/media"); resolver.notifyChange(notifyUri, null); resolver.notifyChange(ContentUris.withAppendedId(Media.CONTENT_URI, mediaId), null); return affected; } int deleteMetaData(long metadataId) { SQLiteDatabase sqldb = getWritableDatabase(); Cursor cursor = null; long trackId = -1; long segmentId = -1; long waypointId = -1; try { cursor = sqldb.query(MetaData.TABLE, new String[] { MetaData.TRACK, MetaData.SEGMENT, MetaData.WAYPOINT }, MetaData._ID + "= ?", new String[] { String.valueOf(metadataId) }, null, null, null, null); if (cursor.moveToFirst()) { trackId = cursor.getLong(0); segmentId = cursor.getLong(0); waypointId = cursor.getLong(0); } else { Log.e(TAG, "Did not find the media element to delete"); } } finally { if (cursor != null) { cursor.close(); } } int affected = sqldb.delete(MetaData.TABLE, MetaData._ID + "= ?", new String[] { String.valueOf(metadataId) }); ContentResolver resolver = this.mContext.getContentResolver(); Uri notifyUri; if (trackId >= 0 && segmentId >= 0 && waypointId >= 0) { notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments/" + segmentId + "/waypoints/" + waypointId + "/media"); resolver.notifyChange(notifyUri, null); } if (trackId >= 0 && segmentId >= 0) { notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments/" + segmentId + "/media"); resolver.notifyChange(notifyUri, null); } notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/media"); resolver.notifyChange(notifyUri, null); resolver.notifyChange(ContentUris.withAppendedId(Media.CONTENT_URI, metadataId), null); return affected; } /** * Delete a segment and all member waypoints * * @param sqldb The SQLiteDatabase in question * @param trackId The track id of this delete * @param segmentId The segment that needs deleting * @return */ int deleteSegment(SQLiteDatabase sqldb, long trackId, long segmentId) { int affected = sqldb.delete(Segments.TABLE, Segments._ID + "= ?", new String[] { String.valueOf(segmentId) }); // Delete all waypoints from segments affected += sqldb.delete(Waypoints.TABLE, Waypoints.SEGMENT + "= ?", new String[] { String.valueOf(segmentId) }); // Delete all media from segment affected += sqldb.delete(Media.TABLE, Media.TRACK + "= ? AND " + Media.SEGMENT + "= ?", new String[] { String.valueOf(trackId), String.valueOf(segmentId) }); // Delete meta-data affected += sqldb.delete(MetaData.TABLE, MetaData.TRACK + "= ? AND " + MetaData.SEGMENT + "= ?", new String[] { String.valueOf(trackId), String.valueOf(segmentId) }); ContentResolver resolver = this.mContext.getContentResolver(); resolver.notifyChange(Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments/" + segmentId), null); resolver.notifyChange(Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments"), null); return affected; } int updateTrack(long trackId, String name) { int updates; String whereclause = Tracks._ID + " = " + trackId; ContentValues args = new ContentValues(); args.put(Tracks.NAME, name); // Execute the query. SQLiteDatabase mDb = getWritableDatabase(); updates = mDb.update(Tracks.TABLE, args, whereclause, null); ContentResolver resolver = this.mContext.getContentResolver(); Uri notifyUri = ContentUris.withAppendedId(Tracks.CONTENT_URI, trackId); resolver.notifyChange(notifyUri, null); return updates; } /** * Insert a key/value pair as meta-data for a track and optionally narrow the * scope by segment or segment/waypoint * * @param trackId * @param segmentId * @param waypointId * @param key * @param value * @return */ int updateMetaData(long trackId, long segmentId, long waypointId, long metadataId, String selection, String[] selectionArgs, String value) { { if ((metadataId < 0 && trackId < 0)) { throw new IllegalArgumentException("Track or meta-data id be provided"); } if (trackId >= 0 && (selection == null || !selection.contains("?") || selectionArgs.length != 1)) { throw new IllegalArgumentException("A where clause selection must be provided to select the correct KEY"); } if (trackId >= 0 && waypointId >= 0 && segmentId < 0) { throw new IllegalArgumentException("Waypoint must have segment"); } SQLiteDatabase sqldb = getWritableDatabase(); String[] whereParams; String whereclause; if (metadataId >= 0) { whereclause = MetaData._ID + " = ? "; whereParams = new String[] { Long.toString(metadataId) }; } else { whereclause = MetaData.TRACK + " = ? AND " + MetaData.SEGMENT + " = ? AND " + MetaData.WAYPOINT + " = ? AND " + MetaData.KEY + " = ? "; whereParams = new String[] { Long.toString(trackId), Long.toString(segmentId), Long.toString(waypointId), selectionArgs[0] }; } ContentValues args = new ContentValues(); args.put(MetaData.VALUE, value); int updates = sqldb.update(MetaData.TABLE, args, whereclause, whereParams); ContentResolver resolver = this.mContext.getContentResolver(); Uri notifyUri; if (trackId >= 0 && segmentId >= 0 && waypointId >= 0) { notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments/" + segmentId + "/waypoints/" + waypointId + "/metadata"); } else if (trackId >= 0 && segmentId >= 0) { notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments/" + segmentId + "/metadata"); } else if (trackId >= 0) { notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/metadata"); } else { notifyUri = Uri.withAppendedPath(MetaData.CONTENT_URI, "" + metadataId); } resolver.notifyChange(notifyUri, null); resolver.notifyChange(MetaData.CONTENT_URI, null); return updates; } } /** * Move to a fresh track with a new first segment for this track * * @return */ long toNextTrack(String name) { long currentTime = new Date().getTime(); ContentValues args = new ContentValues(); args.put(TracksColumns.NAME, name); args.put(TracksColumns.CREATION_TIME, currentTime); SQLiteDatabase sqldb = getWritableDatabase(); long trackId = sqldb.insert(Tracks.TABLE, null, args); ContentResolver resolver = this.mContext.getContentResolver(); resolver.notifyChange(Tracks.CONTENT_URI, null); return trackId; } /** * Moves to a fresh segment to which waypoints can be connected * * @return */ long toNextSegment(long trackId) { SQLiteDatabase sqldb = getWritableDatabase(); ContentValues args = new ContentValues(); args.put(Segments.TRACK, trackId); long segmentId = sqldb.insert(Segments.TABLE, null, args); ContentResolver resolver = this.mContext.getContentResolver(); resolver.notifyChange(Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments"), null); return segmentId; } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.db; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import nl.sogeti.android.gpstracker.db.GPStracking.Media; import nl.sogeti.android.gpstracker.db.GPStracking.MetaData; import nl.sogeti.android.gpstracker.db.GPStracking.Segments; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints; import android.app.SearchManager; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.location.Location; import android.net.Uri; import android.provider.LiveFolders; import android.util.Log; /** * Goal of this Content Provider is to make the GPS Tracking information uniformly * available to this application and even other applications. The GPS-tracking * database can hold, tracks, segments or waypoints * <p> * A track is an actual route taken from start to finish. All the GPS locations * collected are waypoints. Waypoints taken in sequence without loss of GPS-signal * are considered connected and are grouped in segments. A route is build up out of * 1 or more segments. * <p> * For example:<br> * <code>content://nl.sogeti.android.gpstracker/tracks</code> * is the URI that returns all the stored tracks or starts a new track on insert * <p> * <code>content://nl.sogeti.android.gpstracker/tracks/2</code> * is the URI string that would return a single result row, the track with ID = 23. * <p> * <code>content://nl.sogeti.android.gpstracker/tracks/2/segments</code> is the URI that returns * all the stored segments of a track with ID = 2 or starts a new segment on insert * <p> * <code>content://nl.sogeti.android.gpstracker/tracks/2/waypoints</code> is the URI that returns * all the stored waypoints of a track with ID = 2 * <p> * <code>content://nl.sogeti.android.gpstracker/tracks/2/segments</code> is the URI that returns * all the stored segments of a track with ID = 2 * <p> * <code>content://nl.sogeti.android.gpstracker/tracks/2/segments/3</code> is * the URI string that would return a single result row, the segment with ID = 3 of a track with ID = 2 . * <p> * <code>content://nl.sogeti.android.gpstracker/tracks/2/segments/1/waypoints</code> is the URI that * returns all the waypoints of a segment 1 of track 2. * <p> * <code>content://nl.sogeti.android.gpstracker/tracks/2/segments/1/waypoints/52</code> is the URI string that * would return a single result row, the waypoint with ID = 52 * <p> * Media is stored under a waypoint and may be queried as:<br> * <code>content://nl.sogeti.android.gpstracker/tracks/2/segments/3/waypoints/22/media</code> * <p> * * * All media for a segment can be queried with:<br> * <code>content://nl.sogeti.android.gpstracker/tracks/2/segments/3/media</code> * <p> * All media for a track can be queried with:<br> * <code>content://nl.sogeti.android.gpstracker/tracks/2/media</code> * * <p> * The whole set of collected media may be queried as:<br> * <code>content://nl.sogeti.android.gpstracker/media</code> * <p> * A single media is stored with an ID, for instance ID = 12:<br> * <code>content://nl.sogeti.android.gpstracker/media/12</code> * <p> * The whole set of collected media may be queried as:<br> * <code>content://nl.sogeti.android.gpstracker/media</code> * <p> * * * Meta-data regarding a single waypoint may be queried as:<br> * <code>content://nl.sogeti.android.gpstracker/tracks/2/segments/3/waypoints/22/metadata</code> * <p> * Meta-data regarding a single segment as whole may be queried as:<br> * <code>content://nl.sogeti.android.gpstracker/tracks/2/segments/3/metadata</code> * Note: This does not include meta-data of waypoints. * <p> * Meta-data regarding a single track as a whole may be queried as:<br> * <code>content://nl.sogeti.android.gpstracker/tracks/2/metadata</code> * Note: This does not include meta-data of waypoints or segments. * * @version $Id$ * @author rene (c) Jan 22, 2009, Sogeti B.V. */ public class GPStrackingProvider extends ContentProvider { private static final String TAG = "OGT.GPStrackingProvider"; /* Action types as numbers for using the UriMatcher */ private static final int TRACKS = 1; private static final int TRACK_ID = 2; private static final int TRACK_MEDIA = 3; private static final int TRACK_WAYPOINTS = 4; private static final int SEGMENTS = 5; private static final int SEGMENT_ID = 6; private static final int SEGMENT_MEDIA = 7; private static final int WAYPOINTS = 8; private static final int WAYPOINT_ID = 9; private static final int WAYPOINT_MEDIA = 10; private static final int SEARCH_SUGGEST_ID = 11; private static final int LIVE_FOLDERS = 12; private static final int MEDIA = 13; private static final int MEDIA_ID = 14; private static final int TRACK_METADATA = 15; private static final int SEGMENT_METADATA = 16; private static final int WAYPOINT_METADATA = 17; private static final int METADATA = 18; private static final int METADATA_ID = 19; private static final String[] SUGGEST_PROJECTION = new String[] { Tracks._ID, Tracks.NAME+" AS "+SearchManager.SUGGEST_COLUMN_TEXT_1, "datetime("+Tracks.CREATION_TIME+"/1000, 'unixepoch') as "+SearchManager.SUGGEST_COLUMN_TEXT_2, Tracks._ID+" AS "+SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID }; private static final String[] LIVE_PROJECTION = new String[] { Tracks._ID+" AS "+LiveFolders._ID, Tracks.NAME+" AS "+ LiveFolders.NAME, "datetime("+Tracks.CREATION_TIME+"/1000, 'unixepoch') as "+LiveFolders.DESCRIPTION }; private static UriMatcher sURIMatcher = new UriMatcher( UriMatcher.NO_MATCH ); /** * Although it is documented that in addURI(null, path, 0) "path" should be an absolute path this does not seem to work. A relative path gets the jobs done and matches an absolute path. */ static { GPStrackingProvider.sURIMatcher = new UriMatcher( UriMatcher.NO_MATCH ); GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "tracks", GPStrackingProvider.TRACKS ); GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "tracks/#", GPStrackingProvider.TRACK_ID ); GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "tracks/#/media", GPStrackingProvider.TRACK_MEDIA ); GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "tracks/#/metadata", GPStrackingProvider.TRACK_METADATA ); GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "tracks/#/waypoints", GPStrackingProvider.TRACK_WAYPOINTS ); GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "tracks/#/segments", GPStrackingProvider.SEGMENTS ); GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "tracks/#/segments/#", GPStrackingProvider.SEGMENT_ID ); GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "tracks/#/segments/#/media", GPStrackingProvider.SEGMENT_MEDIA ); GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "tracks/#/segments/#/metadata", GPStrackingProvider.SEGMENT_METADATA ); GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "tracks/#/segments/#/waypoints", GPStrackingProvider.WAYPOINTS ); GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "tracks/#/segments/#/waypoints/#", GPStrackingProvider.WAYPOINT_ID ); GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "tracks/#/segments/#/waypoints/#/media", GPStrackingProvider.WAYPOINT_MEDIA ); GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "tracks/#/segments/#/waypoints/#/metadata", GPStrackingProvider.WAYPOINT_METADATA ); GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "media", GPStrackingProvider.MEDIA ); GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "media/#", GPStrackingProvider.MEDIA_ID ); GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "metadata", GPStrackingProvider.METADATA ); GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "metadata/#", GPStrackingProvider.METADATA_ID ); GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "live_folders/tracks", GPStrackingProvider.LIVE_FOLDERS ); GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "search_suggest_query", GPStrackingProvider.SEARCH_SUGGEST_ID ); } private DatabaseHelper mDbHelper; /** * (non-Javadoc) * @see android.content.ContentProvider#onCreate() */ @Override public boolean onCreate() { if (this.mDbHelper == null) { this.mDbHelper = new DatabaseHelper( getContext() ); } return true; } /** * (non-Javadoc) * @see android.content.ContentProvider#getType(android.net.Uri) */ @Override public String getType( Uri uri ) { int match = GPStrackingProvider.sURIMatcher.match( uri ); String mime = null; switch (match) { case TRACKS: mime = Tracks.CONTENT_TYPE; break; case TRACK_ID: mime = Tracks.CONTENT_ITEM_TYPE; break; case SEGMENTS: mime = Segments.CONTENT_TYPE; break; case SEGMENT_ID: mime = Segments.CONTENT_ITEM_TYPE; break; case WAYPOINTS: mime = Waypoints.CONTENT_TYPE; break; case WAYPOINT_ID: mime = Waypoints.CONTENT_ITEM_TYPE; break; case MEDIA_ID: case TRACK_MEDIA: case SEGMENT_MEDIA: case WAYPOINT_MEDIA: mime = Media.CONTENT_ITEM_TYPE; break; case METADATA_ID: case TRACK_METADATA: case SEGMENT_METADATA: case WAYPOINT_METADATA: mime = MetaData.CONTENT_ITEM_TYPE; break; case UriMatcher.NO_MATCH: default: Log.w(TAG, "There is not MIME type defined for URI "+uri); break; } return mime; } /** * (non-Javadoc) * @see android.content.ContentProvider#insert(android.net.Uri, android.content.ContentValues) */ @Override public Uri insert( Uri uri, ContentValues values ) { //Log.d( TAG, "insert on "+uri ); Uri insertedUri = null; int match = GPStrackingProvider.sURIMatcher.match( uri ); List<String> pathSegments = null; long trackId = -1; long segmentId = -1; long waypointId = -1; long mediaId = -1; String key; String value; switch (match) { case WAYPOINTS: pathSegments = uri.getPathSegments(); trackId = Long.parseLong( pathSegments.get( 1 ) ); segmentId = Long.parseLong( pathSegments.get( 3 ) ); Location loc = new Location( TAG ); Double latitude = values.getAsDouble( Waypoints.LATITUDE ); Double longitude = values.getAsDouble( Waypoints.LONGITUDE ); Long time = values.getAsLong( Waypoints.TIME ); Float speed = values.getAsFloat( Waypoints.SPEED ); if( time == null ) { time = System.currentTimeMillis(); } if( speed == null ) { speed = 0f; } loc.setLatitude( latitude ); loc.setLongitude( longitude ); loc.setTime( time ); loc.setSpeed( speed ); if( values.containsKey( Waypoints.ACCURACY ) ) { loc.setAccuracy( values.getAsFloat( Waypoints.ACCURACY ) ); } if( values.containsKey( Waypoints.ALTITUDE ) ) { loc.setAltitude( values.getAsDouble( Waypoints.ALTITUDE ) ); } if( values.containsKey( Waypoints.BEARING ) ) { loc.setBearing( values.getAsFloat( Waypoints.BEARING ) ); } waypointId = this.mDbHelper.insertWaypoint( trackId, segmentId, loc ); // Log.d( TAG, "Have inserted to segment "+segmentId+" with waypoint "+waypointId ); insertedUri = ContentUris.withAppendedId( uri, waypointId ); break; case WAYPOINT_MEDIA: pathSegments = uri.getPathSegments(); trackId = Long.parseLong( pathSegments.get( 1 ) ); segmentId = Long.parseLong( pathSegments.get( 3 ) ); waypointId = Long.parseLong( pathSegments.get( 5 ) ); String mediaUri = values.getAsString( Media.URI ); mediaId = this.mDbHelper.insertMedia( trackId, segmentId, waypointId, mediaUri ); insertedUri = ContentUris.withAppendedId( Media.CONTENT_URI, mediaId ); break; case SEGMENTS: pathSegments = uri.getPathSegments(); trackId = Integer.parseInt( pathSegments.get( 1 ) ); segmentId = this.mDbHelper.toNextSegment( trackId ); insertedUri = ContentUris.withAppendedId( uri, segmentId ); break; case TRACKS: String name = ( values == null ) ? "" : values.getAsString( Tracks.NAME ); trackId = this.mDbHelper.toNextTrack( name ); insertedUri = ContentUris.withAppendedId( uri, trackId ); break; case TRACK_METADATA: pathSegments = uri.getPathSegments(); trackId = Long.parseLong( pathSegments.get( 1 ) ); key = values.getAsString( MetaData.KEY ); value = values.getAsString( MetaData.VALUE ); mediaId = this.mDbHelper.insertOrUpdateMetaData( trackId, -1L, -1L, key, value ); insertedUri = ContentUris.withAppendedId( MetaData.CONTENT_URI, mediaId ); break; case SEGMENT_METADATA: pathSegments = uri.getPathSegments(); trackId = Long.parseLong( pathSegments.get( 1 ) ); segmentId = Long.parseLong( pathSegments.get( 3 ) ); key = values.getAsString( MetaData.KEY ); value = values.getAsString( MetaData.VALUE ); mediaId = this.mDbHelper.insertOrUpdateMetaData( trackId, segmentId, -1L, key, value ); insertedUri = ContentUris.withAppendedId( MetaData.CONTENT_URI, mediaId ); break; case WAYPOINT_METADATA: pathSegments = uri.getPathSegments(); trackId = Long.parseLong( pathSegments.get( 1 ) ); segmentId = Long.parseLong( pathSegments.get( 3 ) ); waypointId = Long.parseLong( pathSegments.get( 5 ) ); key = values.getAsString( MetaData.KEY ); value = values.getAsString( MetaData.VALUE ); mediaId = this.mDbHelper.insertOrUpdateMetaData( trackId, segmentId, waypointId, key, value ); insertedUri = ContentUris.withAppendedId( MetaData.CONTENT_URI, mediaId ); break; default: Log.e( GPStrackingProvider.TAG, "Unable to match the insert URI: " + uri.toString() ); insertedUri = null; break; } return insertedUri; } /** * (non-Javadoc) * @see android.content.ContentProvider#query(android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String) */ @Override public Cursor query( Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder ) { // Log.d( TAG, "Query on Uri:"+uri ); int match = GPStrackingProvider.sURIMatcher.match( uri ); String tableName = null; String innerSelection = "1"; String[] innerSelectionArgs = new String[]{}; String sortorder = sortOrder; List<String> pathSegments = uri.getPathSegments(); switch (match) { case TRACKS: tableName = Tracks.TABLE; break; case TRACK_ID: tableName = Tracks.TABLE; innerSelection = Tracks._ID + " = ? "; innerSelectionArgs = new String[]{ pathSegments.get( 1 ) }; break; case SEGMENTS: tableName = Segments.TABLE; innerSelection = Segments.TRACK + " = ? "; innerSelectionArgs = new String[]{ pathSegments.get( 1 ) }; break; case SEGMENT_ID: tableName = Segments.TABLE; innerSelection = Segments.TRACK + " = ? and " + Segments._ID + " = ? "; innerSelectionArgs = new String[]{ pathSegments.get( 1 ), pathSegments.get( 3 ) }; break; case WAYPOINTS: tableName = Waypoints.TABLE; innerSelection = Waypoints.SEGMENT + " = ? "; innerSelectionArgs = new String[]{ pathSegments.get( 3 ) }; break; case WAYPOINT_ID: tableName = Waypoints.TABLE; innerSelection = Waypoints.SEGMENT + " = ? and " + Waypoints._ID + " = ? "; innerSelectionArgs = new String[]{ pathSegments.get( 3 ), pathSegments.get( 5 ) }; break; case TRACK_WAYPOINTS: tableName = Waypoints.TABLE + " INNER JOIN " + Segments.TABLE + " ON "+ Segments.TABLE+"."+Segments._ID +"=="+ Waypoints.SEGMENT; innerSelection = Segments.TRACK + " = ? "; innerSelectionArgs = new String[]{ pathSegments.get( 1 ) }; break; case GPStrackingProvider.MEDIA: tableName = Media.TABLE; break; case GPStrackingProvider.MEDIA_ID: tableName = Media.TABLE; innerSelection = Media._ID + " = ? "; innerSelectionArgs = new String[]{ pathSegments.get( 1 ) }; break; case TRACK_MEDIA: tableName = Media.TABLE; innerSelection = Media.TRACK + " = ? "; innerSelectionArgs = new String[]{ pathSegments.get( 1 ) }; break; case SEGMENT_MEDIA: tableName = Media.TABLE; innerSelection = Media.TRACK + " = ? and " + Media.SEGMENT + " = ? "; innerSelectionArgs = new String[]{ pathSegments.get( 1 ), pathSegments.get( 3 ) }; break; case WAYPOINT_MEDIA: tableName = Media.TABLE; innerSelection = Media.TRACK + " = ? and " + Media.SEGMENT + " = ? and " + Media.WAYPOINT + " = ? "; innerSelectionArgs = new String[]{ pathSegments.get( 1 ),pathSegments.get( 3 ), pathSegments.get( 5 )}; break; case TRACK_METADATA: tableName = MetaData.TABLE; innerSelection = MetaData.TRACK + " = ? and " + MetaData.SEGMENT + " = ? and " + MetaData.WAYPOINT + " = ? "; innerSelectionArgs = new String[]{ pathSegments.get( 1 ), "-1", "-1" }; break; case SEGMENT_METADATA: tableName = MetaData.TABLE; innerSelection = MetaData.TRACK + " = ? and " + MetaData.SEGMENT + " = ? and " + MetaData.WAYPOINT + " = ? "; innerSelectionArgs = new String[]{pathSegments.get( 1 ), pathSegments.get( 3 ), "-1" }; break; case WAYPOINT_METADATA: tableName = MetaData.TABLE; innerSelection = MetaData.TRACK + " = ? and " + MetaData.SEGMENT + " = ? and " + MetaData.WAYPOINT + " = ? "; innerSelectionArgs = new String[]{ pathSegments.get( 1 ), pathSegments.get( 3 ), pathSegments.get( 5 ) }; break; case GPStrackingProvider.METADATA: tableName = MetaData.TABLE; break; case GPStrackingProvider.METADATA_ID: tableName = MetaData.TABLE; innerSelection = MetaData._ID + " = ? "; innerSelectionArgs = new String[]{ pathSegments.get( 1 ) }; break; case SEARCH_SUGGEST_ID: tableName = Tracks.TABLE; if( selectionArgs[0] == null || selectionArgs[0].equals( "" ) ) { selection = null; selectionArgs = null; sortorder = Tracks.CREATION_TIME+" desc"; } else { selectionArgs[0] = "%" +selectionArgs[0]+ "%"; } projection = SUGGEST_PROJECTION; break; case LIVE_FOLDERS: tableName = Tracks.TABLE; projection = LIVE_PROJECTION; sortorder = Tracks.CREATION_TIME+" desc"; break; default: Log.e( GPStrackingProvider.TAG, "Unable to come to an action in the query uri: " + uri.toString() ); return null; } // SQLiteQueryBuilder is a helper class that creates the // proper SQL syntax for us. SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder(); // Set the table we're querying. qBuilder.setTables( tableName ); if( selection == null ) { selection = innerSelection; } else { selection = "( "+ innerSelection + " ) and " + selection; } LinkedList<String> allArgs = new LinkedList<String>(); if( selectionArgs == null ) { allArgs.addAll(Arrays.asList(innerSelectionArgs)); } else { allArgs.addAll(Arrays.asList(innerSelectionArgs)); allArgs.addAll(Arrays.asList(selectionArgs)); } selectionArgs = allArgs.toArray(innerSelectionArgs); // Make the query. SQLiteDatabase mDb = this.mDbHelper.getWritableDatabase(); Cursor c = qBuilder.query( mDb, projection, selection, selectionArgs, null, null, sortorder ); c.setNotificationUri( getContext().getContentResolver(), uri ); return c; } /** * (non-Javadoc) * @see android.content.ContentProvider#update(android.net.Uri, android.content.ContentValues, java.lang.String, java.lang.String[]) */ @Override public int update( Uri uri, ContentValues givenValues, String selection, String[] selectionArgs ) { int updates = -1 ; long trackId; long segmentId; long waypointId; long metaDataId; List<String> pathSegments; int match = GPStrackingProvider.sURIMatcher.match( uri ); String value; switch (match) { case TRACK_ID: trackId = new Long( uri.getLastPathSegment() ).longValue(); String name = givenValues.getAsString( Tracks.NAME ); updates = mDbHelper.updateTrack(trackId, name); break; case TRACK_METADATA: pathSegments = uri.getPathSegments(); trackId = Long.parseLong( pathSegments.get( 1 ) ); value = givenValues.getAsString( MetaData.VALUE ); updates = mDbHelper.updateMetaData( trackId, -1L, -1L, -1L, selection, selectionArgs, value); break; case SEGMENT_METADATA: pathSegments = uri.getPathSegments(); trackId = Long.parseLong( pathSegments.get( 1 ) ); segmentId = Long.parseLong( pathSegments.get( 3 ) ); value = givenValues.getAsString( MetaData.VALUE ); updates = mDbHelper.updateMetaData( trackId, segmentId, -1L, -1L, selection, selectionArgs, value); break; case WAYPOINT_METADATA: pathSegments = uri.getPathSegments(); trackId = Long.parseLong( pathSegments.get( 1 ) ); segmentId = Long.parseLong( pathSegments.get( 3 ) ); waypointId = Long.parseLong( pathSegments.get( 5 ) ); value = givenValues.getAsString( MetaData.VALUE ); updates = mDbHelper.updateMetaData( trackId, segmentId, waypointId, -1L, selection, selectionArgs, value); break; case METADATA_ID: pathSegments = uri.getPathSegments(); metaDataId = Long.parseLong( pathSegments.get( 1 ) ); value = givenValues.getAsString( MetaData.VALUE ); updates = mDbHelper.updateMetaData( -1L, -1L, -1L, metaDataId, selection, selectionArgs, value); break; default: Log.e( GPStrackingProvider.TAG, "Unable to come to an action in the query uri" + uri.toString() ); return -1; } return updates; } /** * (non-Javadoc) * @see android.content.ContentProvider#delete(android.net.Uri, java.lang.String, java.lang.String[]) */ @Override public int delete( Uri uri, String selection, String[] selectionArgs ) { int match = GPStrackingProvider.sURIMatcher.match( uri ); int affected = 0; switch( match ) { case GPStrackingProvider.TRACK_ID: affected = this.mDbHelper.deleteTrack( new Long( uri.getLastPathSegment() ).longValue() ); break; case GPStrackingProvider.MEDIA_ID: affected = this.mDbHelper.deleteMedia( new Long( uri.getLastPathSegment() ).longValue() ); break; case GPStrackingProvider.METADATA_ID: affected = this.mDbHelper.deleteMetaData( new Long( uri.getLastPathSegment() ).longValue() ); break; default: affected = 0; break; } return affected; } @Override public int bulkInsert( Uri uri, ContentValues[] valuesArray ) { int inserted = 0; int match = GPStrackingProvider.sURIMatcher.match( uri ); switch (match) { case WAYPOINTS: List<String> pathSegments = uri.getPathSegments(); int trackId = Integer.parseInt( pathSegments.get( 1 ) ); int segmentId = Integer.parseInt( pathSegments.get( 3 ) ); inserted = this.mDbHelper.bulkInsertWaypoint( trackId, segmentId, valuesArray ); break; default: inserted = super.bulkInsert( uri, valuesArray ); break; } return inserted; } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.adapter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OptionalDataException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Observable; import java.util.Set; import java.util.Vector; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.db.GPStracking.MetaData; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.Pair; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.SpinnerAdapter; /** * Model containing agregrated data retrieved from the GoBreadcrumbs.com API * * @version $Id:$ * @author rene (c) May 9, 2011, Sogeti B.V. */ public class BreadcrumbsTracks extends Observable { public static final String DESCRIPTION = "DESCRIPTION"; public static final String NAME = "NAME"; public static final String ENDTIME = "ENDTIME"; public static final String TRACK_ID = "BREADCRUMBS_TRACK_ID"; public static final String BUNDLE_ID = "BREADCRUMBS_BUNDLE_ID"; public static final String ACTIVITY_ID = "BREADCRUMBS_ACTIVITY_ID"; public static final String DIFFICULTY = "DIFFICULTY"; public static final String STARTTIME = "STARTTIME"; public static final String ISPUBLIC = "ISPUBLIC"; public static final String RATING = "RATING"; public static final String LATITUDE = "LATITUDE"; public static final String LONGITUDE = "LONGITUDE"; public static final String TOTALDISTANCE = "TOTALDISTANCE"; public static final String TOTALTIME = "TOTALTIME"; private static final String TAG = "OGT.BreadcrumbsTracks"; private static final Integer CACHE_VERSION = Integer.valueOf(8); private static final String BREADCRUMSB_BUNDLES_CACHE_FILE = "breadcrumbs_bundles_cache.data"; private static final String BREADCRUMSB_ACTIVITY_CACHE_FILE = "breadcrumbs_activity_cache.data"; /** * Time in milliseconds that a persisted breadcrumbs cache is used without a * refresh */ private static final long CACHE_TIMEOUT = 1000 * 60;//1000*60*10 ; /** * Mapping from bundleId to a list of trackIds */ private static HashMap<Integer, List<Integer>> sBundlesWithTracks; /** * Map from activityId to a dictionary containing keys like NAME */ private static HashMap<Integer, Map<String, String>> sActivityMappings; /** * Map from bundleId to a dictionary containing keys like NAME and * DESCRIPTION */ private static HashMap<Integer, Map<String, String>> sBundleMappings; /** * Map from trackId to a dictionary containing keys like NAME, ISPUBLIC, * DESCRIPTION and more */ private static HashMap<Integer, Map<String, String>> sTrackMappings; /** * Cache of OGT Tracks that have a Breadcrumbs track id stored in the * meta-data table */ private Map<Long, Integer> mSyncedTracks = null; private static Set<Pair<Integer, Integer>> sScheduledTracksLoading; static { BreadcrumbsTracks.initCacheVariables(); } private static void initCacheVariables() { sBundlesWithTracks = new HashMap<Integer, List<Integer>>(); sActivityMappings = new HashMap<Integer, Map<String, String>>(); sBundleMappings = new HashMap<Integer, Map<String, String>>(); sTrackMappings = new HashMap<Integer, Map<String, String>>(); sScheduledTracksLoading = new HashSet<Pair<Integer, Integer>>(); } private ContentResolver mResolver; /** * Constructor: create a new BreadcrumbsTracks. * * @param resolver Content resolver to obtain local Breadcrumbs references */ public BreadcrumbsTracks(ContentResolver resolver) { mResolver = resolver; } public void addActivity(int activityId, String activityName) { if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "addActivity(Integer " + activityId + " String " + activityName + ")"); } if (sActivityMappings.get(activityId) == null) { sActivityMappings.put(activityId, new HashMap<String, String>()); } sActivityMappings.get(activityId).put(NAME, activityName); setChanged(); notifyObservers(); } /** * Add bundle to the track list * * @param activityId * @param bundleId * @param bundleName * @param bundleDescription */ public void addBundle(int bundleId, String bundleName, String bundleDescription) { if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "addBundle(Integer " + bundleId + ", String " + bundleName + ", String " + bundleDescription + ")"); } if (sBundleMappings.get(bundleId) == null) { sBundleMappings.put(bundleId, new HashMap<String, String>()); } if (sBundlesWithTracks.get(bundleId) == null) { sBundlesWithTracks.put(bundleId, new ArrayList<Integer>()); } sBundleMappings.get(bundleId).put(NAME, bundleName); sBundleMappings.get(bundleId).put(DESCRIPTION, bundleDescription); setChanged(); notifyObservers(); } /** * Add track to tracklist * * @param trackId * @param trackName * @param bundleId * @param trackDescription * @param difficulty * @param startTime * @param endTime * @param isPublic * @param lat * @param lng * @param totalDistance * @param totalTime * @param trackRating */ public void addTrack(int trackId, String trackName, int bundleId, String trackDescription, String difficulty, String startTime, String endTime, String isPublic, Float lat, Float lng, Float totalDistance, Integer totalTime, String trackRating) { if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "addTrack(Integer " + trackId + ", String " + trackName + ", Integer " + bundleId + "..."); } if (sBundlesWithTracks.get(bundleId) == null) { sBundlesWithTracks.put(bundleId, new ArrayList<Integer>()); } if (!sBundlesWithTracks.get(bundleId).contains(trackId)) { sBundlesWithTracks.get(bundleId).add(trackId); sScheduledTracksLoading.remove(Pair.create(Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE, trackId)); } if (sTrackMappings.get(trackId) == null) { sTrackMappings.put(trackId, new HashMap<String, String>()); } putForTrack(trackId, NAME, trackName); putForTrack(trackId, ISPUBLIC, isPublic); putForTrack(trackId, STARTTIME, startTime); putForTrack(trackId, ENDTIME, endTime); putForTrack(trackId, DESCRIPTION, trackDescription); putForTrack(trackId, DIFFICULTY, difficulty); putForTrack(trackId, RATING, trackRating); putForTrack(trackId, LATITUDE, lat); putForTrack(trackId, LONGITUDE, lng); putForTrack(trackId, TOTALDISTANCE, totalDistance); putForTrack(trackId, TOTALTIME, totalTime); notifyObservers(); } public void addSyncedTrack(Long trackId, int bcTrackId) { if (mSyncedTracks == null) { isLocalTrackOnline(-1l); } mSyncedTracks.put(trackId, bcTrackId); setChanged(); notifyObservers(); } public void addTracksLoadingScheduled(Pair<Integer, Integer> item) { sScheduledTracksLoading.add(item); setChanged(); notifyObservers(); } /** * Cleans old bundles based a set of all bundles * * @param newBundleIds */ public void setAllBundleIds(Set<Integer> currentBundleIds) { Set<Integer> keySet = sBundlesWithTracks.keySet(); for (Integer oldBundleId : keySet) { if (!currentBundleIds.contains(oldBundleId)) { removeBundle(oldBundleId); } } } public void setAllTracksForBundleId(int mBundleId, Set<Integer> updatedbcTracksIdList) { List<Integer> trackIdList = sBundlesWithTracks.get(mBundleId); for (int location = 0; location < trackIdList.size(); location++) { Integer oldTrackId = trackIdList.get(location); if (!updatedbcTracksIdList.contains(oldTrackId)) { removeTrack(mBundleId, oldTrackId); } } setChanged(); notifyObservers(); } private void putForTrack(int trackId, String key, Object value) { if (value != null) { sTrackMappings.get(trackId).put(key, value.toString()); } setChanged(); notifyObservers(); } /** * Remove a bundle * * @param deletedId */ public void removeBundle(int deletedId) { sBundleMappings.remove(deletedId); sBundlesWithTracks.remove(deletedId); setChanged(); notifyObservers(); } /** * Remove a track * * @param deletedId */ public void removeTrack(int bundleId, int trackId) { sTrackMappings.remove(trackId); if (sBundlesWithTracks.get(bundleId) != null) { sBundlesWithTracks.get(bundleId).remove(trackId); } setChanged(); notifyObservers(); mResolver.delete(MetaData.CONTENT_URI, MetaData.TRACK + " = ? AND " + MetaData.KEY + " = ? ", new String[] { Integer.toString(trackId), TRACK_ID }); if (mSyncedTracks != null && mSyncedTracks.containsKey(trackId)) { mSyncedTracks.remove(trackId); } } public int positions() { int size = 0; for (int index = 0; index < sBundlesWithTracks.size(); index++) { // One row for the Bundle header size += 1; List<Integer> trackIds = sBundlesWithTracks.get(index); int bundleSize = trackIds != null ? trackIds.size() : 0; // One row per track in each bundle size += bundleSize; } return size; } public Integer getBundleIdForTrackId(int trackId) { for (Integer bundleId : sBundlesWithTracks.keySet()) { List<Integer> trackIds = sBundlesWithTracks.get(bundleId); if (trackIds.contains(trackId)) { return bundleId; } } return null; } /** * @param position list postition 0...n * @return a pair of a TYPE and an ID */ public Pair<Integer, Integer> getItemForPosition(int position) { int countdown = position; for (Integer bundleId : sBundlesWithTracks.keySet()) { if (countdown == 0) { return Pair.create(Constants.BREADCRUMBS_BUNDLE_ITEM_VIEW_TYPE, bundleId); } countdown--; int bundleSize = sBundlesWithTracks.get(bundleId) != null ? sBundlesWithTracks.get(bundleId).size() : 0; if (countdown < bundleSize) { Integer trackId = sBundlesWithTracks.get(bundleId).get(countdown); return Pair.create(Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE, trackId); } countdown -= bundleSize; } return null; } public String getValueForItem(Pair<Integer, Integer> item, String key) { String value = null; switch (item.first) { case Constants.BREADCRUMBS_BUNDLE_ITEM_VIEW_TYPE: value = sBundleMappings.get(item.second).get(key); break; case Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE: value = sTrackMappings.get(item.second).get(key); break; default: value = null; break; } return value; } public SpinnerAdapter getActivityAdapter(Context ctx) { List<String> activities = new Vector<String>(); for (Integer activityId : sActivityMappings.keySet()) { String name = sActivityMappings.get(activityId).get(NAME); name = name != null ? name : ""; activities.add(name); } Collections.sort(activities); ArrayAdapter<String> adapter = new ArrayAdapter<String>(ctx, android.R.layout.simple_spinner_item, activities); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); return adapter; } public SpinnerAdapter getBundleAdapter(Context ctx) { List<String> bundles = new Vector<String>(); for (Integer bundleId : sBundlesWithTracks.keySet()) { bundles.add(sBundleMappings.get(bundleId).get(NAME)); } Collections.sort(bundles); if (!bundles.contains(ctx.getString(R.string.app_name))) { bundles.add(ctx.getString(R.string.app_name)); } ArrayAdapter<String> adapter = new ArrayAdapter<String>(ctx, android.R.layout.simple_spinner_item, bundles); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); return adapter; } public static int getIdForActivity(String selectedItem) { if (selectedItem == null) { return -1; } for (Integer activityId : sActivityMappings.keySet()) { Map<String, String> mapping = sActivityMappings.get(activityId); if (mapping != null && selectedItem.equals(mapping.get(NAME))) { return activityId; } } return -1; } public static int getIdForBundle(int activityId, String selectedItem) { for (Integer bundleId : sBundlesWithTracks.keySet()) { if (selectedItem.equals(sBundleMappings.get(bundleId).get(NAME))) { return bundleId; } } return -1; } private boolean isLocalTrackOnline(Long qtrackId) { if (mSyncedTracks == null) { mSyncedTracks = new HashMap<Long, Integer>(); Cursor cursor = null; try { cursor = mResolver.query(MetaData.CONTENT_URI, new String[] { MetaData.TRACK, MetaData.VALUE }, MetaData.KEY + " = ? ", new String[] { TRACK_ID }, null); if (cursor.moveToFirst()) { do { Long trackId = cursor.getLong(0); try { Integer bcTrackId = Integer.valueOf(cursor.getString(1)); mSyncedTracks.put(trackId, bcTrackId); } catch (NumberFormatException e) { Log.w(TAG, "Illigal value stored as track id", e); } } while (cursor.moveToNext()); } } finally { if (cursor != null) { cursor.close(); } } setChanged(); notifyObservers(); } boolean synced = mSyncedTracks.containsKey(qtrackId); return synced; } public boolean isLocalTrackSynced(Long qtrackId) { boolean uploaded = isLocalTrackOnline(qtrackId); Integer trackId = mSyncedTracks.get(qtrackId); boolean synced = trackId != null && sTrackMappings.get(trackId) != null; return uploaded && synced; } public boolean areTracksLoaded(Pair<Integer, Integer> item) { return sBundlesWithTracks.get(item.second) != null && item.first == Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE; } public boolean areTracksLoadingScheduled(Pair<Integer, Integer> item) { return sScheduledTracksLoading.contains(item); } /** * Read the static breadcrumbs data from private file * * @param ctx * @return is refresh is needed */ @SuppressWarnings("unchecked") public boolean readCache(Context ctx) { FileInputStream fis = null; ObjectInputStream ois = null; Date bundlesPersisted = null, activitiesPersisted = null; Object[] cache; synchronized (BREADCRUMSB_BUNDLES_CACHE_FILE) { try { fis = ctx.openFileInput(BREADCRUMSB_BUNDLES_CACHE_FILE); ois = new ObjectInputStream(fis); cache = (Object[]) ois.readObject(); // new Object[] { CACHE_VERSION, new Date(), sActivitiesWithBundles, sBundlesWithTracks, sBundleMappings, sTrackMappings }; if (cache[0] instanceof Integer && CACHE_VERSION.equals(cache[0])) { bundlesPersisted = (Date) cache[1]; HashMap<Integer, List<Integer>> bundles = (HashMap<Integer, List<Integer>>) cache[2]; HashMap<Integer, Map<String, String>> bundlemappings = (HashMap<Integer, Map<String, String>>) cache[3]; HashMap<Integer, Map<String, String>> trackmappings = (HashMap<Integer, Map<String, String>>) cache[4]; sBundlesWithTracks = bundles != null ? bundles : sBundlesWithTracks; sBundleMappings = bundlemappings != null ? bundlemappings : sBundleMappings; sTrackMappings = trackmappings != null ? trackmappings : sTrackMappings; } else { clearPersistentCache(ctx); } fis = ctx.openFileInput(BREADCRUMSB_ACTIVITY_CACHE_FILE); ois = new ObjectInputStream(fis); cache = (Object[]) ois.readObject(); // new Object[] { CACHE_VERSION, new Date(), sActivityMappings }; if (cache[0] instanceof Integer && CACHE_VERSION.equals(cache[0])) { activitiesPersisted = (Date) cache[1]; HashMap<Integer, Map<String, String>> activitymappings = (HashMap<Integer, Map<String, String>>) cache[2]; sActivityMappings = activitymappings != null ? activitymappings : sActivityMappings; } else { clearPersistentCache(ctx); } } catch (OptionalDataException e) { clearPersistentCache(ctx); Log.w(TAG, "Unable to read persisted breadcrumbs cache", e); } catch (ClassNotFoundException e) { clearPersistentCache(ctx); Log.w(TAG, "Unable to read persisted breadcrumbs cache", e); } catch (IOException e) { clearPersistentCache(ctx); Log.w(TAG, "Unable to read persisted breadcrumbs cache", e); } catch (ClassCastException e) { clearPersistentCache(ctx); Log.w(TAG, "Unable to read persisted breadcrumbs cache", e); } catch (ArrayIndexOutOfBoundsException e) { clearPersistentCache(ctx); Log.w(TAG, "Unable to read persisted breadcrumbs cache", e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { Log.w(TAG, "Error closing file stream after reading cache", e); } } if (ois != null) { try { ois.close(); } catch (IOException e) { Log.w(TAG, "Error closing object stream after reading cache", e); } } } } setChanged(); notifyObservers(); boolean refreshNeeded = false; refreshNeeded = refreshNeeded || bundlesPersisted == null || activitiesPersisted == null; refreshNeeded = refreshNeeded || (activitiesPersisted.getTime() < new Date().getTime() - CACHE_TIMEOUT * 10); refreshNeeded = refreshNeeded || (bundlesPersisted.getTime() < new Date().getTime() - CACHE_TIMEOUT); return refreshNeeded; } public void persistCache(Context ctx) { FileOutputStream fos = null; ObjectOutputStream oos = null; Object[] cache; synchronized (BREADCRUMSB_BUNDLES_CACHE_FILE) { try { fos = ctx.openFileOutput(BREADCRUMSB_BUNDLES_CACHE_FILE, Context.MODE_PRIVATE); oos = new ObjectOutputStream(fos); cache = new Object[] { CACHE_VERSION, new Date(), sBundlesWithTracks, sBundleMappings, sTrackMappings }; oos.writeObject(cache); fos = ctx.openFileOutput(BREADCRUMSB_ACTIVITY_CACHE_FILE, Context.MODE_PRIVATE); oos = new ObjectOutputStream(fos); cache = new Object[] { CACHE_VERSION, new Date(), sActivityMappings }; oos.writeObject(cache); } catch (FileNotFoundException e) { Log.e(TAG, "Error in file stream during persist cache", e); } catch (IOException e) { Log.e(TAG, "Error in object stream during persist cache", e); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { Log.w(TAG, "Error closing file stream after writing cache", e); } } if (oos != null) { try { oos.close(); } catch (IOException e) { Log.w(TAG, "Error closing object stream after writing cache", e); } } } } } public void clearAllCache(Context ctx) { BreadcrumbsTracks.initCacheVariables(); setChanged(); clearPersistentCache(ctx); notifyObservers(); } public void clearPersistentCache(Context ctx) { Log.w(TAG, "Deleting old Breadcrumbs cache files"); synchronized (BREADCRUMSB_BUNDLES_CACHE_FILE) { ctx.deleteFile(BREADCRUMSB_ACTIVITY_CACHE_FILE); ctx.deleteFile(BREADCRUMSB_BUNDLES_CACHE_FILE); } } @Override public String toString() { return "BreadcrumbsTracks [mActivityMappings=" + sActivityMappings + ", mBundleMappings=" + sBundleMappings + ", mTrackMappings=" + sTrackMappings + ", mActivities=" + sActivityMappings + ", mBundles=" + sBundlesWithTracks + "]"; } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.adapter; import java.util.LinkedList; import java.util.List; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.tasks.GpxParser; import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsService; import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsTracks; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.Pair; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; /** * Organizes Breadcrumbs tasks based on demands on the BaseAdapter functions * * @version $Id:$ * @author rene (c) Apr 24, 2011, Sogeti B.V. */ public class BreadcrumbsAdapter extends BaseAdapter { private static final String TAG = "OGT.BreadcrumbsAdapter"; public static final boolean DEBUG = false; private Activity mContext; private LayoutInflater mInflater; private BreadcrumbsService mService; private List<Pair<Integer, Integer>> breadcrumbItems = new LinkedList<Pair<Integer, Integer>>(); public BreadcrumbsAdapter(Activity ctx, BreadcrumbsService service) { super(); mContext = ctx; mService = service; mInflater = LayoutInflater.from(mContext); } public void setService(BreadcrumbsService service) { mService = service; updateItemList(); } /** * Reloads the current list of known breadcrumb listview items * */ public void updateItemList() { mContext.runOnUiThread(new Runnable() { @Override public void run() { if (mService != null) { breadcrumbItems = mService.getAllItems(); notifyDataSetChanged(); } } }); } /** * @see android.widget.Adapter#getCount() */ @Override public int getCount() { if (mService != null) { if (mService.isAuthorized()) { return breadcrumbItems.size(); } else { return 1; } } else { return 0; } } /** * @see android.widget.Adapter#getItem(int) */ @Override public Object getItem(int position) { if (mService.isAuthorized()) { return breadcrumbItems.get(position); } else { return Constants.BREADCRUMBS_CONNECT; } } /** * @see android.widget.Adapter#getItemId(int) */ @Override public long getItemId(int position) { return position; } /** * @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { View view = null; if (mService.isAuthorized()) { int type = getItemViewType(position); if (convertView == null) { switch (type) { case Constants.BREADCRUMBS_BUNDLE_ITEM_VIEW_TYPE: view = mInflater.inflate(R.layout.breadcrumbs_bundle, null); break; case Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE: view = mInflater.inflate(R.layout.breadcrumbs_track, null); break; default: view = new TextView(null); break; } } else { view = convertView; } Pair<Integer, Integer> item = breadcrumbItems.get(position); mService.willDisplayItem(item); String name; switch (type) { case Constants.BREADCRUMBS_BUNDLE_ITEM_VIEW_TYPE: name = mService.getValueForItem((Pair<Integer, Integer>) item, BreadcrumbsTracks.NAME); ((TextView) view.findViewById(R.id.listitem_name)).setText(name); break; case Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE: TextView nameView = (TextView) view.findViewById(R.id.listitem_name); TextView dateView = (TextView) view.findViewById(R.id.listitem_from); nameView.setText(mService.getValueForItem(item, BreadcrumbsTracks.NAME)); String dateString = mService.getValueForItem(item, BreadcrumbsTracks.ENDTIME); if (dateString != null) { Long date = GpxParser.parseXmlDateTime(dateString); dateView.setText(date.toString()); } break; default: view = new TextView(null); break; } } else { if (convertView == null) { view = mInflater.inflate(R.layout.breadcrumbs_connect, null); } else { view = convertView; } ((TextView) view).setText(R.string.breadcrumbs_connect); } return view; } @Override public int getViewTypeCount() { int types = 4; return types; } @Override public int getItemViewType(int position) { if (mService.isAuthorized()) { Pair<Integer, Integer> item = breadcrumbItems.get(position); return item.first; } else { return Constants.BREADCRUMBS_CONNECT_ITEM_VIEW_TYPE; } } @Override public boolean areAllItemsEnabled() { return false; }; @Override public boolean isEnabled(int position) { int itemViewType = getItemViewType(position); return itemViewType == Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE || itemViewType == Constants.BREADCRUMBS_CONNECT_ITEM_VIEW_TYPE; } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.adapter; import java.util.LinkedHashMap; import java.util.Map; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.util.Constants; import android.content.Context; import android.database.DataSetObserver; import android.view.View; import android.view.ViewGroup; import android.widget.Adapter; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.ListAdapter; /** * Combines multiple Adapters into a sectioned ListAdapter * * @version $Id:$ * @author rene (c) Apr 24, 2011, Sogeti B.V. */ public class SectionedListAdapter extends BaseAdapter { @SuppressWarnings("unused") private static final String TAG = "OGT.SectionedListAdapter"; private Map<String, BaseAdapter> mSections; private ArrayAdapter<String> mHeaders; public SectionedListAdapter(Context ctx) { mHeaders = new ArrayAdapter<String>(ctx, R.layout.section_header); mSections = new LinkedHashMap<String, BaseAdapter>(); } public void addSection(String name, BaseAdapter adapter) { mHeaders.add(name); mSections.put(name, adapter); } @Override public void registerDataSetObserver(DataSetObserver observer) { super.registerDataSetObserver(observer); for( Adapter adapter : mSections.values() ) { adapter.registerDataSetObserver(observer); } } @Override public void unregisterDataSetObserver(DataSetObserver observer) { super.unregisterDataSetObserver(observer); for( Adapter adapter : mSections.values() ) { adapter.unregisterDataSetObserver(observer); } } /* * (non-Javadoc) * @see android.widget.Adapter#getCount() */ @Override public int getCount() { int count = 0; for (Adapter adapter : mSections.values()) { count += adapter.getCount() + 1; } return count; } /* * (non-Javadoc) * @see android.widget.Adapter#getItem(int) */ @Override public Object getItem(int position) { int countDown = position; Adapter adapter; for (String section : mSections.keySet()) { adapter = mSections.get(section); if (countDown == 0) { return section; } countDown--; if (countDown < adapter.getCount()) { return adapter.getItem(countDown); } countDown -= adapter.getCount(); } return null; } /* * (non-Javadoc) * @see android.widget.Adapter#getItemId(int) */ @Override public long getItemId(int position) { int countDown = position; Adapter adapter; for (String section : mSections.keySet()) { adapter = mSections.get(section); if (countDown == 0) { return position; } countDown--; if (countDown < adapter.getCount()) { long id = adapter.getItemId(countDown); return id; } countDown -= adapter.getCount(); } return -1; } /* * (non-Javadoc) * @see android.widget.Adapter#getView(int, android.view.View, * android.view.ViewGroup) */ @Override public View getView(final int position, View convertView, ViewGroup parent) { int sectionNumber = 0; int countDown = position; for (String section : mSections.keySet()) { Adapter adapter = mSections.get(section); int size = adapter.getCount() + 1; // check if position inside this section if (countDown == 0) { return mHeaders.getView(sectionNumber, convertView, parent); } if (countDown < size) { return adapter.getView(countDown - 1, convertView, parent); } // otherwise jump into next section countDown -= size; sectionNumber++; } return null; } @Override public int getViewTypeCount() { int types = 1; for (Adapter section : mSections.values()) { types += section.getViewTypeCount(); } return types; } @Override public int getItemViewType(int position) { int type = 1; Adapter adapter; int countDown = position; for (String section : mSections.keySet()) { adapter = mSections.get(section); int size = adapter.getCount() + 1; if (countDown == 0) { return Constants.SECTIONED_HEADER_ITEM_VIEW_TYPE; } else if (countDown < size) { return type + adapter.getItemViewType(countDown - 1); } countDown -= size; type += adapter.getViewTypeCount(); } return ListAdapter.IGNORE_ITEM_VIEW_TYPE; } @Override public boolean areAllItemsEnabled() { return false; }; @Override public boolean isEnabled(int position) { if( getItemViewType(position) == Constants.SECTIONED_HEADER_ITEM_VIEW_TYPE ) { return false; } else { int countDown = position; for (String section : mSections.keySet()) { BaseAdapter adapter = mSections.get(section); countDown--; int size = adapter.getCount() ; if (countDown < size) { return adapter.isEnabled(countDown); } // otherwise jump into next section countDown -= size; } } return false ; } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.util; import java.text.DateFormat; import java.util.Date; import android.content.Context; import android.util.AttributeSet; import android.widget.TextView; /** * An implementation for the XML element DateView that alters the textview in the * formating of the text when displaying a date in ms from 1970. * * @version $Id$ * @author rene (c) Jan 22, 2009, Sogeti B.V. */ public class DateView extends TextView { private Date mDate; /** * Constructor: create a new DateView. * @param context */ public DateView(Context context) { super( context ); } /** * Constructor: create a new DateView. * @param context * @param attrs */ public DateView(Context context, AttributeSet attrs) { super( context, attrs ); } /** * Constructor: create a new DateView. * @param context * @param attrs * @param defStyle */ public DateView(Context context, AttributeSet attrs, int defStyle) { super( context, attrs, defStyle ); } /* * (non-Javadoc) * @see android.widget.TextView#setText(java.lang.CharSequence, android.widget.TextView.BufferType) */ @Override public void setText( CharSequence charSeq, BufferType type ) { // Behavior for the graphical editor if( this.isInEditMode() ) { super.setText( charSeq, type ); return; } long longVal; if( charSeq.length() == 0 ) { longVal = 0l ; } else { try { longVal = Long.parseLong(charSeq.toString()) ; } catch(NumberFormatException e) { longVal = 0l; } } this.mDate = new Date( longVal ); DateFormat dateFormat = android.text.format.DateFormat.getLongDateFormat(this.getContext().getApplicationContext()); DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(this.getContext().getApplicationContext()); String text = timeFormat.format(this.mDate) + " " + dateFormat.format(mDate); super.setText( text, type ); } }
Java
/* Copyright (c) 2008 Google Inc. * * 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 nl.sogeti.android.gpstracker.util; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PushbackInputStream; import java.io.Reader; public class UnicodeReader extends Reader { private static final int BOM_SIZE = 4; private final InputStreamReader reader; /** * Construct UnicodeReader * * @param in Input stream. * @param defaultEncoding Default encoding to be used if BOM is not found, or <code>null</code> to use system default encoding. * @throws IOException If an I/O error occurs. */ public UnicodeReader(InputStream in, String defaultEncoding) throws IOException { byte bom[] = new byte[BOM_SIZE]; String encoding; int unread; PushbackInputStream pushbackStream = new PushbackInputStream( in, BOM_SIZE ); int n = pushbackStream.read( bom, 0, bom.length ); // Read ahead four bytes and check for BOM marks. if( ( bom[0] == (byte) 0xEF ) && ( bom[1] == (byte) 0xBB ) && ( bom[2] == (byte) 0xBF ) ) { encoding = "UTF-8"; unread = n - 3; } else if( ( bom[0] == (byte) 0xFE ) && ( bom[1] == (byte) 0xFF ) ) { encoding = "UTF-16BE"; unread = n - 2; } else if( ( bom[0] == (byte) 0xFF ) && ( bom[1] == (byte) 0xFE ) ) { encoding = "UTF-16LE"; unread = n - 2; } else if( ( bom[0] == (byte) 0x00 ) && ( bom[1] == (byte) 0x00 ) && ( bom[2] == (byte) 0xFE ) && ( bom[3] == (byte) 0xFF ) ) { encoding = "UTF-32BE"; unread = n - 4; } else if( ( bom[0] == (byte) 0xFF ) && ( bom[1] == (byte) 0xFE ) && ( bom[2] == (byte) 0x00 ) && ( bom[3] == (byte) 0x00 ) ) { encoding = "UTF-32LE"; unread = n - 4; } else { encoding = defaultEncoding; unread = n; } // Unread bytes if necessary and skip BOM marks. if( unread > 0 ) { pushbackStream.unread( bom, ( n - unread ), unread ); } else if( unread < -1 ) { pushbackStream.unread( bom, 0, 0 ); } // Use given encoding. if( encoding == null ) { reader = new InputStreamReader( pushbackStream ); } else { reader = new InputStreamReader( pushbackStream, encoding ); } } public String getEncoding() { return reader.getEncoding(); } @Override public int read( char[] cbuf, int off, int len ) throws IOException { return reader.read( cbuf, off, len ); } @Override public void close() throws IOException { reader.close(); } }
Java
/* * Written by Tom van Braeckel @ http://code.google.com/u/tomvanbraeckel/ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.util; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.preference.PreferenceManager; import android.util.Log; public class BootReceiver extends BroadcastReceiver { private final static String TAG = "OGT.BootReceiver"; @Override public void onReceive( Context context, Intent intent ) { // Log.d( TAG, "BootReceiver.onReceive(), probably ACTION_BOOT_COMPLETED" ); String action = intent.getAction(); // start on BOOT_COMPLETED if( action.equals( Intent.ACTION_BOOT_COMPLETED ) ) { // Log.d( TAG, "BootReceiver received ACTION_BOOT_COMPLETED" ); // check in the settings if we need to auto start boolean startImmidiatly = PreferenceManager.getDefaultSharedPreferences( context ).getBoolean( Constants.STARTUPATBOOT, false ); if( startImmidiatly ) { // Log.d( TAG, "Starting LoggerMap activity..." ); context.startService( new Intent( Constants.SERVICENAME ) ); } else { Log.i( TAG, "Not starting Logger Service. Adjust the settings if you wanted this !" ); } } else { // this shouldn't happen ! Log.w( TAG, "OpenGPSTracker's BootReceiver received " + action + ", but it's only able to respond to " + Intent.ACTION_BOOT_COMPLETED + ". This shouldn't happen !" ); } } }
Java
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Mar 10, 2012 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ */ package nl.sogeti.android.gpstracker.util; import nl.sogeti.android.gpstracker.R; import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.Log; import android.view.View; /** * ???? * * @version $Id:$ * @author rene (c) Mar 10, 2012, Sogeti B.V. */ public class SlidingIndicatorView extends View { private static final String TAG = "OGT.SlidingIndicatorView"; private float mMinimum = 0; private float mMaximum = 100 ; private float mValue = 0; private Drawable mIndicator; private int mIntrinsicHeight; public SlidingIndicatorView(Context context) { super(context); } public SlidingIndicatorView(Context context, AttributeSet attrs) { super(context, attrs); } public SlidingIndicatorView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if( mIndicator == null ) { mIndicator = getResources().getDrawable(R.drawable.stip); mIntrinsicHeight = mIndicator.getIntrinsicHeight(); mIndicator.setBounds(0, 0, getWidth(), mIntrinsicHeight); } int height = getHeight(); float scale = Math.abs( mValue/(mMaximum-mMinimum) ); float y = height - height*scale; float translate = y-mIntrinsicHeight; canvas.save(); canvas.translate(0, translate); mIndicator.draw(canvas); canvas.restore(); } public float getMin() { return mMinimum; } public void setMin(float min) { if(mMaximum-mMinimum == 0 ) { Log.w(TAG, "Minimum and maximum difference must be greater then 0"); return; } this.mMinimum = min; } public float getMax() { return mMaximum; } public void setMax(float max) { if(mMaximum-mMinimum == 0 ) { Log.w(TAG, "Minimum and maximum difference must be greater then 0"); return; } this.mMaximum = max; } public float getValue() { return mValue; } public void setValue(float value) { this.mValue = value; } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.util; import nl.sogeti.android.gpstracker.logger.GPSLoggerService; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; public class DockReceiver extends BroadcastReceiver { private final static String TAG = "OGT.DockReceiver"; @Override public void onReceive( Context context, Intent intent ) { String action = intent.getAction(); if( action.equals( Intent.ACTION_DOCK_EVENT ) ) { Bundle extras = intent.getExtras(); boolean start = false; boolean stop = false; if( extras != null && extras.containsKey(Intent.EXTRA_DOCK_STATE ) ) { int dockstate = extras.getInt(Intent.EXTRA_DOCK_STATE, -1); if( dockstate == Intent.EXTRA_DOCK_STATE_CAR ) { start = PreferenceManager.getDefaultSharedPreferences( context ).getBoolean( Constants.LOGATDOCK, false ); } else if( dockstate == Intent.EXTRA_DOCK_STATE_UNDOCKED ) { stop = PreferenceManager.getDefaultSharedPreferences( context ).getBoolean( Constants.STOPATUNDOCK, false ); } } if( start ) { Intent serviceIntent = new Intent( Constants.SERVICENAME ); serviceIntent.putExtra(GPSLoggerService.COMMAND, GPSLoggerService.EXTRA_COMMAND_START); context.startService( serviceIntent ); } else if( stop ) { Intent serviceIntent = new Intent( Constants.SERVICENAME ); serviceIntent.putExtra(GPSLoggerService.COMMAND, GPSLoggerService.EXTRA_COMMAND_STOP); context.startService( serviceIntent ); } } else { Log.w( TAG, "OpenGPSTracker's BootReceiver received " + action + ", but it's only able to respond to " + Intent.ACTION_BOOT_COMPLETED + ". This shouldn't happen !" ); } } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.util; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import nl.sogeti.android.gpstracker.actions.tasks.GpxParser; import nl.sogeti.android.gpstracker.actions.tasks.GpxParser.ProgressAdmin; /** * ???? * * @version $Id$ * @author rene (c) Dec 11, 2010, Sogeti B.V. */ public class ProgressFilterInputStream extends FilterInputStream { GpxParser mAsyncTask; long progress = 0; private ProgressAdmin mProgressAdmin; public ProgressFilterInputStream(InputStream is, ProgressAdmin progressAdmin) { super( is ); mProgressAdmin = progressAdmin; } @Override public int read() throws IOException { int read = super.read(); incrementProgressBy( 1 ); return read; } @Override public int read( byte[] buffer, int offset, int count ) throws IOException { int read = super.read( buffer, offset, count ); incrementProgressBy( read ); return read; } private void incrementProgressBy( int bytes ) { if( bytes > 0 ) { mProgressAdmin.addBytesProgress(bytes); } } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.util; import java.util.Locale; import nl.sogeti.android.gpstracker.R; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.res.Configuration; import android.content.res.Resources; import android.preference.PreferenceManager; import android.util.TypedValue; /** * Collection of methods to provide metric and imperial data based on locale or * overridden by configuration * * @version $Id$ * @author rene (c) Feb 2, 2010, Sogeti B.V. */ public class UnitsI18n { private Context mContext; private double mConversion_from_mps_to_speed; private double mConversion_from_meter_to_distance; private double mConversion_from_meter_to_height; private String mSpeed_unit; private String mDistance_unit; private String mHeight_unit; private UnitsChangeListener mListener; private OnSharedPreferenceChangeListener mPreferenceListener = new OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(Constants.UNITS)) { initBasedOnPreferences(sharedPreferences); if (mListener != null) { mListener.onUnitsChange(); } } } }; private boolean needsUnitFlip; private int mUnits; @SuppressWarnings("unused") private static final String TAG = "OGT.UnitsI18n"; public UnitsI18n(Context ctx, UnitsChangeListener listener) { this(ctx); mListener = listener; } public UnitsI18n(Context ctx) { mContext = ctx; initBasedOnPreferences(PreferenceManager.getDefaultSharedPreferences(mContext)); } private void initBasedOnPreferences(SharedPreferences sharedPreferences) { mUnits = Integer.parseInt(sharedPreferences.getString(Constants.UNITS, Integer.toString(Constants.UNITS_DEFAULT))); switch (mUnits) { case (Constants.UNITS_DEFAULT): setToDefault(); break; case (Constants.UNITS_IMPERIAL): setToImperial(); break; case (Constants.UNITS_METRIC): setToMetric(); break; case (Constants.UNITS_NAUTIC): setToMetric(); overrideWithNautic(mContext.getResources()); break; case (Constants.UNITS_METRICPACE): setToMetric(); overrideWithPace(mContext.getResources()); break; case (Constants.UNITS_IMPERIALPACE): setToImperial(); overrideWithPaceImperial(mContext.getResources()); break; case Constants.UNITS_IMPERIALSURFACE: setToImperial(); overrideWithSurfaceImperial(); break; case Constants.UNITS_METRICSURFACE: setToMetric(); overrideWithSurfaceMetric(); break; default: setToDefault(); break; } } private void setToDefault() { Resources resources = mContext.getResources(); init(resources); } private void setToMetric() { Resources resources = mContext.getResources(); Configuration config = resources.getConfiguration(); Locale oldLocale = config.locale; config.locale = new Locale(""); resources.updateConfiguration(config, resources.getDisplayMetrics()); init(resources); config.locale = oldLocale; resources.updateConfiguration(config, resources.getDisplayMetrics()); } private void setToImperial() { Resources resources = mContext.getResources(); Configuration config = resources.getConfiguration(); Locale oldLocale = config.locale; config.locale = Locale.US; resources.updateConfiguration(config, resources.getDisplayMetrics()); init(resources); config.locale = oldLocale; resources.updateConfiguration(config, resources.getDisplayMetrics()); } /** * Based on a given Locale prefetch the units conversions and names. * * @param resources Resources initialized with a Locale */ private void init(Resources resources) { TypedValue outValue = new TypedValue(); needsUnitFlip = false; resources.getValue(R.raw.conversion_from_mps, outValue, false); mConversion_from_mps_to_speed = outValue.getFloat(); resources.getValue(R.raw.conversion_from_meter, outValue, false); mConversion_from_meter_to_distance = outValue.getFloat(); resources.getValue(R.raw.conversion_from_meter_to_height, outValue, false); mConversion_from_meter_to_height = outValue.getFloat(); mSpeed_unit = resources.getString(R.string.speed_unitname); mDistance_unit = resources.getString(R.string.distance_unitname); mHeight_unit = resources.getString(R.string.distance_smallunitname); } private void overrideWithNautic(Resources resources) { TypedValue outValue = new TypedValue(); resources.getValue(R.raw.conversion_from_mps_to_knot, outValue, false); mConversion_from_mps_to_speed = outValue.getFloat(); resources.getValue(R.raw.conversion_from_meter_to_nauticmile, outValue, false); mConversion_from_meter_to_distance = outValue.getFloat(); mSpeed_unit = resources.getString(R.string.knot_unitname); mDistance_unit = resources.getString(R.string.nautic_unitname); } private void overrideWithPace(Resources resources) { needsUnitFlip = true; mSpeed_unit = resources.getString(R.string.pace_unitname); } private void overrideWithPaceImperial(Resources resources) { needsUnitFlip = true; mSpeed_unit = resources.getString(R.string.pace_unitname_imperial); } private void overrideWithSurfaceImperial() { float width = getWidthPreference(); Resources resources = mContext.getResources(); TypedValue outValue = new TypedValue(); resources.getValue(R.raw.conversion_from_mps_to_acres_hour, outValue, false); mConversion_from_mps_to_speed = outValue.getFloat() * width; mSpeed_unit = resources.getString(R.string.surface_unitname_imperial); } private float getWidthPreference() { return Float.parseFloat(PreferenceManager.getDefaultSharedPreferences(mContext).getString("units_implement_width", "12")); } private void overrideWithSurfaceMetric() { float width = getWidthPreference(); Resources resources = mContext.getResources(); TypedValue outValue = new TypedValue(); resources.getValue(R.raw.conversion_from_mps_to_hectare_hour, outValue, false); mConversion_from_mps_to_speed = outValue.getFloat() * width; mSpeed_unit = resources.getString(R.string.surface_unitname_metric); } public double conversionFromMeterAndMiliseconds(double meters, long miliseconds) { float seconds = miliseconds / 1000f; return conversionFromMetersPerSecond(meters / seconds); } public double conversionFromMetersPerSecond(double mps) { double speed = mps * mConversion_from_mps_to_speed; if (needsUnitFlip) // Flip from "x per hour" to "minutes per x" { if (speed > 1) // Nearly no speed return 0 as if there is no speed { speed = (1 / speed) * 60.0; } else { speed = 0; } } return speed; } public double conversionFromMeter(double meters) { double value = meters * mConversion_from_meter_to_distance; return value; } public double conversionFromLocalToMeters(double localizedValue) { double meters = localizedValue / mConversion_from_meter_to_distance; return meters; } public double conversionFromMeterToHeight(double meters) { return meters * mConversion_from_meter_to_height; } public String getSpeedUnit() { return mSpeed_unit; } public String getDistanceUnit() { return mDistance_unit; } public String getHeightUnit() { return mHeight_unit; } public boolean isUnitFlipped() { return needsUnitFlip; } public void setUnitsChangeListener(UnitsChangeListener unitsChangeListener) { mListener = unitsChangeListener; if( mListener != null ) { initBasedOnPreferences(PreferenceManager.getDefaultSharedPreferences(mContext)); PreferenceManager.getDefaultSharedPreferences(mContext).registerOnSharedPreferenceChangeListener(mPreferenceListener); } else { PreferenceManager.getDefaultSharedPreferences(mContext).unregisterOnSharedPreferenceChangeListener(mPreferenceListener); } } /** * Interface definition for a callback to be invoked when the preference for * units changed. * * @version $Id$ * @author rene (c) Feb 14, 2010, Sogeti B.V. */ public interface UnitsChangeListener { /** * Called when the unit data has changed. */ void onUnitsChange(); } /** * Format a speed using the current unit and flipping * * @param speed * @param decimals format a bit larger showing decimals or seconds * @return */ public String formatSpeed(double speed, boolean decimals) { String speedText; if(mUnits == Constants.UNITS_METRICPACE || mUnits == Constants.UNITS_IMPERIALPACE) { if( decimals ) { speedText = String.format( "%02d %s", (int)speed, this.getSpeedUnit() ); } else { speedText = String.format( "%02d:%02d %s", (int)speed, (int)((speed-(int)speed)*60), // convert decimal to seconds this.getSpeedUnit() ); } } else { if( decimals ) { speedText = String.format( "%.2f %s", speed, this.getSpeedUnit() ); } else { speedText = String.format( "%.0f %s", speed, this.getSpeedUnit() ); } } return speedText; } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.util; import java.io.File; import nl.sogeti.android.gpstracker.db.GPStracking; import android.content.Context; import android.net.Uri; import android.os.Environment; import android.preference.PreferenceManager; /** * Various application wide constants * * @version $Id$ * @author rene (c) Mar 22, 2009, Sogeti B.V. */ public class Constants { public static final String DISABLEBLANKING = "disableblanking"; public static final String DISABLEDIMMING = "disabledimming"; public static final String SATELLITE = "SATELLITE"; public static final String TRAFFIC = "TRAFFIC"; public static final String SPEED = "showspeed"; public static final String ALTITUDE = "showaltitude"; public static final String DISTANCE = "showdistance"; public static final String COMPASS = "COMPASS"; public static final String LOCATION = "LOCATION"; public static final String MAPPROVIDER = "mapprovider"; public static final String TRACKCOLORING = "trackcoloring"; public static final String SPEEDSANITYCHECK = "speedsanitycheck"; public static final String PRECISION = "precision"; public static final String LOGATSTARTUP = "logatstartup"; public static final String STARTUPATBOOT = "startupatboot"; public static final String LOGATDOCK = "logatdock"; public static final String STOPATUNDOCK = "stopatundock"; public static final String SERVICENAME = "nl.sogeti.android.gpstracker.intent.action.GPSLoggerService"; public static final String STREAMBROADCAST = "nl.sogeti.android.gpstracker.intent.action.STREAMBROADCAST"; public static final String UNITS = "units"; public static final int UNITS_DEFAULT = 0; public static final int UNITS_IMPERIAL = 1; public static final int UNITS_METRIC = 2; public static final int UNITS_NAUTIC = 3; public static final int UNITS_METRICPACE = 4; public static final int UNITS_IMPERIALPACE = 5; public static final int UNITS_IMPERIALSURFACE = 6; public static final int UNITS_METRICSURFACE = 7; public static final String SDDIR_DIR = "SDDIR_DIR"; public static final String DEFAULT_EXTERNAL_DIR = "/OpenGPSTracker/"; public static final String TMPICTUREFILE_SUBPATH = "media_tmp.tmp"; public static final Uri NAME_URI = Uri.parse( "content://" + GPStracking.AUTHORITY+".string" ); public static final int GOOGLE = 0; public static final int OSM = 1; public static final int MAPQUEST = 2; public static final String JOGRUNNER_AUTH = "JOGRUNNER_AUTH"; public static final String EXPORT_TYPE = "SHARE_TYPE"; public static final String EXPORT_GPXTARGET = "EXPORT_GPXTARGET"; public static final String EXPORT_KMZTARGET = "EXPORT_KMZTARGET"; public static final String EXPORT_TXTTARGET = "EXPORT_TXTTARGET"; public static final double MIN_STATISTICS_SPEED = 1.0d; public static final int OSM_CLOUDMADE = 0; public static final int OSM_MAKNIK = 1; public static final int OSM_CYCLE = 2; public static final String OSMBASEOVERLAY = "OSM_BASE_OVERLAY"; public static final String LOGGING_INTERVAL = "customprecisiontime"; public static final String LOGGING_DISTANCE = "customprecisiondistance"; public static final String STATUS_MONITOR = "gpsstatusmonitor"; public static final String OSM_USERNAME = "OSM_USERNAME"; public static final String OSM_PASSWORD = "OSM_PASSWORD"; public static final String OSM_VISIBILITY = "OSM_VISIBILITY"; public static final String DATASOURCES_KEY = "DATASOURCES"; /** * Broadcast intent action indicating that the logger service state has * changed. Includes the logging state and its precision. * * @see #EXTRA_LOGGING_PRECISION * @see #EXTRA_LOGGING_STATE */ public static final String LOGGING_STATE_CHANGED_ACTION = "nl.sogeti.android.gpstracker.LOGGING_STATE_CHANGED"; /** * The precision the service is logging on. * * @see #LOGGING_FINE * @see #LOGGING_NORMAL * @see #LOGGING_COARSE * @see #LOGGING_GLOBAL * @see #LOGGING_CUSTOM * */ public static final String EXTRA_LOGGING_PRECISION = "nl.sogeti.android.gpstracker.EXTRA_LOGGING_PRECISION"; /** * The state the service is. * * @see #UNKNOWN * @see #LOGGING * @see #PAUSED * @see #STOPPED */ public static final String EXTRA_LOGGING_STATE = "nl.sogeti.android.gpstracker.EXTRA_LOGGING_STATE"; /** * The state of the service is unknown */ public static final int UNKNOWN = -1; /** * The service is actively logging, it has requested location update from the location provider. */ public static final int LOGGING = 1; /** * The service is not active, but can be resumed to become active and store location changes as * part of a new segment of the current track. */ public static final int PAUSED = 2; /** * The service is not active and can not resume a current track but must start a new one when becoming active. */ public static final int STOPPED = 3; /** * The precision of the GPS provider is based on the custom time interval and distance. */ public static final int LOGGING_CUSTOM = 0; /** * The GPS location provider is asked to update every 10 seconds or every 5 meters. */ public static final int LOGGING_FINE = 1; /** * The GPS location provider is asked to update every 15 seconds or every 10 meters. */ public static final int LOGGING_NORMAL = 2; /** * The GPS location provider is asked to update every 30 seconds or every 25 meters. */ public static final int LOGGING_COARSE = 3; /** * The radio location provider is asked to update every 5 minutes or every 500 meters. */ public static final int LOGGING_GLOBAL = 4; public static final String REQUEST_URL = "http://api.gobreadcrumbs.com/oauth/request_token"; public static final String ACCESS_URL = "http://api.gobreadcrumbs.com/oauth/access_token"; public static final String AUTHORIZE_URL = "http://api.gobreadcrumbs.com/oauth/authorize"; public static final String OSM_REQUEST_URL = "http://www.openstreetmap.org/oauth/request_token"; public static final String OSM_ACCESS_URL = "http://www.openstreetmap.org/oauth/access_token"; public static final String OSM_AUTHORIZE_URL = "http://www.openstreetmap.org/oauth/authorize"; public static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-opengpstracker"; public static final String OAUTH_CALLBACK_HOST = "callback"; public static final String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME + "://" + OAUTH_CALLBACK_HOST; public static final String NAME = "NAME"; /** * Based on preference return the SD-Card directory in which Open GPS Tracker creates and stores files * shared tracks, * * @param ctx * @return */ public static String getSdCardDirectory( Context ctx ) { // Read preference and ensure start and end with '/' symbol String dir = PreferenceManager.getDefaultSharedPreferences(ctx).getString(SDDIR_DIR, DEFAULT_EXTERNAL_DIR); if( !dir.startsWith("/") ) { dir = "/" + dir; } if( !dir.endsWith("/") ) { dir = dir + "/" ; } dir = Environment.getExternalStorageDirectory().getAbsolutePath() + dir; // If neither exists or can be created fall back to default File dirHandle = new File(dir); if( !dirHandle.exists() && !dirHandle.mkdirs() ) { dir = Environment.getExternalStorageDirectory().getAbsolutePath() + DEFAULT_EXTERNAL_DIR; } return dir; } public static String getSdCardTmpFile( Context ctx ) { String dir = getSdCardDirectory( ctx ) + TMPICTUREFILE_SUBPATH; return dir; } public static final String BREADCRUMBS_CONNECT = "breadcrumbs_connect"; public static final int BREADCRUMBS_CONNECT_ITEM_VIEW_TYPE = 0; public static final int BREADCRUMBS_BUNDLE_ITEM_VIEW_TYPE = 2; public static final int BREADCRUMBS_TRACK_ITEM_VIEW_TYPE = 3; public static final int BREADCRUMBS_ACTIVITY_ITEM_VIEW_TYPE = 4; public static final int SECTIONED_HEADER_ITEM_VIEW_TYPE = 0; public static final String BROADCAST_STREAM = "STREAM_ENABLED"; /** * A distance in meters */ public static final String EXTRA_DISTANCE = "nl.sogeti.android.gpstracker.EXTRA_DISTANCE"; /** * A time period in minutes */ public static final String EXTRA_TIME = "nl.sogeti.android.gpstracker.EXTRA_TIME"; /** * The location that pushed beyond the set minimum time or distance */ public static final String EXTRA_LOCATION = "nl.sogeti.android.gpstracker.EXTRA_LOCATION"; /** * The track that is being logged */ public static final String EXTRA_TRACK = "nl.sogeti.android.gpstracker.EXTRA_TRACK"; }
Java
/* * Copyright (C) 2009 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. */ package nl.sogeti.android.gpstracker.util; /** * Container to ease passing around a tuple of two objects. This object provides a sensible * implementation of equals(), returning true if equals() is true on each of the contained * objects. */ public class Pair<F, S> { public final F first; public final S second; private String toStringOverride; /** * Constructor for a Pair. If either are null then equals() and hashCode() will throw * a NullPointerException. * @param first the first object in the Pair * @param second the second object in the pair */ public Pair(F first, S second) { this.first = first; this.second = second; } /** * Checks the two objects for equality by delegating to their respective equals() methods. * @param o the Pair to which this one is to be checked for equality * @return true if the underlying objects of the Pair are both considered equals() */ @SuppressWarnings("unchecked") @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Pair)) return false; final Pair<F, S> other; try { other = (Pair<F, S>) o; } catch (ClassCastException e) { return false; } return first.equals(other.first) && second.equals(other.second); } /** * Compute a hash code using the hash codes of the underlying objects * @return a hashcode of the Pair */ @Override public int hashCode() { int result = 17; result = 31 * result + first.hashCode(); result = 31 * result + second.hashCode(); return result; } /** * Convenience method for creating an appropriately typed pair. * @param a the first object in the Pair * @param b the second object in the pair * @return a Pair that is templatized with the types of a and b */ public static <A, B> Pair <A, B> create(A a, B b) { return new Pair<A, B>(a, b); } public void overrideToString(String toStringOverride) { this.toStringOverride = toStringOverride; } @Override public String toString() { if( toStringOverride == null ) { return super.toString(); } else { return toStringOverride; } } }
Java
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Feb 25, 2012 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ */ package nl.sogeti.android.gpstracker.viewer; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import nl.sogeti.android.gpstracker.R; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import android.util.Log; import android.webkit.WebView; import android.widget.TextView; /** * ???? * * @version $Id:$ * @author rene (c) Feb 25, 2012, Sogeti B.V. */ public class About extends Activity { private static final String TAG = "OGT.About"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.about); fillContentFields(); } private void fillContentFields() { TextView version = (TextView) findViewById(R.id.version); try { version.setText(getPackageManager().getPackageInfo(getPackageName(), 0).versionName); } catch (NameNotFoundException e) { version.setText(""); } WebView license = (WebView) findViewById(R.id.license_body); license.loadUrl("file:///android_asset/license_short.html"); WebView contributions = (WebView) findViewById(R.id.contribution_body); contributions.loadUrl("file:///android_asset/contributions.html"); WebView notice = (WebView) findViewById(R.id.notices_body); notice.loadUrl("file:///android_asset/notices.html"); } public static String readRawTextFile(Context ctx, int resId) { InputStream inputStream = ctx.getResources().openRawResource(resId); InputStreamReader inputreader = new InputStreamReader(inputStream); BufferedReader buffreader = new BufferedReader(inputreader); String line; StringBuilder text = new StringBuilder(); try { while ((line = buffreader.readLine()) != null) { text.append(line); text.append('\n'); } } catch (IOException e) { Log.e(TAG, "Failed to read raw text resource", e); } return text.toString(); } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.viewer.map; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.SlidingIndicatorView; import nl.sogeti.android.gpstracker.viewer.map.overlay.FixedMyLocationOverlay; import nl.sogeti.android.gpstracker.viewer.map.overlay.OverlayProvider; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.graphics.Bitmap; import android.graphics.Point; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.widget.BaseAdapter; import android.widget.TextView; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapView; /** * Main activity showing a track and allowing logging control * * @version $Id$ * @author rene (c) Jan 18, 2009, Sogeti B.V. */ public class GoogleLoggerMap extends MapActivity implements LoggerMap { LoggerMapHelper mHelper; private MapView mMapView; private TextView[] mSpeedtexts; private TextView mLastGPSSpeedView; private TextView mLastGPSAltitudeView; private TextView mDistanceView; private FixedMyLocationOverlay mMylocation; /** * Called when the activity is first created. */ @Override protected void onCreate(Bundle load) { super.onCreate(load); setContentView(R.layout.map_google); mHelper = new LoggerMapHelper(this); mMapView = (MapView) findViewById(R.id.myMapView); mMylocation = new FixedMyLocationOverlay(this, mMapView); mMapView.setBuiltInZoomControls(true); TextView[] speeds = { (TextView) findViewById(R.id.speedview05), (TextView) findViewById(R.id.speedview04), (TextView) findViewById(R.id.speedview03), (TextView) findViewById(R.id.speedview02), (TextView) findViewById(R.id.speedview01), (TextView) findViewById(R.id.speedview00) }; mSpeedtexts = speeds; mLastGPSSpeedView = (TextView) findViewById(R.id.currentSpeed); mLastGPSAltitudeView = (TextView) findViewById(R.id.currentAltitude); mDistanceView = (TextView) findViewById(R.id.currentDistance); mHelper.onCreate(load); } @Override protected void onResume() { super.onResume(); mHelper.onResume(); } @Override protected void onPause() { mHelper.onPause(); super.onPause(); } @Override protected void onDestroy() { mHelper.onDestroy(); super.onDestroy(); } @Override public void onNewIntent(Intent newIntent) { mHelper.onNewIntent(newIntent); } @Override protected void onRestoreInstanceState(Bundle load) { if (load != null) { super.onRestoreInstanceState(load); } mHelper.onRestoreInstanceState(load); } @Override protected void onSaveInstanceState(Bundle save) { super.onSaveInstanceState(save); mHelper.onSaveInstanceState(save); } @Override public boolean onCreateOptionsMenu(Menu menu) { boolean result = super.onCreateOptionsMenu(menu); mHelper.onCreateOptionsMenu(menu); return result; } @Override public boolean onPrepareOptionsMenu(Menu menu) { mHelper.onPrepareOptionsMenu(menu); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { boolean handled = mHelper.onOptionsItemSelected(item); if( !handled ) { handled = super.onOptionsItemSelected(item); } return handled; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); mHelper.onActivityResult(requestCode, resultCode, intent); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { boolean propagate = true; switch (keyCode) { case KeyEvent.KEYCODE_S: setSatelliteOverlay(!this.mMapView.isSatellite()); propagate = false; break; case KeyEvent.KEYCODE_A: setTrafficOverlay(!this.mMapView.isTraffic()); propagate = false; break; default: propagate = mHelper.onKeyDown(keyCode, event); if( propagate ) { propagate = super.onKeyDown(keyCode, event); } break; } return propagate; } @Override protected Dialog onCreateDialog(int id) { Dialog dialog = mHelper.onCreateDialog(id); if( dialog == null ) { dialog = super.onCreateDialog(id); } return dialog; } @Override protected void onPrepareDialog(int id, Dialog dialog) { mHelper.onPrepareDialog(id, dialog); super.onPrepareDialog(id, dialog); } /******************************/ /** Own methods **/ /******************************/ private void setTrafficOverlay(boolean b) { SharedPreferences sharedPreferences = mHelper.getPreferences(); Editor editor = sharedPreferences.edit(); editor.putBoolean(Constants.TRAFFIC, b); editor.commit(); } private void setSatelliteOverlay(boolean b) { SharedPreferences sharedPreferences = mHelper.getPreferences(); Editor editor = sharedPreferences.edit(); editor.putBoolean(Constants.SATELLITE, b); editor.commit(); } @Override protected boolean isRouteDisplayed() { return true; } @Override protected boolean isLocationDisplayed() { SharedPreferences sharedPreferences = mHelper.getPreferences(); return sharedPreferences.getBoolean(Constants.LOCATION, false) || mHelper.isLogging(); } /******************************/ /** Loggermap methods **/ /******************************/ @Override public void updateOverlays() { SharedPreferences sharedPreferences = mHelper.getPreferences(); GoogleLoggerMap.this.mMapView.setSatellite(sharedPreferences.getBoolean(Constants.SATELLITE, false)); GoogleLoggerMap.this.mMapView.setTraffic(sharedPreferences.getBoolean(Constants.TRAFFIC, false)); } @Override public void setDrawingCacheEnabled(boolean b) { findViewById(R.id.mapScreen).setDrawingCacheEnabled(true); } @Override public Activity getActivity() { return this; } @Override public void onLayerCheckedChanged(int checkedId, boolean isChecked) { switch (checkedId) { case R.id.layer_google_satellite: setSatelliteOverlay(true); break; case R.id.layer_google_regular: setSatelliteOverlay(false); break; case R.id.layer_traffic: setTrafficOverlay(isChecked); break; default: break; } } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(Constants.TRAFFIC)) { updateOverlays(); } else if (key.equals(Constants.SATELLITE)) { updateOverlays(); } } @Override public Bitmap getDrawingCache() { return findViewById(R.id.mapScreen).getDrawingCache(); } @Override public void showMediaDialog(BaseAdapter mediaAdapter) { mHelper.showMediaDialog(mediaAdapter); } public void onDateOverlayChanged() { mMapView.postInvalidate(); } @Override public String getDataSourceId() { return LoggerMapHelper.GOOGLE_PROVIDER; } @Override public boolean isOutsideScreen(GeoPoint lastPoint) { Point out = new Point(); this.mMapView.getProjection().toPixels(lastPoint, out); int height = this.mMapView.getHeight(); int width = this.mMapView.getWidth(); return (out.x < 0 || out.y < 0 || out.y > height || out.x > width); } @Override public boolean isNearScreenEdge(GeoPoint lastPoint) { Point out = new Point(); this.mMapView.getProjection().toPixels(lastPoint, out); int height = this.mMapView.getHeight(); int width = this.mMapView.getWidth(); return (out.x < width / 4 || out.y < height / 4 || out.x > (width / 4) * 3 || out.y > (height / 4) * 3); } @Override public void executePostponedActions() { // NOOP for Google Maps } @Override public void enableCompass() { mMylocation.enableCompass(); } @Override public void enableMyLocation() { mMylocation.enableMyLocation(); } @Override public void disableMyLocation() { mMylocation.disableMyLocation(); } @Override public void disableCompass() { mMylocation.disableCompass(); } @Override public void setZoom(int zoom) { mMapView.getController().setZoom(zoom); } @Override public void animateTo(GeoPoint storedPoint) { mMapView.getController().animateTo(storedPoint); } @Override public int getZoomLevel() { return mMapView.getZoomLevel(); } @Override public GeoPoint getMapCenter() { return mMapView.getMapCenter(); } @Override public boolean zoomOut() { return mMapView.getController().zoomOut(); } @Override public boolean zoomIn() { return mMapView.getController().zoomIn(); } @Override public void postInvalidate() { mMapView.postInvalidate(); } @Override public void clearAnimation() { mMapView.clearAnimation(); } @Override public void setCenter(GeoPoint lastPoint) { mMapView.getController().setCenter(lastPoint); } @Override public int getMaxZoomLevel() { return mMapView.getMaxZoomLevel(); } @Override public GeoPoint fromPixels(int x, int y) { return mMapView.getProjection().fromPixels(x, y); } @Override public boolean hasProjection() { return mMapView.getProjection() != null; } @Override public float metersToEquatorPixels(float float1) { return mMapView.getProjection().metersToEquatorPixels(float1); } @Override public void toPixels(GeoPoint geoPoint, Point screenPoint) { mMapView.getProjection().toPixels(geoPoint, screenPoint); } @Override public TextView[] getSpeedTextViews() { return mSpeedtexts; } @Override public TextView getAltitideTextView() { return mLastGPSAltitudeView; } @Override public TextView getSpeedTextView() { return mLastGPSSpeedView; } @Override public TextView getDistanceTextView() { return mDistanceView; } @Override public void addOverlay(OverlayProvider overlay) { mMapView.getOverlays().add(overlay.getGoogleOverlay()); } @Override public void clearOverlays() { mMapView.getOverlays().clear(); } @Override public SlidingIndicatorView getScaleIndicatorView() { return (SlidingIndicatorView) findViewById(R.id.scaleindicator); } }
Java
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Feb 26, 2012 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ */ package nl.sogeti.android.gpstracker.viewer.map; import java.util.concurrent.Semaphore; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.ControlTracking; import nl.sogeti.android.gpstracker.actions.InsertNote; import nl.sogeti.android.gpstracker.actions.ShareTrack; import nl.sogeti.android.gpstracker.actions.Statistics; import nl.sogeti.android.gpstracker.db.GPStracking.Media; import nl.sogeti.android.gpstracker.db.GPStracking.Segments; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints; import nl.sogeti.android.gpstracker.logger.GPSLoggerServiceManager; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.SlidingIndicatorView; import nl.sogeti.android.gpstracker.util.UnitsI18n; import nl.sogeti.android.gpstracker.viewer.About; import nl.sogeti.android.gpstracker.viewer.ApplicationPreferenceActivity; import nl.sogeti.android.gpstracker.viewer.TrackList; import nl.sogeti.android.gpstracker.viewer.map.overlay.BitmapSegmentsOverlay; import nl.sogeti.android.gpstracker.viewer.map.overlay.SegmentRendering; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.Bitmap; import android.location.Location; import android.location.LocationManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.preference.PreferenceManager; import android.util.Log; import android.view.ContextMenu; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.Gallery; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import com.google.android.maps.GeoPoint; /** * ???? * * @version $Id:$ * @author rene (c) Feb 26, 2012, Sogeti B.V. */ public class LoggerMapHelper { public static final String OSM_PROVIDER = "OSM"; public static final String GOOGLE_PROVIDER = "GOOGLE"; public static final String MAPQUEST_PROVIDER = "MAPQUEST"; private static final String INSTANCE_E6LONG = "e6long"; private static final String INSTANCE_E6LAT = "e6lat"; private static final String INSTANCE_ZOOM = "zoom"; private static final String INSTANCE_AVGSPEED = "averagespeed"; private static final String INSTANCE_HEIGHT = "averageheight"; private static final String INSTANCE_TRACK = "track"; private static final String INSTANCE_SPEED = "speed"; private static final String INSTANCE_ALTITUDE = "altitude"; private static final String INSTANCE_DISTANCE = "distance"; private static final int ZOOM_LEVEL = 16; // MENU'S private static final int MENU_SETTINGS = 1; private static final int MENU_TRACKING = 2; private static final int MENU_TRACKLIST = 3; private static final int MENU_STATS = 4; private static final int MENU_ABOUT = 5; private static final int MENU_LAYERS = 6; private static final int MENU_NOTE = 7; private static final int MENU_SHARE = 13; private static final int MENU_CONTRIB = 14; private static final int DIALOG_NOTRACK = 24; private static final int DIALOG_LAYERS = 31; private static final int DIALOG_URIS = 34; private static final int DIALOG_CONTRIB = 35; private static final String TAG = "OGT.LoggerMap"; private double mAverageSpeed = 33.33d / 3d; private double mAverageHeight = 33.33d / 3d; private long mTrackId = -1; private long mLastSegment = -1; private UnitsI18n mUnits; private WakeLock mWakeLock = null; private SharedPreferences mSharedPreferences; private GPSLoggerServiceManager mLoggerServiceManager; private SegmentRendering mLastSegmentOverlay; private BaseAdapter mMediaAdapter; private Handler mHandler; private ContentObserver mTrackSegmentsObserver; private ContentObserver mSegmentWaypointsObserver; private ContentObserver mTrackMediasObserver; private DialogInterface.OnClickListener mNoTrackDialogListener; private OnItemSelectedListener mGalerySelectListener; private Uri mSelected; private OnClickListener mNoteSelectDialogListener; private OnCheckedChangeListener mCheckedChangeListener; private android.widget.RadioGroup.OnCheckedChangeListener mGroupCheckedChangeListener; private OnSharedPreferenceChangeListener mSharedPreferenceChangeListener; private UnitsI18n.UnitsChangeListener mUnitsChangeListener; /** * Run after the ServiceManager completes the binding to the remote service */ private Runnable mServiceConnected; private Runnable speedCalculator; private Runnable heightCalculator; private LoggerMap mLoggerMap; private BitmapSegmentsOverlay mBitmapSegmentsOverlay; private float mSpeed; private double mAltitude; private float mDistance; public LoggerMapHelper(LoggerMap loggerMap) { mLoggerMap = loggerMap; } /** * Called when the activity is first created. */ protected void onCreate(Bundle load) { mLoggerMap.setDrawingCacheEnabled(true); mUnits = new UnitsI18n(mLoggerMap.getActivity()); mLoggerServiceManager = new GPSLoggerServiceManager(mLoggerMap.getActivity()); final Semaphore calulatorSemaphore = new Semaphore(0); Thread calulator = new Thread("OverlayCalculator") { @Override public void run() { Looper.prepare(); mHandler = new Handler(); calulatorSemaphore.release(); Looper.loop(); } }; calulator.start(); try { calulatorSemaphore.acquire(); } catch (InterruptedException e) { Log.e(TAG, "Failed waiting for a semaphore", e); } mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(mLoggerMap.getActivity()); mBitmapSegmentsOverlay = new BitmapSegmentsOverlay(mLoggerMap, mHandler); createListeners(); onRestoreInstanceState(load); mLoggerMap.updateOverlays(); } protected void onResume() { updateMapProvider(); mLoggerServiceManager.startup(mLoggerMap.getActivity(), mServiceConnected); mSharedPreferences.registerOnSharedPreferenceChangeListener(mSharedPreferenceChangeListener); mUnits.setUnitsChangeListener(mUnitsChangeListener); updateTitleBar(); updateBlankingBehavior(); if (mTrackId >= 0) { ContentResolver resolver = mLoggerMap.getActivity().getContentResolver(); Uri trackUri = Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/segments"); Uri lastSegmentUri = Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/segments/" + mLastSegment + "/waypoints"); Uri mediaUri = ContentUris.withAppendedId(Media.CONTENT_URI, mTrackId); resolver.unregisterContentObserver(this.mTrackSegmentsObserver); resolver.unregisterContentObserver(this.mSegmentWaypointsObserver); resolver.unregisterContentObserver(this.mTrackMediasObserver); resolver.registerContentObserver(trackUri, false, this.mTrackSegmentsObserver); resolver.registerContentObserver(lastSegmentUri, true, this.mSegmentWaypointsObserver); resolver.registerContentObserver(mediaUri, true, this.mTrackMediasObserver); } updateDataOverlays(); updateSpeedColoring(); updateSpeedDisplayVisibility(); updateAltitudeDisplayVisibility(); updateDistanceDisplayVisibility(); updateCompassDisplayVisibility(); updateLocationDisplayVisibility(); updateTrackNumbers(); mLoggerMap.executePostponedActions(); } protected void onPause() { if (this.mWakeLock != null && this.mWakeLock.isHeld()) { this.mWakeLock.release(); Log.w(TAG, "onPause(): Released lock to keep screen on!"); } mLoggerMap.clearOverlays(); mBitmapSegmentsOverlay.clearSegments(); mLastSegmentOverlay = null; ContentResolver resolver = mLoggerMap.getActivity().getContentResolver(); resolver.unregisterContentObserver(this.mTrackSegmentsObserver); resolver.unregisterContentObserver(this.mSegmentWaypointsObserver); resolver.unregisterContentObserver(this.mTrackMediasObserver); mSharedPreferences.unregisterOnSharedPreferenceChangeListener(this.mSharedPreferenceChangeListener); mUnits.setUnitsChangeListener(null); mLoggerMap.disableMyLocation(); mLoggerMap.disableCompass(); this.mLoggerServiceManager.shutdown(mLoggerMap.getActivity()); } protected void onDestroy() { mLoggerMap.clearOverlays(); mHandler.post(new Runnable() { @Override public void run() { Looper.myLooper().quit(); } }); if (mWakeLock != null && mWakeLock.isHeld()) { mWakeLock.release(); Log.w(TAG, "onDestroy(): Released lock to keep screen on!"); } if (mLoggerServiceManager.getLoggingState() == Constants.STOPPED) { mLoggerMap.getActivity().stopService(new Intent(Constants.SERVICENAME)); } mUnits = null; } public void onNewIntent(Intent newIntent) { Uri data = newIntent.getData(); if (data != null) { moveToTrack(Long.parseLong(data.getLastPathSegment()), true); } } protected void onRestoreInstanceState(Bundle load) { Uri data = mLoggerMap.getActivity().getIntent().getData(); if (load != null && load.containsKey(INSTANCE_TRACK)) // 1st method: track from a previous instance of this activity { long loadTrackId = load.getLong(INSTANCE_TRACK); moveToTrack(loadTrackId, false); if (load.containsKey(INSTANCE_AVGSPEED)) { mAverageSpeed = load.getDouble(INSTANCE_AVGSPEED); } if (load.containsKey(INSTANCE_HEIGHT)) { mAverageHeight = load.getDouble(INSTANCE_HEIGHT); } if( load.containsKey(INSTANCE_SPEED)) { mSpeed = load.getFloat(INSTANCE_SPEED); } if( load.containsKey(INSTANCE_ALTITUDE)) { mAltitude = load.getDouble(INSTANCE_HEIGHT); } if( load.containsKey(INSTANCE_DISTANCE)) { mDistance = load.getFloat(INSTANCE_DISTANCE); } } else if (data != null) // 2nd method: track ordered to make { long loadTrackId = Long.parseLong(data.getLastPathSegment()); moveToTrack(loadTrackId, true); } else // 3rd method: just try the last track { moveToLastTrack(); } if (load != null && load.containsKey(INSTANCE_ZOOM)) { mLoggerMap.setZoom(load.getInt(INSTANCE_ZOOM)); } else { mLoggerMap.setZoom(ZOOM_LEVEL); } if (load != null && load.containsKey(INSTANCE_E6LAT) && load.containsKey(INSTANCE_E6LONG)) { GeoPoint storedPoint = new GeoPoint(load.getInt(INSTANCE_E6LAT), load.getInt(INSTANCE_E6LONG)); mLoggerMap.animateTo(storedPoint); } else { GeoPoint lastPoint = getLastTrackPoint(); mLoggerMap.animateTo(lastPoint); } } protected void onSaveInstanceState(Bundle save) { save.putLong(INSTANCE_TRACK, this.mTrackId); save.putDouble(INSTANCE_AVGSPEED, mAverageSpeed); save.putDouble(INSTANCE_HEIGHT, mAverageHeight); save.putInt(INSTANCE_ZOOM, mLoggerMap.getZoomLevel()); save.putFloat(INSTANCE_SPEED, mSpeed); save.putDouble(INSTANCE_ALTITUDE, mAltitude); save.putFloat(INSTANCE_DISTANCE, mDistance); GeoPoint point = mLoggerMap.getMapCenter(); save.putInt(INSTANCE_E6LAT, point.getLatitudeE6()); save.putInt(INSTANCE_E6LONG, point.getLongitudeE6()); } public boolean onKeyDown(int keyCode, KeyEvent event) { boolean propagate = true; switch (keyCode) { case KeyEvent.KEYCODE_T: propagate = mLoggerMap.zoomIn(); propagate = false; break; case KeyEvent.KEYCODE_G: propagate = mLoggerMap.zoomOut(); propagate = false; break; case KeyEvent.KEYCODE_F: moveToTrack(this.mTrackId - 1, true); propagate = false; break; case KeyEvent.KEYCODE_H: moveToTrack(this.mTrackId + 1, true); propagate = false; break; } return propagate; } private void setSpeedOverlay(boolean b) { Editor editor = mSharedPreferences.edit(); editor.putBoolean(Constants.SPEED, b); editor.commit(); } private void setAltitudeOverlay(boolean b) { Editor editor = mSharedPreferences.edit(); editor.putBoolean(Constants.ALTITUDE, b); editor.commit(); } private void setDistanceOverlay(boolean b) { Editor editor = mSharedPreferences.edit(); editor.putBoolean(Constants.DISTANCE, b); editor.commit(); } private void setCompassOverlay(boolean b) { Editor editor = mSharedPreferences.edit(); editor.putBoolean(Constants.COMPASS, b); editor.commit(); } private void setLocationOverlay(boolean b) { Editor editor = mSharedPreferences.edit(); editor.putBoolean(Constants.LOCATION, b); editor.commit(); } private void setOsmBaseOverlay(int b) { Editor editor = mSharedPreferences.edit(); editor.putInt(Constants.OSMBASEOVERLAY, b); editor.commit(); } private void createListeners() { /******************************************************* * 8 Runnable listener actions */ speedCalculator = new Runnable() { @Override public void run() { double avgspeed = 0.0; ContentResolver resolver = mLoggerMap.getActivity().getContentResolver(); Cursor waypointsCursor = null; try { waypointsCursor = resolver.query(Uri.withAppendedPath(Tracks.CONTENT_URI, LoggerMapHelper.this.mTrackId + "/waypoints"), new String[] { "avg(" + Waypoints.SPEED + ")", "max(" + Waypoints.SPEED + ")" }, null, null, null); if (waypointsCursor != null && waypointsCursor.moveToLast()) { double average = waypointsCursor.getDouble(0); double maxBasedAverage = waypointsCursor.getDouble(1) / 2; avgspeed = Math.min(average, maxBasedAverage); } if (avgspeed < 2) { avgspeed = 5.55d / 2; } } finally { if (waypointsCursor != null) { waypointsCursor.close(); } } mAverageSpeed = avgspeed; mLoggerMap.getActivity().runOnUiThread(new Runnable() { @Override public void run() { updateSpeedColoring(); } }); } }; heightCalculator = new Runnable() { @Override public void run() { double avgHeight = 0.0; ContentResolver resolver = mLoggerMap.getActivity().getContentResolver(); Cursor waypointsCursor = null; try { waypointsCursor = resolver.query(Uri.withAppendedPath(Tracks.CONTENT_URI, LoggerMapHelper.this.mTrackId + "/waypoints"), new String[] { "avg(" + Waypoints.ALTITUDE + ")", "max(" + Waypoints.ALTITUDE + ")" }, null, null, null); if (waypointsCursor != null && waypointsCursor.moveToLast()) { double average = waypointsCursor.getDouble(0); double maxBasedAverage = waypointsCursor.getDouble(1) / 2; avgHeight = Math.min(average, maxBasedAverage); } } finally { if (waypointsCursor != null) { waypointsCursor.close(); } } mAverageHeight = avgHeight; mLoggerMap.getActivity().runOnUiThread(new Runnable() { @Override public void run() { updateSpeedColoring(); } }); } }; mServiceConnected = new Runnable() { @Override public void run() { updateBlankingBehavior(); } }; /******************************************************* * 8 Various dialog listeners */ mGalerySelectListener = new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView< ? > parent, View view, int pos, long id) { mSelected = (Uri) parent.getSelectedItem(); } @Override public void onNothingSelected(AdapterView< ? > arg0) { mSelected = null; } }; mNoteSelectDialogListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { SegmentRendering.handleMedia(mLoggerMap.getActivity(), mSelected); mSelected = null; } }; mGroupCheckedChangeListener = new android.widget.RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.layer_osm_cloudmade: setOsmBaseOverlay(Constants.OSM_CLOUDMADE); break; case R.id.layer_osm_maknik: setOsmBaseOverlay(Constants.OSM_MAKNIK); break; case R.id.layer_osm_bicycle: setOsmBaseOverlay(Constants.OSM_CYCLE); break; default: mLoggerMap.onLayerCheckedChanged(checkedId, true); break; } } }; mCheckedChangeListener = new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { int checkedId; checkedId = buttonView.getId(); switch (checkedId) { case R.id.layer_speed: setSpeedOverlay(isChecked); break; case R.id.layer_altitude: setAltitudeOverlay(isChecked); break; case R.id.layer_distance: setDistanceOverlay(isChecked); break; case R.id.layer_compass: setCompassOverlay(isChecked); break; case R.id.layer_location: setLocationOverlay(isChecked); break; default: mLoggerMap.onLayerCheckedChanged(checkedId, isChecked); break; } } }; mNoTrackDialogListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Log.d( TAG, "mNoTrackDialogListener" + which); Intent tracklistIntent = new Intent(mLoggerMap.getActivity(), TrackList.class); tracklistIntent.putExtra(Tracks._ID, mTrackId); mLoggerMap.getActivity().startActivityForResult(tracklistIntent, MENU_TRACKLIST); } }; /** * Listeners to events outside this mapview */ mSharedPreferenceChangeListener = new OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(Constants.TRACKCOLORING)) { mAverageSpeed = 0.0; mAverageHeight = 0.0; updateSpeedColoring(); } else if (key.equals(Constants.DISABLEBLANKING) || key.equals(Constants.DISABLEDIMMING)) { updateBlankingBehavior(); } else if (key.equals(Constants.SPEED)) { updateSpeedDisplayVisibility(); } else if (key.equals(Constants.ALTITUDE)) { updateAltitudeDisplayVisibility(); } else if (key.equals(Constants.DISTANCE)) { updateDistanceDisplayVisibility(); } else if (key.equals(Constants.COMPASS)) { updateCompassDisplayVisibility(); } else if (key.equals(Constants.LOCATION)) { updateLocationDisplayVisibility(); } else if (key.equals(Constants.MAPPROVIDER)) { updateMapProvider(); } else if (key.equals(Constants.OSMBASEOVERLAY)) { mLoggerMap.updateOverlays(); } else { mLoggerMap.onSharedPreferenceChanged(sharedPreferences, key); } } }; mTrackMediasObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfUpdate) { if (!selfUpdate) { if (mLastSegmentOverlay != null) { mLastSegmentOverlay.calculateMedia(); } } else { Log.w(TAG, "mTrackMediasObserver skipping change on " + mLastSegment); } } }; mTrackSegmentsObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfUpdate) { if (!selfUpdate) { updateDataOverlays(); } else { Log.w(TAG, "mTrackSegmentsObserver skipping change on " + mLastSegment); } } }; mSegmentWaypointsObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfUpdate) { if (!selfUpdate) { updateTrackNumbers(); if (mLastSegmentOverlay != null) { moveActiveViewWindow(); updateMapProviderAdministration(mLoggerMap.getDataSourceId()); } else { Log.e(TAG, "Error the last segment changed but it is not on screen! " + mLastSegment); } } else { Log.w(TAG, "mSegmentWaypointsObserver skipping change on " + mLastSegment); } } }; mUnitsChangeListener = new UnitsI18n.UnitsChangeListener() { @Override public void onUnitsChange() { mAverageSpeed = 0.0; mAverageHeight = 0.0; updateTrackNumbers(); updateSpeedColoring(); } }; } public void onCreateOptionsMenu(Menu menu) { menu.add(ContextMenu.NONE, MENU_TRACKING, ContextMenu.NONE, R.string.menu_tracking).setIcon(R.drawable.ic_menu_movie).setAlphabeticShortcut('T'); menu.add(ContextMenu.NONE, MENU_LAYERS, ContextMenu.NONE, R.string.menu_showLayers).setIcon(R.drawable.ic_menu_mapmode).setAlphabeticShortcut('L'); menu.add(ContextMenu.NONE, MENU_NOTE, ContextMenu.NONE, R.string.menu_insertnote).setIcon(R.drawable.ic_menu_myplaces); menu.add(ContextMenu.NONE, MENU_STATS, ContextMenu.NONE, R.string.menu_statistics).setIcon(R.drawable.ic_menu_picture).setAlphabeticShortcut('S'); menu.add(ContextMenu.NONE, MENU_SHARE, ContextMenu.NONE, R.string.menu_shareTrack).setIcon(R.drawable.ic_menu_share).setAlphabeticShortcut('I'); // More menu.add(ContextMenu.NONE, MENU_TRACKLIST, ContextMenu.NONE, R.string.menu_tracklist).setIcon(R.drawable.ic_menu_show_list).setAlphabeticShortcut('P'); menu.add(ContextMenu.NONE, MENU_SETTINGS, ContextMenu.NONE, R.string.menu_settings).setIcon(R.drawable.ic_menu_preferences).setAlphabeticShortcut('C'); menu.add(ContextMenu.NONE, MENU_ABOUT, ContextMenu.NONE, R.string.menu_about).setIcon(R.drawable.ic_menu_info_details).setAlphabeticShortcut('A'); menu.add(ContextMenu.NONE, MENU_CONTRIB, ContextMenu.NONE, R.string.menu_contrib).setIcon(R.drawable.ic_menu_allfriends); } public void onPrepareOptionsMenu(Menu menu) { MenuItem noteMenu = menu.findItem(MENU_NOTE); noteMenu.setEnabled(mLoggerServiceManager.isMediaPrepared()); MenuItem shareMenu = menu.findItem(MENU_SHARE); shareMenu.setEnabled(mTrackId >= 0); } public boolean onOptionsItemSelected(MenuItem item) { boolean handled = false; Uri trackUri; Intent intent; switch (item.getItemId()) { case MENU_TRACKING: intent = new Intent(mLoggerMap.getActivity(), ControlTracking.class); mLoggerMap.getActivity().startActivityForResult(intent, MENU_TRACKING); handled = true; break; case MENU_LAYERS: mLoggerMap.getActivity().showDialog(DIALOG_LAYERS); handled = true; break; case MENU_NOTE: intent = new Intent(mLoggerMap.getActivity(), InsertNote.class); mLoggerMap.getActivity().startActivityForResult(intent, MENU_NOTE); handled = true; break; case MENU_SETTINGS: intent = new Intent(mLoggerMap.getActivity(), ApplicationPreferenceActivity.class); mLoggerMap.getActivity().startActivity(intent); handled = true; break; case MENU_TRACKLIST: intent = new Intent(mLoggerMap.getActivity(), TrackList.class); intent.putExtra(Tracks._ID, this.mTrackId); mLoggerMap.getActivity().startActivityForResult(intent, MENU_TRACKLIST); handled = true; break; case MENU_STATS: if (this.mTrackId >= 0) { intent = new Intent(mLoggerMap.getActivity(), Statistics.class); trackUri = ContentUris.withAppendedId(Tracks.CONTENT_URI, mTrackId); intent.setData(trackUri); mLoggerMap.getActivity().startActivity(intent); break; } else { mLoggerMap.getActivity().showDialog(DIALOG_NOTRACK); } handled = true; break; case MENU_ABOUT: intent = new Intent(mLoggerMap.getActivity(), About.class); mLoggerMap.getActivity().startActivity(intent); break; case MENU_SHARE: intent = new Intent(Intent.ACTION_RUN); trackUri = ContentUris.withAppendedId(Tracks.CONTENT_URI, mTrackId); intent.setDataAndType(trackUri, Tracks.CONTENT_ITEM_TYPE); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); Bitmap bm = mLoggerMap.getDrawingCache(); Uri screenStreamUri = ShareTrack.storeScreenBitmap(bm); intent.putExtra(Intent.EXTRA_STREAM, screenStreamUri); mLoggerMap.getActivity().startActivityForResult(Intent.createChooser(intent, mLoggerMap.getActivity().getString(R.string.share_track)), MENU_SHARE); handled = true; break; case MENU_CONTRIB: mLoggerMap.getActivity().showDialog(DIALOG_CONTRIB); default: handled = false; break; } return handled; } protected Dialog onCreateDialog(int id) { Dialog dialog = null; LayoutInflater factory = null; View view = null; Builder builder = null; switch (id) { case DIALOG_LAYERS: builder = new AlertDialog.Builder(mLoggerMap.getActivity()); factory = LayoutInflater.from(mLoggerMap.getActivity()); view = factory.inflate(R.layout.layerdialog, null); CheckBox traffic = (CheckBox) view.findViewById(R.id.layer_traffic); CheckBox speed = (CheckBox) view.findViewById(R.id.layer_speed); CheckBox altitude = (CheckBox) view.findViewById(R.id.layer_altitude); CheckBox distance = (CheckBox) view.findViewById(R.id.layer_distance); CheckBox compass = (CheckBox) view.findViewById(R.id.layer_compass); CheckBox location = (CheckBox) view.findViewById(R.id.layer_location); ((RadioGroup) view.findViewById(R.id.google_backgrounds)).setOnCheckedChangeListener(mGroupCheckedChangeListener); ((RadioGroup) view.findViewById(R.id.osm_backgrounds)).setOnCheckedChangeListener(mGroupCheckedChangeListener); traffic.setOnCheckedChangeListener(mCheckedChangeListener); speed.setOnCheckedChangeListener(mCheckedChangeListener); altitude.setOnCheckedChangeListener(mCheckedChangeListener); distance.setOnCheckedChangeListener(mCheckedChangeListener); compass.setOnCheckedChangeListener(mCheckedChangeListener); location.setOnCheckedChangeListener(mCheckedChangeListener); builder.setTitle(R.string.dialog_layer_title).setIcon(android.R.drawable.ic_dialog_map).setPositiveButton(R.string.btn_okay, null).setView(view); dialog = builder.create(); return dialog; case DIALOG_NOTRACK: builder = new AlertDialog.Builder(mLoggerMap.getActivity()); builder.setTitle(R.string.dialog_notrack_title).setMessage(R.string.dialog_notrack_message).setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.btn_selecttrack, mNoTrackDialogListener).setNegativeButton(R.string.btn_cancel, null); dialog = builder.create(); return dialog; case DIALOG_URIS: builder = new AlertDialog.Builder(mLoggerMap.getActivity()); factory = LayoutInflater.from(mLoggerMap.getActivity()); view = factory.inflate(R.layout.mediachooser, null); builder.setTitle(R.string.dialog_select_media_title).setMessage(R.string.dialog_select_media_message).setIcon(android.R.drawable.ic_dialog_alert) .setNegativeButton(R.string.btn_cancel, null).setPositiveButton(R.string.btn_okay, mNoteSelectDialogListener).setView(view); dialog = builder.create(); return dialog; case DIALOG_CONTRIB: builder = new AlertDialog.Builder(mLoggerMap.getActivity()); factory = LayoutInflater.from(mLoggerMap.getActivity()); view = factory.inflate(R.layout.contrib, null); TextView contribView = (TextView) view.findViewById(R.id.contrib_view); contribView.setText(R.string.dialog_contrib_message); builder.setTitle(R.string.dialog_contrib_title).setView(view).setIcon(android.R.drawable.ic_dialog_email) .setPositiveButton(R.string.btn_okay, null); dialog = builder.create(); return dialog; default: return null; } } protected void onPrepareDialog(int id, Dialog dialog) { RadioButton satellite; RadioButton regular; RadioButton cloudmade; RadioButton mapnik; RadioButton cycle; switch (id) { case DIALOG_LAYERS: satellite = (RadioButton) dialog.findViewById(R.id.layer_google_satellite); regular = (RadioButton) dialog.findViewById(R.id.layer_google_regular); satellite.setChecked(mSharedPreferences.getBoolean(Constants.SATELLITE, false)); regular.setChecked(!mSharedPreferences.getBoolean(Constants.SATELLITE, false)); int osmbase = mSharedPreferences.getInt(Constants.OSMBASEOVERLAY, 0); cloudmade = (RadioButton) dialog.findViewById(R.id.layer_osm_cloudmade); mapnik = (RadioButton) dialog.findViewById(R.id.layer_osm_maknik); cycle = (RadioButton) dialog.findViewById(R.id.layer_osm_bicycle); cloudmade.setChecked(osmbase == Constants.OSM_CLOUDMADE); mapnik.setChecked(osmbase == Constants.OSM_MAKNIK); cycle.setChecked(osmbase == Constants.OSM_CYCLE); ((CheckBox) dialog.findViewById(R.id.layer_traffic)).setChecked(mSharedPreferences.getBoolean(Constants.TRAFFIC, false)); ((CheckBox) dialog.findViewById(R.id.layer_speed)).setChecked(mSharedPreferences.getBoolean(Constants.SPEED, false)); ((CheckBox) dialog.findViewById(R.id.layer_altitude)).setChecked(mSharedPreferences.getBoolean(Constants.ALTITUDE, false)); ((CheckBox) dialog.findViewById(R.id.layer_distance)).setChecked(mSharedPreferences.getBoolean(Constants.DISTANCE, false)); ((CheckBox) dialog.findViewById(R.id.layer_compass)).setChecked(mSharedPreferences.getBoolean(Constants.COMPASS, false)); ((CheckBox) dialog.findViewById(R.id.layer_location)).setChecked(mSharedPreferences.getBoolean(Constants.LOCATION, false)); int provider = Integer.valueOf(mSharedPreferences.getString(Constants.MAPPROVIDER, "" + Constants.GOOGLE)).intValue(); switch (provider) { case Constants.GOOGLE: dialog.findViewById(R.id.google_backgrounds).setVisibility(View.VISIBLE); dialog.findViewById(R.id.osm_backgrounds).setVisibility(View.GONE); dialog.findViewById(R.id.shared_layers).setVisibility(View.VISIBLE); dialog.findViewById(R.id.google_overlays).setVisibility(View.VISIBLE); break; case Constants.OSM: dialog.findViewById(R.id.osm_backgrounds).setVisibility(View.VISIBLE); dialog.findViewById(R.id.google_backgrounds).setVisibility(View.GONE); dialog.findViewById(R.id.shared_layers).setVisibility(View.VISIBLE); dialog.findViewById(R.id.google_overlays).setVisibility(View.GONE); break; default: dialog.findViewById(R.id.osm_backgrounds).setVisibility(View.GONE); dialog.findViewById(R.id.google_backgrounds).setVisibility(View.GONE); dialog.findViewById(R.id.shared_layers).setVisibility(View.VISIBLE); dialog.findViewById(R.id.google_overlays).setVisibility(View.GONE); break; } break; case DIALOG_URIS: Gallery gallery = (Gallery) dialog.findViewById(R.id.gallery); gallery.setAdapter(mMediaAdapter); gallery.setOnItemSelectedListener(mGalerySelectListener); default: break; } } protected void onActivityResult(int requestCode, int resultCode, Intent intent) { Uri trackUri; long trackId; switch (requestCode) { case MENU_TRACKLIST: if (resultCode == Activity.RESULT_OK) { trackUri = intent.getData(); trackId = Long.parseLong(trackUri.getLastPathSegment()); moveToTrack(trackId, true); } break; case MENU_TRACKING: if (resultCode == Activity.RESULT_OK) { trackUri = intent.getData(); if (trackUri != null) { trackId = Long.parseLong(trackUri.getLastPathSegment()); moveToTrack(trackId, true); } } break; case MENU_SHARE: ShareTrack.clearScreenBitmap(); break; default: Log.e(TAG, "Returned form unknow activity: " + requestCode); break; } } private void updateTitleBar() { ContentResolver resolver = mLoggerMap.getActivity().getContentResolver(); Cursor trackCursor = null; try { trackCursor = resolver.query(ContentUris.withAppendedId(Tracks.CONTENT_URI, this.mTrackId), new String[] { Tracks.NAME }, null, null, null); if (trackCursor != null && trackCursor.moveToLast()) { String trackName = trackCursor.getString(0); mLoggerMap.getActivity().setTitle(mLoggerMap.getActivity().getString(R.string.app_name) + ": " + trackName); } } finally { if (trackCursor != null) { trackCursor.close(); } } } private void updateMapProvider() { Class< ? > mapClass = null; int provider = Integer.valueOf(mSharedPreferences.getString(Constants.MAPPROVIDER, "" + Constants.GOOGLE)).intValue(); switch (provider) { case Constants.GOOGLE: mapClass = GoogleLoggerMap.class; break; case Constants.OSM: mapClass = OsmLoggerMap.class; break; case Constants.MAPQUEST: mapClass = MapQuestLoggerMap.class; break; default: mapClass = GoogleLoggerMap.class; Log.e(TAG, "Fault in value " + provider + " as MapProvider, defaulting to Google Maps."); break; } if (mapClass != mLoggerMap.getActivity().getClass()) { Intent myIntent = mLoggerMap.getActivity().getIntent(); Intent realIntent; if (myIntent != null) { realIntent = new Intent(myIntent.getAction(), myIntent.getData(), mLoggerMap.getActivity(), mapClass); realIntent.putExtras(myIntent); } else { realIntent = new Intent(mLoggerMap.getActivity(), mapClass); realIntent.putExtras(myIntent); } mLoggerMap.getActivity().startActivity(realIntent); mLoggerMap.getActivity().finish(); } } protected void updateMapProviderAdministration(String provider) { mLoggerServiceManager.storeDerivedDataSource(provider); } private void updateBlankingBehavior() { boolean disableblanking = mSharedPreferences.getBoolean(Constants.DISABLEBLANKING, false); boolean disabledimming = mSharedPreferences.getBoolean(Constants.DISABLEDIMMING, false); if (disableblanking) { if (mWakeLock == null) { PowerManager pm = (PowerManager) mLoggerMap.getActivity().getSystemService(Context.POWER_SERVICE); if (disabledimming) { mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, TAG); } else { mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, TAG); } } if (mLoggerServiceManager.getLoggingState() == Constants.LOGGING && !mWakeLock.isHeld()) { mWakeLock.acquire(); Log.w(TAG, "Acquired lock to keep screen on!"); } } } private void updateSpeedColoring() { int trackColoringMethod = Integer.valueOf(mSharedPreferences.getString(Constants.TRACKCOLORING, "3")).intValue(); View speedbar = mLoggerMap.getActivity().findViewById(R.id.speedbar); SlidingIndicatorView scaleIndicator = mLoggerMap.getScaleIndicatorView(); TextView[] speedtexts = mLoggerMap.getSpeedTextViews(); switch (trackColoringMethod) { case SegmentRendering.DRAW_MEASURED: case SegmentRendering.DRAW_CALCULATED: // mAverageSpeed is set to 0 if unknown or to trigger an recalculation here if (mAverageSpeed == 0.0) { mHandler.removeCallbacks(speedCalculator); mHandler.post(speedCalculator); } else { drawSpeedTexts(); speedtexts = mLoggerMap.getSpeedTextViews(); speedbar.setVisibility(View.VISIBLE); scaleIndicator.setVisibility(View.VISIBLE); for (int i = 0; i < speedtexts.length; i++) { speedtexts[i].setVisibility(View.VISIBLE); } } break; case SegmentRendering.DRAW_DOTS: case SegmentRendering.DRAW_GREEN: case SegmentRendering.DRAW_RED: speedbar.setVisibility(View.INVISIBLE); scaleIndicator.setVisibility(View.INVISIBLE); for (int i = 0; i < speedtexts.length; i++) { speedtexts[i].setVisibility(View.INVISIBLE); } break; case SegmentRendering.DRAW_HEIGHT: if (mAverageHeight == 0.0) { mHandler.removeCallbacks(heightCalculator); mHandler.post(heightCalculator); } else { drawHeightTexts(); speedtexts = mLoggerMap.getSpeedTextViews(); speedbar.setVisibility(View.VISIBLE); scaleIndicator.setVisibility(View.VISIBLE); for (int i = 0; i < speedtexts.length; i++) { speedtexts[i].setVisibility(View.VISIBLE); } } break; default: break; } mBitmapSegmentsOverlay.setTrackColoringMethod(trackColoringMethod, mAverageSpeed, mAverageHeight); } private void updateSpeedDisplayVisibility() { boolean showspeed = mSharedPreferences.getBoolean(Constants.SPEED, false); TextView lastGPSSpeedView = mLoggerMap.getSpeedTextView(); if (showspeed) { lastGPSSpeedView.setVisibility(View.VISIBLE); } else { lastGPSSpeedView.setVisibility(View.GONE); } updateScaleDisplayVisibility(); } private void updateAltitudeDisplayVisibility() { boolean showaltitude = mSharedPreferences.getBoolean(Constants.ALTITUDE, false); TextView lastGPSAltitudeView = mLoggerMap.getAltitideTextView(); if (showaltitude) { lastGPSAltitudeView.setVisibility(View.VISIBLE); } else { lastGPSAltitudeView.setVisibility(View.GONE); } updateScaleDisplayVisibility(); } private void updateScaleDisplayVisibility() { SlidingIndicatorView scaleIndicator = mLoggerMap.getScaleIndicatorView(); boolean showspeed = mSharedPreferences.getBoolean(Constants.SPEED, false); boolean showaltitude = mSharedPreferences.getBoolean(Constants.ALTITUDE, false); int trackColoringMethod = Integer.valueOf(mSharedPreferences.getString(Constants.TRACKCOLORING, "3")).intValue(); switch (trackColoringMethod) { case SegmentRendering.DRAW_MEASURED: case SegmentRendering.DRAW_CALCULATED: if( showspeed ) { scaleIndicator.setVisibility(View.VISIBLE); } else { scaleIndicator.setVisibility(View.GONE); } break; case SegmentRendering.DRAW_HEIGHT: default: if( showaltitude ) { scaleIndicator.setVisibility(View.VISIBLE); } else { scaleIndicator.setVisibility(View.GONE); } break; } } private void updateDistanceDisplayVisibility() { boolean showdistance = mSharedPreferences.getBoolean(Constants.DISTANCE, false); TextView distanceView = mLoggerMap.getDistanceTextView(); if (showdistance) { distanceView.setVisibility(View.VISIBLE); } else { distanceView.setVisibility(View.GONE); } } private void updateCompassDisplayVisibility() { boolean compass = mSharedPreferences.getBoolean(Constants.COMPASS, false); if (compass) { mLoggerMap.enableCompass(); } else { mLoggerMap.disableCompass(); } } private void updateLocationDisplayVisibility() { boolean location = mSharedPreferences.getBoolean(Constants.LOCATION, false); if (location) { mLoggerMap.enableMyLocation(); } else { mLoggerMap.disableMyLocation(); } } /** * Retrieves the numbers of the measured speed and altitude from the most * recent waypoint and updates UI components with this latest bit of * information. */ private void updateTrackNumbers() { Location lastWaypoint = mLoggerServiceManager.getLastWaypoint(); UnitsI18n units = mUnits; if (lastWaypoint != null && units != null) { // Speed number mSpeed = lastWaypoint.getSpeed(); mAltitude = lastWaypoint.getAltitude(); mDistance = mLoggerServiceManager.getTrackedDistance(); } //Distance number double distance = units.conversionFromMeter(mDistance); String distanceText = String.format("%.2f %s", distance, units.getDistanceUnit()); TextView mDistanceView = mLoggerMap.getDistanceTextView(); mDistanceView.setText(distanceText); //Speed number double speed = units.conversionFromMetersPerSecond(mSpeed); String speedText = units.formatSpeed(speed, false); TextView lastGPSSpeedView = mLoggerMap.getSpeedTextView(); lastGPSSpeedView.setText(speedText); //Altitude number double altitude = units.conversionFromMeterToHeight(mAltitude); String altitudeText = String.format("%.0f %s", altitude, units.getHeightUnit()); TextView mLastGPSAltitudeView = mLoggerMap.getAltitideTextView(); mLastGPSAltitudeView.setText(altitudeText); // Slider indicator SlidingIndicatorView currentScaleIndicator = mLoggerMap.getScaleIndicatorView(); int trackColoringMethod = Integer.valueOf(mSharedPreferences.getString(Constants.TRACKCOLORING, "3")).intValue(); if( trackColoringMethod == SegmentRendering.DRAW_MEASURED || trackColoringMethod == SegmentRendering.DRAW_CALCULATED) { currentScaleIndicator.setValue((float) speed); // Speed color bar and reference numbers if (speed > 2 * mAverageSpeed ) { mAverageSpeed = 0.0; updateSpeedColoring(); mBitmapSegmentsOverlay.scheduleRecalculation(); } } else if(trackColoringMethod == SegmentRendering.DRAW_HEIGHT) { currentScaleIndicator.setValue((float) altitude); // Speed color bar and reference numbers if (altitude > 2 * mAverageHeight ) { mAverageHeight = 0.0; updateSpeedColoring(); mLoggerMap.postInvalidate(); } } } /** * For the current track identifier the route of that track is drawn by * adding a OverLay for each segments in the track * * @param trackId * @see SegmentRendering */ private void createDataOverlays() { mLastSegmentOverlay = null; mBitmapSegmentsOverlay.clearSegments(); mLoggerMap.clearOverlays(); mLoggerMap.addOverlay(mBitmapSegmentsOverlay); ContentResolver resolver = mLoggerMap.getActivity().getContentResolver(); Cursor segments = null; int trackColoringMethod = Integer.valueOf(mSharedPreferences.getString(Constants.TRACKCOLORING, "2")).intValue(); try { Uri segmentsUri = Uri.withAppendedPath(Tracks.CONTENT_URI, this.mTrackId + "/segments"); segments = resolver.query(segmentsUri, new String[] { Segments._ID }, null, null, null); if (segments != null && segments.moveToFirst()) { do { long segmentsId = segments.getLong(0); Uri segmentUri = ContentUris.withAppendedId(segmentsUri, segmentsId); SegmentRendering segmentOverlay = new SegmentRendering(mLoggerMap, segmentUri, trackColoringMethod, mAverageSpeed, mAverageHeight, mHandler); mBitmapSegmentsOverlay.addSegment(segmentOverlay); mLastSegmentOverlay = segmentOverlay; if (segments.isFirst()) { segmentOverlay.addPlacement(SegmentRendering.FIRST_SEGMENT); } if (segments.isLast()) { segmentOverlay.addPlacement(SegmentRendering.LAST_SEGMENT); } mLastSegment = segmentsId; } while (segments.moveToNext()); } } finally { if (segments != null) { segments.close(); } } Uri lastSegmentUri = Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/segments/" + mLastSegment + "/waypoints"); resolver.unregisterContentObserver(this.mSegmentWaypointsObserver); resolver.registerContentObserver(lastSegmentUri, false, this.mSegmentWaypointsObserver); } private void updateDataOverlays() { ContentResolver resolver = mLoggerMap.getActivity().getContentResolver(); Uri segmentsUri = Uri.withAppendedPath(Tracks.CONTENT_URI, this.mTrackId + "/segments"); Cursor segmentsCursor = null; int segmentOverlaysCount = mBitmapSegmentsOverlay.size(); try { segmentsCursor = resolver.query(segmentsUri, new String[] { Segments._ID }, null, null, null); if (segmentsCursor != null && segmentsCursor.getCount() == segmentOverlaysCount) { // Log.d( TAG, "Alignment of segments" ); } else { createDataOverlays(); } } finally { if (segmentsCursor != null) { segmentsCursor.close(); } } } /** * Call when an overlay has recalulated and has new information to be redrawn */ private void moveActiveViewWindow() { GeoPoint lastPoint = getLastTrackPoint(); if (lastPoint != null && mLoggerServiceManager.getLoggingState() == Constants.LOGGING) { if (mLoggerMap.isOutsideScreen(lastPoint)) { mLoggerMap.clearAnimation(); mLoggerMap.setCenter(lastPoint); } else if (mLoggerMap.isNearScreenEdge(lastPoint)) { mLoggerMap.clearAnimation(); mLoggerMap.animateTo(lastPoint); } } } /** * Updates the labels next to the color bar with speeds */ private void drawSpeedTexts() { UnitsI18n units = mUnits; if (units != null) { double avgSpeed = units.conversionFromMetersPerSecond(mAverageSpeed); TextView[] mSpeedtexts = mLoggerMap.getSpeedTextViews(); SlidingIndicatorView currentScaleIndicator = mLoggerMap.getScaleIndicatorView(); for (int i = 0; i < mSpeedtexts.length; i++) { mSpeedtexts[i].setVisibility(View.VISIBLE); double speed; if (mUnits.isUnitFlipped()) { speed = ((avgSpeed * 2d) / 5d) * (mSpeedtexts.length - i - 1); } else { speed = ((avgSpeed * 2d) / 5d) * i; } if( i == 0 ) { currentScaleIndicator.setMin((float) speed); } else { currentScaleIndicator.setMax((float) speed); } String speedText = units.formatSpeed(speed, false); mSpeedtexts[i].setText(speedText); } } } /** * Updates the labels next to the color bar with heights */ private void drawHeightTexts() { UnitsI18n units = mUnits; if (units != null) { double avgHeight = units.conversionFromMeterToHeight(mAverageHeight); TextView[] mSpeedtexts = mLoggerMap.getSpeedTextViews(); SlidingIndicatorView currentScaleIndicator = mLoggerMap.getScaleIndicatorView(); for (int i = 0; i < mSpeedtexts.length; i++) { mSpeedtexts[i].setVisibility(View.VISIBLE); double height = ((avgHeight * 2d) / 5d) * i; String heightText = String.format( "%d %s", (int)height, units.getHeightUnit() ); mSpeedtexts[i].setText(heightText); if( i == 0 ) { currentScaleIndicator.setMin((float) height); } else { currentScaleIndicator.setMax((float) height); } } } } /** * Alter this to set a new track as current. * * @param trackId * @param center center on the end of the track */ private void moveToTrack(long trackId, boolean center) { if( trackId == mTrackId ) { return; } Cursor track = null; try { ContentResolver resolver = mLoggerMap.getActivity().getContentResolver(); Uri trackUri = ContentUris.withAppendedId(Tracks.CONTENT_URI, trackId); track = resolver.query(trackUri, new String[] { Tracks.NAME }, null, null, null); if (track != null && track.moveToFirst()) { this.mTrackId = trackId; mLastSegment = -1; resolver.unregisterContentObserver(this.mTrackSegmentsObserver); resolver.unregisterContentObserver(this.mTrackMediasObserver); Uri tracksegmentsUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments"); resolver.registerContentObserver(tracksegmentsUri, false, this.mTrackSegmentsObserver); resolver.registerContentObserver(Media.CONTENT_URI, true, this.mTrackMediasObserver); mLoggerMap.clearOverlays(); mBitmapSegmentsOverlay.clearSegments(); mAverageSpeed = 0.0; mAverageHeight = 0.0; updateTitleBar(); updateDataOverlays(); updateSpeedColoring(); if (center) { GeoPoint lastPoint = getLastTrackPoint(); mLoggerMap.animateTo(lastPoint); } } } finally { if (track != null) { track.close(); } } } /** * Get the last know position from the GPS provider and return that * information wrapped in a GeoPoint to which the Map can navigate. * * @see GeoPoint * @return */ private GeoPoint getLastKnowGeopointLocation() { int microLatitude = 0; int microLongitude = 0; LocationManager locationManager = (LocationManager) mLoggerMap.getActivity().getApplication().getSystemService(Context.LOCATION_SERVICE); Location locationFine = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (locationFine != null) { microLatitude = (int) (locationFine.getLatitude() * 1E6d); microLongitude = (int) (locationFine.getLongitude() * 1E6d); } if (locationFine == null || microLatitude == 0 || microLongitude == 0) { Location locationCoarse = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (locationCoarse != null) { microLatitude = (int) (locationCoarse.getLatitude() * 1E6d); microLongitude = (int) (locationCoarse.getLongitude() * 1E6d); } if (locationCoarse == null || microLatitude == 0 || microLongitude == 0) { microLatitude = 51985105; microLongitude = 5106132; } } GeoPoint geoPoint = new GeoPoint(microLatitude, microLongitude); return geoPoint; } /** * Retrieve the last point of the current track * * @param context */ private GeoPoint getLastTrackPoint() { Cursor waypoint = null; GeoPoint lastPoint = null; // First try the service which might have a cached version Location lastLoc = mLoggerServiceManager.getLastWaypoint(); if (lastLoc != null) { int microLatitude = (int) (lastLoc.getLatitude() * 1E6d); int microLongitude = (int) (lastLoc.getLongitude() * 1E6d); lastPoint = new GeoPoint(microLatitude, microLongitude); } // If nothing yet, try the content resolver and query the track if (lastPoint == null || lastPoint.getLatitudeE6() == 0 || lastPoint.getLongitudeE6() == 0) { try { ContentResolver resolver = mLoggerMap.getActivity().getContentResolver(); waypoint = resolver.query(Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/waypoints"), new String[] { Waypoints.LATITUDE, Waypoints.LONGITUDE, "max(" + Waypoints.TABLE + "." + Waypoints._ID + ")" }, null, null, null); if (waypoint != null && waypoint.moveToLast()) { int microLatitude = (int) (waypoint.getDouble(0) * 1E6d); int microLongitude = (int) (waypoint.getDouble(1) * 1E6d); lastPoint = new GeoPoint(microLatitude, microLongitude); } } finally { if (waypoint != null) { waypoint.close(); } } } // If nothing yet, try the last generally known location if (lastPoint == null || lastPoint.getLatitudeE6() == 0 || lastPoint.getLongitudeE6() == 0) { lastPoint = getLastKnowGeopointLocation(); } return lastPoint; } private void moveToLastTrack() { int trackId = -1; Cursor track = null; try { ContentResolver resolver = mLoggerMap.getActivity().getContentResolver(); track = resolver.query(Tracks.CONTENT_URI, new String[] { "max(" + Tracks._ID + ")", Tracks.NAME, }, null, null, null); if (track != null && track.moveToLast()) { trackId = track.getInt(0); moveToTrack(trackId, false); } } finally { if (track != null) { track.close(); } } } /** * Enables a SegmentOverlay to call back to the MapActivity to show a dialog * with choices of media * * @param mediaAdapter */ public void showMediaDialog(BaseAdapter mediaAdapter) { mMediaAdapter = mediaAdapter; mLoggerMap.getActivity().showDialog(DIALOG_URIS); } public SharedPreferences getPreferences() { return mSharedPreferences; } public boolean isLogging() { return mLoggerServiceManager.getLoggingState() == Constants.LOGGING; } }
Java
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Feb 26, 2012 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ */ package nl.sogeti.android.gpstracker.viewer.map; import nl.sogeti.android.gpstracker.util.Constants; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; /** * ???? * * @version $Id:$ * @author rene (c) Feb 26, 2012, Sogeti B.V. */ public class CommonLoggerMap extends Activity { private static final String TAG = "OGT.CommonLoggerMap"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent myIntent = getIntent(); Intent realIntent; Class<?> mapClass = GoogleLoggerMap.class; int provider = Integer.valueOf(PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.MAPPROVIDER, "" + Constants.GOOGLE)).intValue(); switch (provider) { case Constants.GOOGLE: mapClass = GoogleLoggerMap.class; break; case Constants.OSM: mapClass = OsmLoggerMap.class; break; case Constants.MAPQUEST: mapClass = MapQuestLoggerMap.class; break; default: mapClass = GoogleLoggerMap.class; Log.e(TAG, "Fault in value " + provider + " as MapProvider, defaulting to Google Maps."); break; } if( myIntent != null ) { realIntent = new Intent(myIntent.getAction(), myIntent.getData(), this, mapClass); realIntent.putExtras(myIntent); } else { realIntent = new Intent(this, mapClass); realIntent.putExtras(myIntent); } startActivity(realIntent); finish(); } }
Java
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Feb 26, 2012 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ */ package nl.sogeti.android.gpstracker.viewer.map; import nl.sogeti.android.gpstracker.util.SlidingIndicatorView; import nl.sogeti.android.gpstracker.viewer.map.overlay.OverlayProvider; import android.app.Activity; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.Point; import android.widget.BaseAdapter; import android.widget.TextView; import com.google.android.maps.GeoPoint; /** * ???? * * @version $Id$ * @author rene (c) Feb 26, 2012, Sogeti B.V. */ public interface LoggerMap { void setDrawingCacheEnabled(boolean b); Activity getActivity(); void updateOverlays(); void onLayerCheckedChanged(int checkedId, boolean b); void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key); Bitmap getDrawingCache(); void showMediaDialog(BaseAdapter mediaAdapter); String getDataSourceId(); boolean isOutsideScreen(GeoPoint lastPoint); boolean isNearScreenEdge(GeoPoint lastPoint); void executePostponedActions(); void disableMyLocation(); void disableCompass(); void setZoom(int int1); void animateTo(GeoPoint storedPoint); int getZoomLevel(); GeoPoint getMapCenter(); boolean zoomOut(); boolean zoomIn(); void postInvalidate(); void enableCompass(); void enableMyLocation(); void addOverlay(OverlayProvider overlay); void clearAnimation(); void setCenter(GeoPoint lastPoint); int getMaxZoomLevel(); GeoPoint fromPixels(int x, int y); boolean hasProjection(); float metersToEquatorPixels(float float1); void toPixels(GeoPoint geopoint, Point screenPoint); TextView[] getSpeedTextViews(); TextView getAltitideTextView(); TextView getSpeedTextView(); TextView getDistanceTextView(); void clearOverlays(); SlidingIndicatorView getScaleIndicatorView(); }
Java
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Mar 3, 2012 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ */ package nl.sogeti.android.gpstracker.viewer.map; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.util.SlidingIndicatorView; import nl.sogeti.android.gpstracker.viewer.map.overlay.OverlayProvider; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.Point; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.widget.BaseAdapter; import android.widget.TextView; import com.google.android.maps.GeoPoint; import com.mapquest.android.maps.MapActivity; import com.mapquest.android.maps.MapView; import com.mapquest.android.maps.MyLocationOverlay; /** * ???? * * @version $Id:$ * @author rene (c) Mar 3, 2012, Sogeti B.V. */ public class MapQuestLoggerMap extends MapActivity implements LoggerMap { LoggerMapHelper mHelper; private MapView mMapView; private TextView[] mSpeedtexts; private TextView mLastGPSSpeedView; private TextView mLastGPSAltitudeView; private TextView mDistanceView; private MyLocationOverlay mMylocation; /** * Called when the activity is first created. */ @Override protected void onCreate(Bundle load) { super.onCreate(load); setContentView(R.layout.map_mapquest); mMapView = (MapView) findViewById(R.id.myMapView); mHelper = new LoggerMapHelper(this); mMapView = (MapView) findViewById(R.id.myMapView); mMylocation = new MyLocationOverlay(this, mMapView); mMapView.setBuiltInZoomControls(true); TextView[] speeds = { (TextView) findViewById(R.id.speedview05), (TextView) findViewById(R.id.speedview04), (TextView) findViewById(R.id.speedview03), (TextView) findViewById(R.id.speedview02), (TextView) findViewById(R.id.speedview01), (TextView) findViewById(R.id.speedview00) }; mSpeedtexts = speeds; mLastGPSSpeedView = (TextView) findViewById(R.id.currentSpeed); mLastGPSAltitudeView = (TextView) findViewById(R.id.currentAltitude); mDistanceView = (TextView) findViewById(R.id.currentDistance); mHelper.onCreate(load); } @Override protected void onResume() { super.onResume(); mHelper.onResume(); } @Override protected void onPause() { mHelper.onPause(); super.onPause(); } @Override protected void onDestroy() { mHelper.onDestroy(); super.onDestroy(); } @Override public void onNewIntent(Intent newIntent) { mHelper.onNewIntent(newIntent); } @Override protected void onRestoreInstanceState(Bundle load) { if (load != null) { super.onRestoreInstanceState(load); } mHelper.onRestoreInstanceState(load); } @Override protected void onSaveInstanceState(Bundle save) { super.onSaveInstanceState(save); mHelper.onSaveInstanceState(save); } @Override public boolean onCreateOptionsMenu(Menu menu) { boolean result = super.onCreateOptionsMenu(menu); mHelper.onCreateOptionsMenu(menu); return result; } @Override public boolean onPrepareOptionsMenu(Menu menu) { mHelper.onPrepareOptionsMenu(menu); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { boolean handled = mHelper.onOptionsItemSelected(item); if( !handled ) { handled = super.onOptionsItemSelected(item); } return handled; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); mHelper.onActivityResult(requestCode, resultCode, intent); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { boolean propagate = true; switch (keyCode) { default: propagate = mHelper.onKeyDown(keyCode, event); if( propagate ) { propagate = super.onKeyDown(keyCode, event); } break; } return propagate; } @Override protected Dialog onCreateDialog(int id) { Dialog dialog = mHelper.onCreateDialog(id); if( dialog == null ) { dialog = super.onCreateDialog(id); } return dialog; } @Override protected void onPrepareDialog(int id, Dialog dialog) { mHelper.onPrepareDialog(id, dialog); super.onPrepareDialog(id, dialog); } /******************************/ /** Loggermap methods **/ /******************************/ @Override public void updateOverlays() { } @Override public void setDrawingCacheEnabled(boolean b) { findViewById(R.id.mapScreen).setDrawingCacheEnabled(true); } @Override public Activity getActivity() { return this; } @Override public void onLayerCheckedChanged(int checkedId, boolean isChecked) { } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { } @Override public Bitmap getDrawingCache() { return findViewById(R.id.mapScreen).getDrawingCache(); } @Override public void showMediaDialog(BaseAdapter mediaAdapter) { mHelper.showMediaDialog(mediaAdapter); } public void onDateOverlayChanged() { mMapView.postInvalidate(); } @Override public String getDataSourceId() { return LoggerMapHelper.MAPQUEST_PROVIDER; } @Override public boolean isOutsideScreen(GeoPoint lastPoint) { Point out = new Point(); this.mMapView.getProjection().toPixels(MapQuestLoggerMap.convertGeoPoint(lastPoint), out); int height = this.mMapView.getHeight(); int width = this.mMapView.getWidth(); return (out.x < 0 || out.y < 0 || out.y > height || out.x > width); } @Override public boolean isNearScreenEdge(GeoPoint lastPoint) { Point out = new Point(); this.mMapView.getProjection().toPixels(MapQuestLoggerMap.convertGeoPoint(lastPoint), out); int height = this.mMapView.getHeight(); int width = this.mMapView.getWidth(); return (out.x < width / 4 || out.y < height / 4 || out.x > (width / 4) * 3 || out.y > (height / 4) * 3); } @Override public void executePostponedActions() { } @Override public void enableCompass() { mMylocation.enableCompass(); } @Override public void enableMyLocation() { mMylocation.enableMyLocation(); } @Override public void disableMyLocation() { mMylocation.disableMyLocation(); } @Override public void disableCompass() { mMylocation.disableCompass(); } @Override public void setZoom(int zoom) { mMapView.getController().setZoom(zoom); } @Override public void animateTo(GeoPoint storedPoint) { mMapView.getController().animateTo(MapQuestLoggerMap.convertGeoPoint(storedPoint)); } @Override public int getZoomLevel() { return mMapView.getZoomLevel(); } @Override public GeoPoint getMapCenter() { return MapQuestLoggerMap.convertMapQuestGeoPoint(mMapView.getMapCenter()); } @Override public boolean zoomOut() { return mMapView.getController().zoomOut(); } @Override public boolean zoomIn() { return mMapView.getController().zoomIn(); } @Override public void postInvalidate() { mMapView.postInvalidate(); } @Override public void addOverlay(OverlayProvider overlay) { mMapView.getOverlays().add(overlay.getMapQuestOverlay()); } @Override public void clearAnimation() { mMapView.clearAnimation(); } @Override public void setCenter(GeoPoint lastPoint) { mMapView.getController().setCenter( MapQuestLoggerMap.convertGeoPoint(lastPoint)); } @Override public int getMaxZoomLevel() { return mMapView.getMaxZoomLevel(); } @Override public GeoPoint fromPixels(int x, int y) { com.mapquest.android.maps.GeoPoint mqGeopoint = mMapView.getProjection().fromPixels(x, y); return convertMapQuestGeoPoint(mqGeopoint); } @Override public boolean hasProjection() { return mMapView.getProjection() != null; } @Override public float metersToEquatorPixels(float float1) { return mMapView.getProjection().metersToEquatorPixels(float1); } @Override public void toPixels(GeoPoint geoPoint, Point screenPoint) { com.mapquest.android.maps.GeoPoint mqGeopoint = MapQuestLoggerMap.convertGeoPoint(geoPoint); mMapView.getProjection().toPixels( mqGeopoint, screenPoint); } @Override public TextView[] getSpeedTextViews() { return mSpeedtexts; } @Override public TextView getAltitideTextView() { return mLastGPSAltitudeView; } @Override public TextView getSpeedTextView() { return mLastGPSSpeedView; } @Override public TextView getDistanceTextView() { return mDistanceView; } static com.mapquest.android.maps.GeoPoint convertGeoPoint( GeoPoint point ) { return new com.mapquest.android.maps.GeoPoint(point.getLatitudeE6(), point.getLongitudeE6() ); } static GeoPoint convertMapQuestGeoPoint( com.mapquest.android.maps.GeoPoint mqPoint ) { return new GeoPoint(mqPoint.getLatitudeE6(), mqPoint.getLongitudeE6() ); } @Override public void clearOverlays() { mMapView.getOverlays().clear(); } @Override public SlidingIndicatorView getScaleIndicatorView() { return (SlidingIndicatorView) findViewById(R.id.scaleindicator); } /******************************/ /** Own methods **/ /******************************/ @Override public boolean isRouteDisplayed() { return true; } }
Java
/* * Written by Pieter @ android-developers on groups.google.com * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.viewer.map.overlay; import nl.sogeti.android.gpstracker.R; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Point; import android.graphics.drawable.Drawable; import android.location.Location; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.Projection; /** * Fix for a ClassCastException found on some Google Maps API's implementations. * @see <a href="http://www.spectrekking.com/download/FixedMyLocationOverlay.java">www.spectrekking.com</a> * @version $Id$ */ public class FixedMyLocationOverlay extends MyLocationOverlay { private boolean bugged = false; private Paint accuracyPaint; private Point center; private Point left; private Drawable drawable; private int width; private int height; public FixedMyLocationOverlay(Context context, MapView mapView) { super(context, mapView); } @Override protected void drawMyLocation(Canvas canvas, MapView mapView, Location lastFix, GeoPoint myLoc, long when) { if (!bugged) { try { super.drawMyLocation(canvas, mapView, lastFix, myLoc, when); } catch (Exception e) { bugged = true; } } if (bugged) { if (drawable == null) { if( accuracyPaint == null ) { accuracyPaint = new Paint(); accuracyPaint.setAntiAlias(true); accuracyPaint.setStrokeWidth(2.0f); } drawable = mapView.getContext().getResources().getDrawable(R.drawable.mylocation); width = drawable.getIntrinsicWidth(); height = drawable.getIntrinsicHeight(); center = new Point(); left = new Point(); } Projection projection = mapView.getProjection(); double latitude = lastFix.getLatitude(); double longitude = lastFix.getLongitude(); float accuracy = lastFix.getAccuracy(); float[] result = new float[1]; Location.distanceBetween(latitude, longitude, latitude, longitude + 1, result); float longitudeLineDistance = result[0]; GeoPoint leftGeo = new GeoPoint((int)(latitude*1e6), (int)((longitude-accuracy/longitudeLineDistance)*1e6)); projection.toPixels(leftGeo, left); projection.toPixels(myLoc, center); int radius = center.x - left.x; accuracyPaint.setColor(0xff6666ff); accuracyPaint.setStyle(Style.STROKE); canvas.drawCircle(center.x, center.y, radius, accuracyPaint); accuracyPaint.setColor(0x186666ff); accuracyPaint.setStyle(Style.FILL); canvas.drawCircle(center.x, center.y, radius, accuracyPaint); drawable.setBounds(center.x - width / 2, center.y - height / 2, center.x + width / 2, center.y + height / 2); drawable.draw(canvas); } } }
Java
package nl.sogeti.android.gpstracker.viewer.map.overlay; import nl.sogeti.android.gpstracker.viewer.map.LoggerMap; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.os.Handler; import android.util.Log; import android.view.MotionEvent; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.Overlay; public abstract class AsyncOverlay extends Overlay implements OverlayProvider { private static final int OFFSET = 20; private static final String TAG = "GG.AsyncOverlay"; /** * Handler provided by the MapActivity to recalculate graphics */ private Handler mHandler; private GeoPoint mGeoTopLeft; private GeoPoint mGeoBottumRight; private int mWidth; private int mHeight; private Bitmap mActiveBitmap; private GeoPoint mActiveTopLeft; private Point mActivePointTopLeft; private Bitmap mCalculationBitmap; private Paint mPaint; private LoggerMap mLoggerMap; SegmentOsmOverlay mOsmOverlay; private SegmentMapQuestOverlay mMapQuestOverlay; private int mActiveZoomLevel; private Runnable mBitmapUpdater = new Runnable() { @Override public void run() { postedBitmapUpdater = false; mCalculationBitmap.eraseColor(Color.TRANSPARENT); mGeoTopLeft = mLoggerMap.fromPixels(0, 0); mGeoBottumRight = mLoggerMap.fromPixels(mWidth, mHeight); Canvas calculationCanvas = new Canvas(mCalculationBitmap); redrawOffscreen(calculationCanvas, mLoggerMap); synchronized (mActiveBitmap) { Bitmap oldActiveBitmap = mActiveBitmap; mActiveBitmap = mCalculationBitmap; mActiveTopLeft = mGeoTopLeft; mCalculationBitmap = oldActiveBitmap; } mLoggerMap.postInvalidate(); } }; private boolean postedBitmapUpdater; AsyncOverlay(LoggerMap loggermap, Handler handler) { mLoggerMap = loggermap; mHandler = handler; mWidth = 1; mHeight = 1; mPaint = new Paint(); mActiveZoomLevel = -1; mActiveBitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888); mActiveTopLeft = new GeoPoint(0, 0); mActivePointTopLeft = new Point(); mCalculationBitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888); mOsmOverlay = new SegmentOsmOverlay(mLoggerMap.getActivity(), mLoggerMap, this); mMapQuestOverlay = new SegmentMapQuestOverlay(this); } protected void reset() { synchronized (mActiveBitmap) { mCalculationBitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); mActiveBitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); } } protected void considerRedrawOffscreen() { int oldZoomLevel = mActiveZoomLevel; mActiveZoomLevel = mLoggerMap.getZoomLevel(); boolean needNewCalculation = false; if (mCalculationBitmap.getWidth() != mWidth || mCalculationBitmap.getHeight() != mHeight) { mCalculationBitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888); needNewCalculation = true; } boolean unaligned = isOutAlignment(); if (needNewCalculation || mActiveZoomLevel != oldZoomLevel || unaligned) { scheduleRecalculation(); } } private boolean isOutAlignment() { Point screenPoint = new Point(0, 0); if (mGeoTopLeft != null) { mLoggerMap.toPixels(mGeoTopLeft, screenPoint); } return mGeoTopLeft == null || mGeoBottumRight == null || screenPoint.x > OFFSET || screenPoint.y > OFFSET || screenPoint.x < -OFFSET || screenPoint.y < -OFFSET; } public void onDateOverlayChanged() { if (!postedBitmapUpdater) { postedBitmapUpdater = true; mHandler.post(mBitmapUpdater); } } protected abstract void redrawOffscreen(Canvas asyncBuffer, LoggerMap loggermap); protected abstract void scheduleRecalculation(); /** * {@inheritDoc} */ @Override public void draw(Canvas canvas, MapView mapView, boolean shadow) { if (!shadow) { draw(canvas); } } private void draw(Canvas canvas) { mWidth = canvas.getWidth(); mHeight = canvas.getHeight(); considerRedrawOffscreen(); if (mActiveBitmap.getWidth() > 1) { synchronized (mActiveBitmap) { mLoggerMap.toPixels(mActiveTopLeft, mActivePointTopLeft); canvas.drawBitmap(mActiveBitmap, mActivePointTopLeft.x, mActivePointTopLeft.y, mPaint); } } } protected boolean isPointOnScreen(Point point) { return point.x < 0 || point.y < 0 || point.x > mWidth || point.y > mHeight; } @Override public boolean onTap(GeoPoint tappedGeoPoint, MapView mapview) { return commonOnTap(tappedGeoPoint); } /**************************************/ /** Multi map support **/ /**************************************/ @Override public Overlay getGoogleOverlay() { return this; } @Override public org.osmdroid.views.overlay.Overlay getOSMOverlay() { return mOsmOverlay; } @Override public com.mapquest.android.maps.Overlay getMapQuestOverlay() { return mMapQuestOverlay; } protected abstract boolean commonOnTap(GeoPoint tappedGeoPoint); static class SegmentOsmOverlay extends org.osmdroid.views.overlay.Overlay { AsyncOverlay mSegmentOverlay; LoggerMap mLoggerMap; public SegmentOsmOverlay(Context ctx, LoggerMap map, AsyncOverlay segmentOverlay) { super(ctx); mLoggerMap = map; mSegmentOverlay = segmentOverlay; } public AsyncOverlay getSegmentOverlay() { return mSegmentOverlay; } @Override public boolean onSingleTapUp(MotionEvent e, org.osmdroid.views.MapView openStreetMapView) { int x = (int) e.getX(); int y = (int) e.getY(); GeoPoint tappedGeoPoint = mLoggerMap.fromPixels(x, y); return mSegmentOverlay.commonOnTap(tappedGeoPoint); } @Override protected void draw(Canvas canvas, org.osmdroid.views.MapView view, boolean shadow) { if (!shadow) { mSegmentOverlay.draw(canvas); } } } static class SegmentMapQuestOverlay extends com.mapquest.android.maps.Overlay { AsyncOverlay mSegmentOverlay; public SegmentMapQuestOverlay(AsyncOverlay segmentOverlay) { super(); mSegmentOverlay = segmentOverlay; } public AsyncOverlay getSegmentOverlay() { return mSegmentOverlay; } @Override public boolean onTap(com.mapquest.android.maps.GeoPoint p, com.mapquest.android.maps.MapView mapView) { GeoPoint tappedGeoPoint = new GeoPoint(p.getLatitudeE6(), p.getLongitudeE6()); return mSegmentOverlay.commonOnTap(tappedGeoPoint); } @Override public void draw(Canvas canvas, com.mapquest.android.maps.MapView mapView, boolean shadow) { if (!shadow) { mSegmentOverlay.draw(canvas); } } } }
Java
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.viewer.map.overlay; import com.mapquest.android.maps.Overlay; public interface OverlayProvider { public com.google.android.maps.Overlay getGoogleOverlay(); public org.osmdroid.views.overlay.Overlay getOSMOverlay(); public Overlay getMapQuestOverlay(); }
Java