基于android端计步器软件的尝试

来源:互联网 发布:基本款 外套 知乎 编辑:程序博客网 时间:2024/06/06 02:54

这学期选了一门java课,然而课已经上完了还是对java一知半解,只能通过大作业来实践一下了。这次要做的是一个计步器软件,最初的目标是想实现记录步数并且显示走过路程,并能与朋友圈好友比较走过步数的功能,其实和微信运动的那个东西的目标是一样的。但是在实现过程中确实遇到了许多的问题,导致功能有些缩水。计步功能:这其实是一个数学问题,套用不同的公式计步的准确程度真的查了特别多

计步功能:

package com.example.test1207;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.hardware.Sensor;import android.hardware.SensorEvent;import android.hardware.SensorEventListener;import android.hardware.SensorManager;import android.app.Activity;import android.content.Context;import android.util.Log;import android.widget.TextView;import java.text.DateFormat;import java.text.ParsePosition;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;//import com.baidu.mapapi.SDKInitializer;//import com.baidu.mapapi.map.MapView;//import com.example.baidumap.R; //import com.example.baidumap.R;import android.view.Window;    import android.content.Context;import android.hardware.Sensor;import android.hardware.SensorEvent;import android.hardware.SensorEventListener;import android.hardware.SensorManager;import android.util.Log;public class MainActivity implements SensorEventListener {<span style="white-space:pre"></span>public static int CURRENT_SETP = 0;<span style="white-space:pre"></span>public static float SENSITIVITY = 0;   //SENSITIVITY灵敏度<span style="white-space:pre"></span>private float mLastValues[] = new float[3 * 2];<span style="white-space:pre"></span>private float mScale[] = new float[2];<span style="white-space:pre"></span>private float mYOffset;<span style="white-space:pre"></span>private static long end = 0;<span style="white-space:pre"></span>private static long start = 0;<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * 最后加速度方向<span style="white-space:pre"></span> */<span style="white-space:pre"></span>private float mLastDirections[] = new float[3 * 2];<span style="white-space:pre"></span>private float mLastExtremes[][] = { new float[3 * 2], new float[3 * 2] };<span style="white-space:pre"></span>private float mLastDiff[] = new float[3 * 2];<span style="white-space:pre"></span>private int mLastMatch = -1;<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * 传入上下文的构造函数<span style="white-space:pre"></span> * <span style="white-space:pre"></span> * @param context<span style="white-space:pre"></span> */<span style="white-space:pre"></span>public MainActivity(Context context) {<span style="white-space:pre"></span>// TODO Auto-generated constructor stub<span style="white-space:pre"></span>super();<span style="white-space:pre"></span>int h = 480;<span style="white-space:pre"></span>mYOffset = h * 0.5f;<span style="white-space:pre"></span>mScale[0] = -(h * 0.5f * (1.0f / (SensorManager.STANDARD_GRAVITY * 2)));<span style="white-space:pre"></span>mScale[1] = -(h * 0.5f * (1.0f / (SensorManager.MAGNETIC_FIELD_EARTH_MAX)));/*<span style="white-space:pre"></span>if (SettingsActivity.sharedPreferences == null) {<span style="white-space:pre"></span>SettingsActivity.sharedPreferences = context.getSharedPreferences(<span style="white-space:pre"></span>SettingsActivity.SETP_SHARED_PREFERENCES,<span style="white-space:pre"></span>Context.MODE_PRIVATE);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>SENSITIVITY = SettingsActivity.sharedPreferences.getInt(<span style="white-space:pre"></span>SettingsActivity.SENSITIVITY_VALUE, 3);*/<span style="white-space:pre"></span>}<span style="white-space:pre"></span>// public void setSensitivity(float sensitivity) {<span style="white-space:pre"></span>// SENSITIVITY = sensitivity; // 1.97 2.96 4.44 6.66 10.00 15.00 22.50<span style="white-space:pre"></span>// // 33.75<span style="white-space:pre"></span>// // 50.62<span style="white-space:pre"></span>// }<span style="white-space:pre"></span>// public void onSensorChanged(int sensor, float[] values) {<span style="white-space:pre"></span>@Override<span style="white-space:pre"></span>public void onSensorChanged(SensorEvent event) {<span style="white-space:pre"></span>// Log.i(Constant.STEP_SERVER, "StepDetector");<span style="white-space:pre"></span>Sensor sensor = event.sensor;<span style="white-space:pre"></span>// Log.i(Constant.STEP_DETECTOR, "onSensorChanged");<span style="white-space:pre"></span>synchronized (this) {<span style="white-space:pre"></span>if (sensor.getType() == Sensor.TYPE_ORIENTATION) {<span style="white-space:pre"></span>} else {<span style="white-space:pre"></span>int j = (sensor.getType() == Sensor.TYPE_ACCELEROMETER) ? 1 : 0;<span style="white-space:pre"></span>if (j == 1) {<span style="white-space:pre"></span>float vSum = 0;<span style="white-space:pre"></span>for (int i = 0; i < 3; i++) {<span style="white-space:pre"></span>final float v = mYOffset + event.values[i] * mScale[j];<span style="white-space:pre"></span>vSum += v;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>int k = 0;<span style="white-space:pre"></span>float v = vSum / 3;<span style="white-space:pre"></span>float direction = (v > mLastValues[k] ? 1: (v < mLastValues[k] ? -1 : 0));<span style="white-space:pre"></span>if (direction == -mLastDirections[k]) {<span style="white-space:pre"></span>// Direction changed<span style="white-space:pre"></span>int extType = (direction > 0 ? 0 : 1); // minumum or<span style="white-space:pre"></span>// maximum?<span style="white-space:pre"></span>mLastExtremes[extType][k] = mLastValues[k];<span style="white-space:pre"></span>float diff = Math.abs(mLastExtremes[extType][k]- mLastExtremes[1 - extType][k]);<span style="white-space:pre"></span>if (diff > SENSITIVITY) {<span style="white-space:pre"></span>boolean isAlmostAsLargeAsPrevious = diff > (mLastDiff[k] * 2 / 3);<span style="white-space:pre"></span>boolean isPreviousLargeEnough = mLastDiff[k] > (diff / 3);<span style="white-space:pre"></span>boolean isNotContra = (mLastMatch != 1 - extType);<span style="white-space:pre"></span>if (isAlmostAsLargeAsPrevious && isPreviousLargeEnough && isNotContra) {<span style="white-space:pre"></span>end = System.currentTimeMillis();<span style="white-space:pre"></span>if (end - start > 500) {// 此时判断为走了一步<span style="white-space:pre"></span>Log.i("StepDetector", "CURRENT_SETP:"<span style="white-space:pre"></span>+ CURRENT_SETP);<span style="white-space:pre"></span>CURRENT_SETP++;<span style="white-space:pre"></span>mLastMatch = extType;<span style="white-space:pre"></span>start = end;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>} else {<span style="white-space:pre"></span>mLastMatch = -1;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>mLastDiff[k] = diff;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>mLastDirections[k] = direction;<span style="white-space:pre"></span>mLastValues[k] = v;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>@Override<span style="white-space:pre"></span>public void onAccuracyChanged(Sensor sensor, int accuracy) {<span style="white-space:pre"></span>// TODO Auto-generated method stub<span style="white-space:pre"></span>}}
这段主要是参考了一下计步函数写出来的,重力传感器测出了x,y,z三个方向的加速度,可以网上先下载一个软件来观察一下走路时的加速度的变化曲线。我设定的可以判断为走了一步的依据是当加速的波峰波谷连续出现两次并大于设定的阈值时认为走了一步,并且出现波动的时间不超过0.2秒,因为人的走路速度不会这么快,这样排除了干扰。当然现在这个的准确程度还有待提高,并不能准确测出步数,还需要再调试一下。

记录走过路程功能:

这段其实主要依靠的是百度地图的api接口实现的。本来没有发现百度地图的鹰眼demo在自己记录走过的位置的经度纬度,记录下来,并把所有的点连城线来记录路程,百度地图的画图功能用起来好麻烦啊…………。但是有一天突然发现百度地图有这个功能………………而且比我自己写的准确了不少,于是就直接调用了,主要用了百度鹰眼demo的记录路线功能和存储路线的功能。

这里说一下百度地图的sdk下载下来再用百度给的示例代码是有问题的,虽然我并没有找出问题在哪里,但是倒是可以在百度地图的demo里自己修改,方便了很多,不需要考虑用到的package了。

package com.baidu.trackshow;import com.baidu.mapapi.SDKInitializer;import com.baidu.mapapi.map.BaiduMap;import com.baidu.mapapi.map.MapView;import com.baidu.trackshow.R;import com.baidu.trace.LBSTraceClient;import com.baidu.trace.OnEntityListener;import com.baidu.trace.Trace;import android.content.Intent;import android.content.IntentFilter;import android.annotation.SuppressLint;import android.app.FragmentManager;import android.app.FragmentTransaction;import android.content.Context;import android.graphics.Color;import android.os.Bundle;import android.os.Looper;import android.support.v4.app.FragmentActivity;import android.telephony.TelephonyManager;import android.view.View;import android.view.View.OnClickListener;import android.view.Window;import android.widget.Button;import android.widget.Toast;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.hardware.Sensor;import android.hardware.SensorEvent;import android.hardware.SensorEventListener;import android.hardware.SensorManager;import android.app.Activity;import android.content.Context;import android.util.Log;import android.widget.TextView;import java.text.DateFormat;import java.text.ParsePosition;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;import com.baidu.mapapi.SDKInitializer;import com.baidu.mapapi.map.MapView;@SuppressLint("NewApi")public class MainActivity extends FragmentActivity implements OnClickListener,SensorEventListener{    /**     * 轨迹服务     */    protected static Trace trace = null;    /**     * entity标识     */    protected static String entityName = null;    /**     * 鹰眼服务ID,开发者创建的鹰眼服务对应的服务ID     */    protected static long serviceId = 104296; // serviceId为开发者创建的鹰眼服务ID    /**     * 轨迹服务类型(0 : 不建立socket长连接, 1 : 建立socket长连接但不上传位置数据,2 : 建立socket长连接并上传位置数据)     */    private int traceType = 2;    /**     * 轨迹服务客户端     */    protected static LBSTraceClient client = null;    /**     * Entity监听器     */    protected static OnEntityListener entityListener = null;    private Button btnTrackUpload;    private Button btnTrackQuery;    protected static MapView bmapView = null;    protected static BaiduMap mBaiduMap = null;    /**     * 用于对Fragment进行管理     */    private FragmentManager fragmentManager;    private TrackUploadFragment mTrackUploadFragment;    private TrackQueryFragment mTrackQueryFragment;            private static final String TAG = MainActivity.class.getSimpleName();<span style="white-space:pre"></span>private SensorManager mSensorManager;<span style="white-space:pre"></span>private Sensor mSensor;<span style="white-space:pre"></span>private TextView textviewX;<span style="white-space:pre"></span>private TextView textviewY;<span style="white-space:pre"></span>private TextView textviewZ;<span style="white-space:pre"></span>private TextView textviewF;<span style="white-space:pre"></span>private TextView textviewS;<span style="white-space:pre"></span>private TextView textview1;<span style="white-space:pre"></span>private TextView textview2;<span style="white-space:pre"></span>private TextView textview3;<span style="white-space:pre"></span><span style="white-space:pre"></span>private int mX, mY, mZ;<span style="white-space:pre"></span>private long lasttimestamp = 0;<span style="white-space:pre"></span>Calendar mCalendar;<span style="white-space:pre"></span>int s = 0;<span style="white-space:pre"></span>int lastX = 0,lastY = 0,lastZ = 0;<span style="white-space:pre"></span>float cal;<span style="white-space:pre"></span>float precal;<span style="white-space:pre"></span>float minnum;<span style="white-space:pre"></span>int lastnum = 0;<span style="white-space:pre"></span>float top,buttom;<span style="white-space:pre"></span>int prelastnum = 0;<span style="white-space:pre"></span>int preup=0;<span style="white-space:pre"></span>int predown=0;    protected static Context mContext = null;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        SDKInitializer.initialize(getApplicationContext());        requestWindowFeature(Window.FEATURE_NO_TITLE);        setContentView(R.layout.activity_main);                  /*      textviewX = (TextView) findViewById(R.id.textView1);<span style="white-space:pre"></span>textviewY = (TextView) findViewById(R.id.textView3);<span style="white-space:pre"></span>textviewZ = (TextView) findViewById(R.id.textView4);<span style="white-space:pre"></span>textviewF = (TextView) findViewById(R.id.textView2);<span style="white-space:pre"></span>textviewS = (TextView) findViewById(R.id.textView5);<span style="white-space:pre"></span>textview1 = (TextView) findViewById(R.id.textView6);<span style="white-space:pre"></span>textview2 = (TextView) findViewById(R.id.textView7);<span style="white-space:pre"></span>textview3 = (TextView) findViewById(R.id.textView8);*/<span style="white-space:pre"></span>        mContext = getApplicationContext();        // 初始化轨迹服务客户端        client = new LBSTraceClient(mContext);        // 初始化entity标识        entityName = getImei(mContext);        // 初始化轨迹服务        trace = new Trace(getApplicationContext(), serviceId, entityName, traceType);        // 添加entity  //      addEntity();        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);<span style="white-space:pre"></span>mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);// TYPE_GRAVITY<span style="white-space:pre"></span>if (null == mSensorManager) {<span style="white-space:pre"></span>Log.d(TAG, "deveice not support SensorManager");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>mSensorManager.registerListener(this, mSensor,<span style="white-space:pre"></span>SensorManager.SENSOR_DELAY_NORMAL);// SENSOR_DELAY_GAME    }        public void onAccuracyChanged(Sensor sensor, int accuracy) {<span style="white-space:pre"></span>}<span style="white-space:pre"></span>@Override<span style="white-space:pre"></span>public void onSensorChanged(SensorEvent event) {<span style="white-space:pre"></span>if (event.sensor == null) {<span style="white-space:pre"></span>return;<span style="white-space:pre"></span>}//<span style="white-space:pre"></span>if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {//<span style="white-space:pre"></span>int x = (int) event.values[0];//<span style="white-space:pre"></span>int y = (int) event.values[1];//<span style="white-space:pre"></span>int z = (int) event.values[2];//<span style="white-space:pre"></span>cal = (float) Math.sqrt(x * x + y * y + z * z);//<span style="white-space:pre"></span>/*<span style="white-space:pre"></span>int lastx = x - lastX;//<span style="white-space:pre"></span>int lasty = y - lastY;//<span style="white-space:pre"></span>int lastz = z - lastZ;//<span style="white-space:pre"></span>*///<span style="white-space:pre"></span>//<span style="white-space:pre"></span>precal = (float) Math.sqrt(lastX * lastX + lastY * lastY + lastZ * lastZ);//<span style="white-space:pre"></span>int temp = decide(precal,cal);//<span style="white-space:pre"></span>minnum = getminnum(cal);//<span style="white-space:pre"></span>if(temp == 1 || (top - buttom) >= 0.2){//<span style="white-space:pre"></span>s = s + 1;//<span style="white-space:pre"></span>}///*<span style="white-space:pre"></span>if (lastx + lasty + lastz > 0)//<span style="white-space:pre"></span>{//<span style="white-space:pre"></span>s=s+1;<span style="white-space:pre"></span>//<span style="white-space:pre"></span>textviewS.setText(""+s+"");//<span style="white-space:pre"></span>}//<span style="white-space:pre"></span>*///<span style="white-space:pre"></span>//<span style="white-space:pre"></span>/*<span style="white-space:pre"></span>textview1.setText(""+lastx+"");//<span style="white-space:pre"></span>textview2.setText(""+lasty+"");//<span style="white-space:pre"></span>textview3.setText(""+lastz+"");*///<span style="white-space:pre"></span>mCalendar = Calendar.getInstance();//<span style="white-space:pre"></span>long stamp = mCalendar.getTimeInMillis() / 1000l;////<span style="white-space:pre"></span>//<span style="white-space:pre"></span>int second = mCalendar.get(Calendar.SECOND);//<span style="white-space:pre"></span>textviewX.setText(String.valueOf(x));//<span style="white-space:pre"></span>textviewY.setText(String.valueOf(y));//<span style="white-space:pre"></span>textviewZ.setText(String.valueOf(z));//<span style="white-space:pre"></span>textview1.setText("阈值"+temp+"");//<span style="white-space:pre"></span>textview2.setText("波峰"+top+"");//<span style="white-space:pre"></span>textview3.setText("波谷"+buttom+"");//<span style="white-space:pre"></span>int px = Math.abs(mX - x);//<span style="white-space:pre"></span>int py = Math.abs(mY - y);//<span style="white-space:pre"></span>int pz = Math.abs(mZ - z);//<span style="white-space:pre"></span>Log.d(TAG, "pX:" + px + "  pY:" + py + "  pZ:" + pz + "    stamp:"//<span style="white-space:pre"></span>+ stamp + "  second:" + second);//<span style="white-space:pre"></span>int maxvalue = getMaxValue(px, py, pz);//<span style="white-space:pre"></span>if (maxvalue > 2 && (stamp - lasttimestamp) > 5) {//<span style="white-space:pre"></span>lasttimestamp = stamp;//<span style="white-space:pre"></span>Log.d(TAG, " sensor isMoveorchanged....");//<span style="white-space:pre"></span>textviewF.setText("检测正在移动..");//<span style="white-space:pre"></span>//<span style="white-space:pre"></span>textviewS.setText("当前步数"+s+"");//<span style="white-space:pre"></span>//<span style="white-space:pre"></span>lastX = x;//<span style="white-space:pre"></span>lastY = y;//<span style="white-space:pre"></span>lastZ = z;<span style="white-space:pre"></span>//<span style="white-space:pre"></span>}////<span style="white-space:pre"></span>/*<span style="white-space:pre"></span>mX = x;//<span style="white-space:pre"></span>mY = y;//<span style="white-space:pre"></span>mZ = z;//*///<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}//<span style="white-space:pre"></span>public void OpenNew(View v){//<span style="white-space:pre"></span>    //新建一个显式意图,第一个参数为当前Activity类对象,第二个参数为你要打开的Activity类//<span style="white-space:pre"></span>    Intent intent =new Intent(MainActivity.this,TrackUploadFragment.class);//<span style="white-space:pre"></span>    //<span style="white-space:pre"></span>    //用Bundle携带数据//<span style="white-space:pre"></span>    Bundle bundle=new Bundle();//<span style="white-space:pre"></span>    //传递name参数为tinyphp//<span style="white-space:pre"></span>    bundle.putString("name", "s");//<span style="white-space:pre"></span>    intent.putExtras(bundle);//<span style="white-space:pre"></span>    //<span style="white-space:pre"></span>    startActivity(intent);        //<span style="white-space:pre"></span>    }<span style="white-space:pre"></span>public int getMaxValue(int px, int py, int pz) {<span style="white-space:pre"></span>int max = 0;<span style="white-space:pre"></span>if (px > py && px > pz) {<span style="white-space:pre"></span>max = px;<span style="white-space:pre"></span>} else if (py > px && py > pz) {<span style="white-space:pre"></span>max = py;<span style="white-space:pre"></span>} else if (pz > px && pz > py) {<span style="white-space:pre"></span>max = pz;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>return max;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>public int decide(float oldcal, float newcal){<span style="white-space:pre"></span>if(oldcal < newcal){<span style="white-space:pre"></span>lastnum ++;<span style="white-space:pre"></span>preup = 1;<span style="white-space:pre"></span>predown=0;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>else{<span style="white-space:pre"></span>prelastnum = lastnum;<span style="white-space:pre"></span>lastnum = 0;<span style="white-space:pre"></span>preup=0;<span style="white-space:pre"></span>predown=1;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>if(preup == 1 && prelastnum >= 2){<span style="white-space:pre"></span>top = oldcal;<span style="white-space:pre"></span>return 1;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>else if(preup == 1 && prelastnum == 0){<span style="white-space:pre"></span>buttom = oldcal;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>return 0;<span style="white-space:pre"></span>}<span style="white-space:pre"></span><span style="white-space:pre"></span>float []tempValue = new float[4] ;<span style="white-space:pre"></span>int tempCount = 0;public float getminnum(float cal) {<span style="white-space:pre"></span>float tempThread = (float)0.2;<span style="white-space:pre"></span>if (tempCount < 4) {<span style="white-space:pre"></span>tempValue[tempCount] = cal;<span style="white-space:pre"></span>tempCount++;<span style="white-space:pre"></span>} else {<span style="white-space:pre"></span>tempThread = averageValue(tempValue, 4);<span style="white-space:pre"></span>for (int i = 1; i < 4; i++) {<span style="white-space:pre"></span>tempValue[i - 1] = tempValue[i];<span style="white-space:pre"></span>}<span style="white-space:pre"></span>tempValue[3] = cal;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>return tempThread;}public float averageValue(float value[], int n) {<span style="white-space:pre"></span>float ave = 0;<span style="white-space:pre"></span>for (int i = 0; i < n; i++) {<span style="white-space:pre"></span>ave += value[i];<span style="white-space:pre"></span>}<span style="white-space:pre"></span>ave = ave / 4;<span style="white-space:pre"></span>if (ave >= 8)<span style="white-space:pre"></span>ave = (float) 4.3;<span style="white-space:pre"></span>else if (ave >= 7 && ave < 8)<span style="white-space:pre"></span>ave = (float) 3.3;<span style="white-space:pre"></span>else if (ave >= 4 && ave < 7)<span style="white-space:pre"></span>ave = (float) 2.3;<span style="white-space:pre"></span>else if (ave >= 3 && ave < 4)<span style="white-space:pre"></span>ave = (float) 2.0;<span style="white-space:pre"></span>else {<span style="white-space:pre"></span>ave = (float) 1.3;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>return ave;}    @Override    protected void onStart() {        // TODO Auto-generated method stub        super.onStart();        // 初始化控件        btnTrackUpload = (Button) findViewById(R.id.btn_trackupload);        btnTrackQuery = (Button) findViewById(R.id.btn_trackquery);        btnTrackUpload.setOnClickListener(this);        btnTrackQuery.setOnClickListener(this);        fragmentManager = getFragmentManager();        bmapView = (MapView) findViewById(R.id.bmapView);        mBaiduMap = bmapView.getMap();        bmapView.showZoomControls(false);        // 初始化OnEntityListener        initOnEntityListener();        // 设置默认的Fragment        setDefaultFragment();    }    /**     * 添加Entity     *///   private void addEntity() {//        Geofence.addEntity();//    }    /**     * 设置默认的Fragment     */    private void setDefaultFragment() {        handlerButtonClick(R.id.btn_trackupload);    }    /**     * 点击事件     */    public void onClick(View v) {        // TODO Auto-generated method stub        handlerButtonClick(v.getId());    }    /**     * 初始化OnEntityListener     */    private void initOnEntityListener() {        entityListener = new OnEntityListener() {            // 请求失败回调接口            @Override            public void onRequestFailedCallback(String arg0) {                // TODO Auto-generated method stub                Looper.prepare();                Toast.makeText(getApplicationContext(), "entity请求失败回调接口消息 : " + arg0, Toast.LENGTH_SHORT).show();                Looper.loop();            }            // 添加entity回调接口            @Override            public void onAddEntityCallback(String arg0) {                // TODO Auto-generated method stub                Looper.prepare();                Toast.makeText(getApplicationContext(), "添加entity回调接口消息 : " + arg0, Toast.LENGTH_SHORT).show();                Looper.loop();            }            // 查询entity列表回调接口            @Override            public void onQueryEntityListCallback(String message) {                // TODO Auto-generated method stub                if (mTrackUploadFragment != null) {                    mTrackUploadFragment.showRealtimeTrack(message);                }            }        };    }    /**     * 处理tab点击事件     *      * @param id     */    private void handlerButtonClick(int id) {        // 重置button状态        onResetButton();        // 开启Fragment事务        FragmentTransaction transaction = fragmentManager.beginTransaction();        // 隐藏Fragment        hideFragments(transaction);        switch (id) {            case R.id.btn_trackquery:                TrackUploadFragment.isInUploadFragment = false;                if (mTrackQueryFragment == null) {                    mTrackQueryFragment = new TrackQueryFragment();                    transaction.add(R.id.fragment_content, mTrackQueryFragment);                } else {                    transaction.show(mTrackQueryFragment);                }                mTrackQueryFragment.addMarker();                btnTrackQuery.setTextColor(Color.rgb(0x00, 0x00, 0xd8));                btnTrackQuery.setBackgroundColor(Color.rgb(0x99, 0xcc, 0xff));                mBaiduMap.setOnMapClickListener(null);                break;            case R.id.btn_trackupload:                TrackUploadFragment.isInUploadFragment = true;                if (mTrackUploadFragment == null) {                    mTrackUploadFragment = new TrackUploadFragment();                    transaction.add(R.id.fragment_content, mTrackUploadFragment);                } else {                    transaction.show(mTrackUploadFragment);                }                TrackUploadFragment.addMarker();                btnTrackUpload.setTextColor(Color.rgb(0x00, 0x00, 0xd8));                btnTrackUpload.setBackgroundColor(Color.rgb(0x99, 0xcc, 0xff));                mBaiduMap.setOnMapClickListener(null);                break;        }        // 事务提交        transaction.commit();    }    /**     * 重置button状态     */    private void onResetButton() {        btnTrackQuery.setTextColor(Color.rgb(0x00, 0x00, 0x00));        btnTrackQuery.setBackgroundColor(Color.rgb(0xFF, 0xFF, 0xFF));        btnTrackUpload.setTextColor(Color.rgb(0x00, 0x00, 0x00));        btnTrackUpload.setBackgroundColor(Color.rgb(0xFF, 0xFF, 0xFF));    }    /**     * 隐藏Fragment     *      */    private void hideFragments(FragmentTransaction transaction) {        if (mTrackQueryFragment != null) {            transaction.hide(mTrackQueryFragment);        }        if (mTrackUploadFragment != null) {            transaction.hide(mTrackUploadFragment);        }        // 清空地图覆盖物        mBaiduMap.clear();    }    /**     * 获取设备IMEI码     *      * @param context     * @return     */    protected static String getImei(Context context) {        String mImei = "NULL";        try {            mImei = ((TelephonyManager) context                    .getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();        } catch (Exception e) {            System.out.println("获取IMEI码失败");            mImei = "NULL";        }        return mImei;    }    @Override    protected void onDestroy() {        // TODO Auto-generated method stub        super.onDestroy();        client.onDestroy();    }}

package com.baidu.trackshow;import java.util.ArrayList;import java.util.List;import android.annotation.SuppressLint;import android.app.Fragment;import android.graphics.Color;import android.os.Bundle;import android.os.Handler;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.TextView;import android.widget.Toast;import android.content.Intent;import android.content.IntentFilter;import com.baidu.mapapi.map.BitmapDescriptor;import com.baidu.mapapi.map.BitmapDescriptorFactory;import com.baidu.mapapi.map.MapStatus;import com.baidu.mapapi.map.MapStatusUpdate;import com.baidu.mapapi.map.MapStatusUpdateFactory;import com.baidu.mapapi.map.MarkerOptions;import com.baidu.mapapi.map.OverlayOptions;import com.baidu.mapapi.map.PolylineOptions;import com.baidu.mapapi.model.LatLng;import com.baidu.trace.OnStartTraceListener;import com.baidu.trace.OnStopTraceListener;import com.baidu.trackutils.GsonService;import com.baidu.trackutils.RealtimeTrackData;import com.baidu.mapapi.SDKInitializer;import com.baidu.mapapi.map.BaiduMap;import com.baidu.mapapi.map.MapView;import com.baidu.trackshow.R;import com.baidu.trace.LBSTraceClient;import com.baidu.trace.OnEntityListener;import com.baidu.trace.Trace;import android.annotation.SuppressLint;import android.app.FragmentManager;import android.app.FragmentTransaction;import android.content.Context;import android.graphics.Color;import android.os.Bundle;import android.os.Looper;import android.support.v4.app.FragmentActivity;import android.telephony.TelephonyManager;import android.view.View;import android.view.View.OnClickListener;import android.view.Window;import android.widget.Button;import android.widget.Toast;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.hardware.Sensor;import android.hardware.SensorEvent;import android.hardware.SensorEventListener;import android.hardware.SensorManager;import android.app.Activity;import android.content.Context;import android.util.Log;import android.widget.TextView;import java.text.DateFormat;import java.text.ParsePosition;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;import com.baidu.mapapi.SDKInitializer;import com.baidu.mapapi.map.MapView;/** * 轨迹追踪 */@SuppressLint("NewApi")public class TrackUploadFragment extends Fragment implements SensorEventListener{    private Button btnStartTrace = null;    private Button btnStopTrace = null;    private Button btnOperator = null;            private Context context;    private int mX, mY, mZ;private long lasttimestamp = 0;Calendar mCalendar;int s = 0;int lastX = 0,lastY = 0,lastZ = 0;float cal;float precal;float minnum;int lastnum = 0;float top,buttom;int prelastnum = 0;int preup=0;int predown=0;int h = 480;int flag=0;private float mLastValues[] = new float[3 * 2];private float mScale[] = new float[2];private float mYOffset;private static long end = 0;private static long start = 0;private float mLastDirections[] = new float[3 * 2];private float mLastExtremes[][] = { new float[3 * 2], new float[3 * 2] };private float mLastDiff[] = new float[3 * 2];private int mLastMatch = -1;public static int CURRENT_SETP = 0;            protected TextView tvEntityName = null;    private TextView textview111;    private static final String TAG = MainActivity.class.getSimpleName();private SensorManager mSensorManager;private Sensor mSensor; //   private Geofence geoFence = null;    /**     * 开启轨迹服务监听器     */    protected static OnStartTraceListener startTraceListener = null;    /**     * 停止轨迹服务监听器     */    protected static OnStopTraceListener stopTraceListener = null;    /**     * 打包周期(单位 : 秒)     */    private int packInterval = 30;    /**     * 图标     */    private static BitmapDescriptor realtimeBitmap;    // 覆盖物    protected static OverlayOptions overlay;    // 路线覆盖物    private static PolylineOptions polyline = null;    private static List<LatLng> pointList = new ArrayList<LatLng>();    protected boolean isTraceStart = false;    /**     * 刷新地图线程(获取实时点)     */    protected RefreshThread refreshThread = null;    protected static MapStatusUpdate msUpdate = null;    private View view = null;    private LayoutInflater mInflater = null;    protected static boolean isInUploadFragment = true;                    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,            Bundle savedInstanceState) {        view = inflater.inflate(R.layout.fragment_trackupload, container, false);                      //  super.onCreate(savedInstanceState);       // SDKInitializer.initialize(getApplicationContext());       // setContentView(R.layout.activity_main);        textview111 = (TextView) view.findViewById(R.id.textView11);                        mYOffset = h * 0.5f;mScale[0] = -(h * 0.5f * (1.0f / (SensorManager.STANDARD_GRAVITY * 2)));mScale[1] = -(h * 0.5f * (1.0f / (SensorManager.MAGNETIC_FIELD_EARTH_MAX)));        context=getActivity();        mInflater = inflater;        mSensorManager = (SensorManager) context.getSystemService(context.SENSOR_SERVICE);mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);// TYPE_GRAVITYif (null == mSensorManager) {Log.d(TAG, "deveice not support SensorManager");}mSensorManager.registerListener(this, mSensor,SensorManager.SENSOR_DELAY_NORMAL);// SENSOR_DELAY_GAME                        return view;    }    public void onAccuracyChanged(Sensor sensor, int accuracy) {}@Override//public void onSensorChanged(SensorEvent event) {//if (event.sensor == null) {//return;//}//if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {//int x = (int) event.values[0];//int y = (int) event.values[1];//int z = (int) event.values[2];//cal = (float) Math.sqrt(x * x + y * y + z * z);///*int lastx = x - lastX;//int lasty = y - lastY;//int lastz = z - lastZ;//*/////precal = (float) Math.sqrt(lastX * lastX + lastY * lastY + lastZ * lastZ);//int temp = decide(precal,cal);//minnum = getminnum(cal);//if(temp == 1 || (top - buttom) >= 0.2){//s = s + 1;//}///*if (lastx + lasty + lastz > 0)//{//s=s+1;//textviewS.setText(""+s+"");//}//*//////*textview1.setText(""+lastx+"");//textview2.setText(""+lasty+"");//textview3.setText(""+lastz+"");*///mCalendar = Calendar.getInstance();//long stamp = mCalendar.getTimeInMillis() / 1000l;//////int second = mCalendar.get(Calendar.SECOND);////textviewX.setText(String.valueOf(x));////textviewY.setText(String.valueOf(y));////textviewZ.setText(String.valueOf(z));////textview1.setText("阈值"+temp+"");////textview2.setText("波峰"+top+"");////textview3.setText("波谷"+buttom+"");//int px = Math.abs(mX - x);//int py = Math.abs(mY - y);//int pz = Math.abs(mZ - z);//Log.d(TAG, "pX:" + px + "  pY:" + py + "  pZ:" + pz + "    stamp:"//+ stamp + "  second:" + second);//int maxvalue = getMaxValue(px, py, pz);//if (maxvalue > 2 && (stamp - lasttimestamp) > 5) {//lasttimestamp = stamp;//Log.d(TAG, " sensor isMoveorchanged....");////textviewF.setText("检测正在移动..");//////textviewS.setText("当前步数"+s+"");////lastX = x;//lastY = y;//lastZ = z;//}//}//}public void onSensorChanged(SensorEvent event) {// Log.i(Constant.STEP_SERVER, "StepDetector");Sensor sensor = event.sensor;// Log.i(Constant.STEP_DETECTOR, "onSensorChanged");synchronized (this) {if (event.sensor == null) {} else {int j = (sensor.getType() == Sensor.TYPE_ACCELEROMETER) ? 1 : 0;if (j == 1) {float vSum = 0;for (int i = 0; i < 3; i++) {final float v = mYOffset + event.values[i] * mScale[j];vSum += v;}int k = 0;float v = vSum / 3;float direction = (v > mLastValues[k] ? 1: (v < mLastValues[k] ? -1 : 0));if (direction == -mLastDirections[k]) {// Direction changedint extType = (direction > 0 ? 0 : 1); // minumum or// maximum?mLastExtremes[extType][k] = mLastValues[k];float diff = Math.abs(mLastExtremes[extType][k]- mLastExtremes[1 - extType][k]);if (diff > 10 ) {boolean isAlmostAsLargeAsPrevious = diff > (mLastDiff[k] * 2 / 3);boolean isPreviousLargeEnough = mLastDiff[k] > (diff / 3);boolean isNotContra = (mLastMatch != 1 - extType);if (isAlmostAsLargeAsPrevious && isPreviousLargeEnough && isNotContra) {end = System.currentTimeMillis();if (end - start > 500) {// 此时判断为走了一步Log.i("StepDetector", "CURRENT_SETP:"+ CURRENT_SETP);CURRENT_SETP++;mLastMatch = extType;start = end;}} else {mLastMatch = -1;}mLastDiff[k] = diff;}}mLastDirections[k] = direction;mLastValues[k] = v;}if(flag == 0)textview111.setText(""+CURRENT_SETP+"");}}}public int getMaxValue(int px, int py, int pz) {int max = 0;if (px > py && px > pz) {max = px;} else if (py > px && py > pz) {max = py;} else if (pz > px && pz > py) {max = pz;}return max;}public int decide(float oldcal, float newcal){if(oldcal < newcal){lastnum ++;preup = 1;predown=0;}else{prelastnum = lastnum;lastnum = 0;preup=0;predown=1;}if(preup == 1 && prelastnum >= 2){top = oldcal;return 1;}else if(preup == 1 && prelastnum == 0){buttom = oldcal;}return 0;}float []tempValue = new float[4] ;int tempCount = 0;public float getminnum(float cal) {float tempThread = (float)0.2;if (tempCount < 4) {tempValue[tempCount] = cal;tempCount++;} else {tempThread = averageValue(tempValue, 4);for (int i = 1; i < 4; i++) {tempValue[i - 1] = tempValue[i];}tempValue[3] = cal;}return tempThread;}public float averageValue(float value[], int n) {float ave = 0;for (int i = 0; i < n; i++) {ave += value[i];}ave = ave / 4;if (ave >= 8)ave = (float) 4.3;else if (ave >= 7 && ave < 8)ave = (float) 3.3;else if (ave >= 4 && ave < 7)ave = (float) 2.3;else if (ave >= 3 && ave < 4)ave = (float) 2.0;else {ave = (float) 1.3;}return ave;}    @Override    public void onStart() {        // TODO Auto-generated method stub        super.onStart();        // 初始化        init();        // 初始化监听器        initListener();        // 设置采集周期        setInterval();        // 设置http请求协议类型        // setRequestType();    }    /**     * 初始化     *      * @param context     */    private void init() {        btnStartTrace = (Button) view.findViewById(R.id.btn_starttrace);        btnStopTrace = (Button) view.findViewById(R.id.btn_stoptrace); //       btnOperator = (Button) view.findViewById(R.id.btn_operator);        tvEntityName = (TextView) view.findViewById(R.id.tv_entityName);        tvEntityName.setText(" entityName : " + MainActivity.entityName + " ");        btnStartTrace.setOnClickListener(new View.OnClickListener() {            public void onClick(View v) {                            // TODO Auto-generated method stub            textview111.setText("当前开始步数"+CURRENT_SETP+" ");            flag = 0;                Toast.makeText(getActivity(), "正在开启轨迹服务,请稍候", Toast.LENGTH_LONG).show();                startTrace();            }        });        btnStopTrace.setOnClickListener(new View.OnClickListener() {            public void onClick(View v) {            textview111.setText("当前结束步数"+CURRENT_SETP+"");            flag = 1;                // TODO Auto-generated method stub            //Intent intent = getActivity().getIntent();            //Bundle bundle = getActivity().getIntent().getExtras();                //接收name值            //    String name = bundle.getString("name");               //Log.i("获取到的name值为",name);                //    textview111.setText(name);                Toast.makeText(getActivity(), "正在停止轨迹服务,请稍候", Toast.LENGTH_SHORT).show();                stopTrace();            }        });   /*     btnOperator.setOnClickListener(new View.OnClickListener() {            public void onClick(View v) {                // TODO Auto-generated method stub                geoFence = new Geofence(getActivity(), mInflater);                if (geoFence.popupwindow != null && geoFence.popupwindow.isShowing()) {                    geoFence.popupwindow.dismiss();                    return;                } else {                    geoFence.initPopupWindowView();                    geoFence.popupwindow.showAsDropDown(v, 0, 5);                }            }        });*/    }    /**     * 初始化监听器     */    private void initListener() {        // 初始化开启轨迹服务监听器        initOnStartTraceListener();        // 初始化停止轨迹服务监听器        initOnStopTraceListener();    }    /**     * 开启轨迹服务     *      */    private void startTrace() {        // 通过轨迹服务客户端client开启轨迹服务        MainActivity.client.startTrace(MainActivity.trace, startTraceListener);    }    /**     * 停止轨迹服务     *      */    private void stopTrace() {        // 通过轨迹服务客户端client停止轨迹服务        MainActivity.client.stopTrace(MainActivity.trace, stopTraceListener);    }    /**     * 设置采集周期和打包周期     *      */    private void setInterval() {        // 位置采集周期        int gatherInterval = 5;        // 打包周期        packInterval = 10;        MainActivity.client.setInterval(gatherInterval, packInterval);    }    /**     * 设置请求协议     */    @SuppressWarnings("unused")    private void setRequestType() {        int type = 1;        MainActivity.client.setProtocolType(type);    }    /**     * 查询实时轨迹     *      * @param v     */    private void queryRealtimeTrack() {        // // entity标识列表(多个entityName,以英文逗号"," 分割)        String entityNames = MainActivity.entityName;        // 属性名称(格式为 : "key1=value1,key2=value2,.....")        String columnKey = "";        // 返回结果的类型(0 : 返回全部结果,1 : 只返回entityName的列表)        int returnType = 0;        // 活跃时间(指定该字段时,返回从该时间点之后仍有位置变动的entity的实时点集合)        // int activeTime = (int) (System.currentTimeMillis() / 1000 - 30);        int activeTime = 0;        // 分页大小        int pageSize = 10;        // 分页索引        int pageIndex = 1;        MainActivity.client.queryEntityList(MainActivity.serviceId, entityNames, columnKey, returnType, activeTime,                pageSize,                pageIndex, MainActivity.entityListener);    }    /**     * 初始化OnStartTraceListener     */    private void initOnStartTraceListener() {        // 初始化startTraceListener        startTraceListener = new OnStartTraceListener() {            // 开启轨迹服务回调接口(arg0 : 消息编码,arg1 : 消息内容,详情查看类参考)            public void onTraceCallback(int arg0, String arg1) {                // TODO Auto-generated method stub                showMessage("开启轨迹服务回调接口消息 [消息编码 : " + arg0 + ",消息内容 : " + arg1 + "]", Integer.valueOf(arg0));                if (0 == arg0) {                    isTraceStart = true;                    startRefreshThread(true);                }            }            // 轨迹服务推送接口(用于接收服务端推送消息,arg0 : 消息类型,arg1 : 消息内容,详情查看类参考)            public void onTracePushCallback(byte arg0, String arg1) {                // TODO Auto-generated method stub                showMessage("轨迹服务推送接口消息 [消息类型 : " + arg0 + ",消息内容 : " + arg1 + "]", null);            }        };    }    /**     * 初始化OnStopTraceListener     */    private void initOnStopTraceListener() {        // 初始化stopTraceListener        stopTraceListener = new OnStopTraceListener() {            // 轨迹服务停止成功            public void onStopTraceSuccess() {                // TODO Auto-generated method stub                showMessage("停止轨迹服务成功", Integer.valueOf(1));                isTraceStart = false;                startRefreshThread(false);            }            // 轨迹服务停止失败(arg0 : 错误编码,arg1 : 消息内容,详情查看类参考)            public void onStopTraceFailed(int arg0, String arg1) {                // TODO Auto-generated method stub                showMessage("停止轨迹服务接口消息 [错误编码 : " + arg0 + ",消息内容 : " + arg1 + "]", null);            }        };    }    protected class RefreshThread extends Thread {        protected boolean refresh = true;        @Override        public void run() {            // TODO Auto-generated method stub            while (refresh) {                // 查询实时轨迹                queryRealtimeTrack();                try {                    Thread.sleep(packInterval * 1000);                } catch (InterruptedException e) {                    // TODO Auto-generated catch block                    System.out.println("线程休眠失败");                }            }        }    }    /**     * 显示实时轨迹     *      * @param realtimeTrack     */    protected void showRealtimeTrack(String realtimeTrack) {        if (null == refreshThread || !refreshThread.refresh) {            return;        }        RealtimeTrackData realtimeTrackData = GsonService.parseJson(realtimeTrack,                RealtimeTrackData.class);        if (null != realtimeTrackData && realtimeTrackData.getStatus() == 0) {            LatLng latLng = realtimeTrackData.getRealtimePoint();            if (null != latLng) {                pointList.add(latLng);                if (isInUploadFragment) {                    // 绘制实时点                    drawRealtimePoint(latLng);                }            } else {                showMessage("当前查询无轨迹点", null);            }        }    }    /**     * 绘制实时点     *      * @param points     */    private void drawRealtimePoint(LatLng point) {        MainActivity.mBaiduMap.clear();        MapStatus mMapStatus = new MapStatus.Builder().target(point).zoom(18).build();        msUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);        realtimeBitmap = BitmapDescriptorFactory                .fromResource(R.drawable.icon_gcoding);        overlay = new MarkerOptions().position(point)                .icon(realtimeBitmap).zIndex(9).draggable(true);        if (pointList.size() >= 2 && pointList.size() <= 10000) {            // 添加路线(轨迹)            polyline = new PolylineOptions().width(10)                    .color(Color.RED).points(pointList);        }        addMarker();    }    /**     * 添加地图覆盖物     */    protected static void addMarker() {        if (null != msUpdate) {            MainActivity.mBaiduMap.setMapStatus(msUpdate);        }        // 路线覆盖物        if (null != polyline) {            MainActivity.mBaiduMap.addOverlay(polyline);        }        // 围栏覆盖物//        if (null != Geofence.fenceOverlay) { //           MainActivity.mBaiduMap.addOverlay(Geofence.fenceOverlay); //       }        // 实时点覆盖物        if (null != overlay) {            MainActivity.mBaiduMap.addOverlay(overlay);        }    }    protected void startRefreshThread(boolean isStart) {        if (null == refreshThread) {            refreshThread = new RefreshThread();        }        refreshThread.refresh = isStart;        if (isStart) {            if (!refreshThread.isAlive()) {                refreshThread.start();            }        } else {            refreshThread = null;        }    }    private void showMessage(final String message, final Integer errorNo) {        new Handler(MainActivity.mContext.getMainLooper()).post(new Runnable() {            public void run() {                Toast.makeText(MainActivity.mContext, message, Toast.LENGTH_LONG).show();                if (null != errorNo) {                    if (0 == errorNo.intValue()) {                        btnStartTrace.setBackgroundColor(Color.rgb(0x99, 0xcc, 0xff));                        btnStartTrace.setTextColor(Color.rgb(0x00, 0x00, 0xd8));                    } else if (1 == errorNo.intValue()) {                        btnStartTrace.setBackgroundColor(Color.rgb(0xff, 0xff, 0xff));                        btnStartTrace.setTextColor(Color.rgb(0x00, 0x00, 0x00));                    }                }            }        });    }}


与微信好友比较功能:

因为微信的个人开发者给的接口比较少,所以找了个第三方平台用来放云存储数据库,然后在微信弄了个公众号,关注这个公众号的人可以把这个app的步数信息传递到数据库中,然后就可以实现排名功能了。但是介于最近比较忙,所以只能先把这件事推后一下,过一段再实现这个功能了。



1 0