暑假里做了一个安卓计步器,不依靠GPS,也不用联网,只依靠重力加速度传感器和三轴磁力传感器,就可以实现记录步数和记录行走轨迹。我还加入了摇一摇切歌的功能,享受运动的乐趣~~
发布的apk可以在这里下载:pan.baidu.com/s/1i3gw3sh (打算以后完备了再发布到应用市场,所以欢迎大家吐槽评论)
这个项目只用了三天时间(作为自己的第一个安卓作品,我觉得还是很快的~~),当时完全是被deadline给逼出来的。老师对这个项目赞不绝口,觉得我一个正在上预科的孩子,学校里C语言还没有开课,就能自己做得这么好,于是果断给99分,哈哈~~不过,我觉得这个项目有很多地方可以改进和完善,因此在这里把这个项目总结一下,以备查询,也欢迎大家给出意见。以后有时间,再推出2.0、3.0等版本咯咯~~
计步器的原理是基本的物理知识,不再赘述,以后有时间可以单独写一篇,说明我是如何推导的。下面是所有代码:
第一部分:manifest
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.pedometre" android:versionCode="1" android:versionName="1.0" > <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="21" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name"> <activity android:theme="@style/myTheme" android:name=".MainActivity" android:label="@string/app_name" > </activity> <activity android:theme="@android:style/Theme.NoTitleBar" android:name="com.example.pedometre.splash"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.pedometre.aide" android:theme="@style/myTheme"> <meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".MainActivity" /> </activity> <activity android:name="com.example.pedometre.carteDraw" android:theme="@style/myTheme"> <meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".MainActivity" /> </activity> <service android:name="com.example.pedometre.StepCounterService"></service> <activity android:name="com.example.pedometre.mPlayer" android:theme="@style/myTheme"> <meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".MainActivity" /> </activity> <service android:name="com.example.pedometre.mPlayerService"></service> </application> </manifest>第二部分:mainActivity
package com.example.pedometre; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.text.DecimalFormat; import java.util.ArrayList; import com.example.pedometre.StepDetector; import com.example.pedometre.StepCounterService; import android.support.v4.widget.DrawerLayout; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorListener; import android.hardware.SensorManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewConfiguration; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Chronometer; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; public class MainActivity extends Activity { private DrawerLayout mDrawerLayout = null; private ListView mylistview; private ArrayList<String> list = new ArrayList<String>(); private TextView tv_step; private TextView sy_dis; private TextView sy_cal; private TextView sy_vit; private Button btn_start; private Button btn_stop; private Thread mThread; private Chronometer timer; public static int total_step = 0; private int total_step1=0; private float pep_weight=60; private float per_step=0.5f; private float last_time=0; private float kaluli=0; private float x=0; private float st_x=0; private float st_y=0; private String inputName=""; private SensorManager sm1; private SensorManager sm2; float[] accelerometerValues = new float[3]; float[] magneticFieldValues = new float[3]; public static float[]da_st=new float[10000]; public static float max_width=0f,max_height=0f; @SuppressLint("HandlerLeak") Handler mHandler = new Handler(){ @Override public void handleMessage(android.os.Message msg) { super.handleMessage(msg); if(msg.what == 0x00){ countStep(); tv_step.setText(total_step+""); last_time=last_time/1000/3600; kaluli=pep_weight*last_time*30/(last_time/per_step/total_step*400*60); DecimalFormat decimalFormat=new DecimalFormat("0.00"); sy_cal.setText(decimalFormat.format(kaluli)+"kcal"); float[] values = new float[3]; float[] R = new float[9]; SensorManager.getRotationMatrix(R, null, accelerometerValues, magneticFieldValues); SensorManager.getOrientation(R, values); da_st[total_step]=values[0]; /* st_x=(float) (st_x+Math.cos(values[0])); st_y=(float) (st_y+Math.sin(values[0])); if (Math.abs(st_x)>max_height){ max_height=Math.abs(st_x); } if (Math.abs(st_y)>max_width){ max_width=Math.abs(st_y); } */ sy_dis.setText(decimalFormat.format(total_step*per_step/1000)+"km"); sy_vit.setText(decimalFormat.format(total_step*per_step/1000/last_time)+"km/h"); } } }; private void countStep() { if(StepDetector.CURRENT_SETP % 2 == 0){ total_step = StepDetector.CURRENT_SETP; }else{ total_step = StepDetector.CURRENT_SETP + 1; } Log.i("total_step", StepDetector.CURRENT_SETP+""); total_step = StepDetector.CURRENT_SETP; }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sm1 = (SensorManager) getSystemService(SENSOR_SERVICE); sm2 = (SensorManager) getSystemService(SENSOR_SERVICE); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); forceShowOverflowMenu(); tv_step = (TextView) findViewById(R.id.tv_step); sy_dis = (TextView) findViewById(R.id.sy_distance); sy_cal = (TextView) findViewById(R.id.sy_caluli); sy_vit = (TextView) findViewById(R.id.sy_vitesse); btn_start = (Button) findViewById(R.id.btn_start); btn_stop = (Button) findViewById(R.id.btn_stop); timer = (Chronometer) findViewById(R.id.chronometer); mylistview = (ListView)findViewById(R.id.left_drawer); list.add("Poids(kg): (60kg par défaut)"); list.add("Longueur de chaque étape(cm): (50cm par défaut)"); list.add("La sensibilité du capteur: (3 par défaut)"); list.add("Intervalle temporel entre deux étapes(ms): (500 par défaut)"); ArrayAdapter<String> myArrayAdapter = new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1,list); mylistview.setAdapter(myArrayAdapter); mylistview.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) { if(list.get(arg2).contains("Poids")){ inputTitleDialog(); int t=0; try{ t=Integer.parseInt(inputName); }catch(Exception e){} if (t>0){ list.set(arg2,"Poids(kg): ("+inputName+"kg par défaut)"); pep_weight=t; } } if(list.get(arg2).contains("Longueur")){ inputTitleDialog(); int t=0; try{ t=Integer.parseInt(inputName); }catch(Exception e){} if (t>0){ list.set(arg2,"Longueur de chaque étape(cm): ("+inputName+"cm par défaut)"); per_step=(float) (t*1.0/100); } } if(list.get(arg2).contains("sensibilité")){ inputTitleDialog(); int t=0; try{ t=Integer.parseInt(inputName); }catch(Exception e){} if (t>0){ list.set(arg2,"La sensibilité du capteur: ("+inputName+" par défaut)"); StepDetector.SENSITIVITY=t; } } if(list.get(arg2).contains("Intervalle")){ inputTitleDialog(); int t=0; try{ t=Integer.parseInt(inputName); }catch(Exception e){} if (t>0){ list.set(arg2,"Intervalle temporel entre deux étapes(ms): ("+inputName+" par défaut)"); StepDetector.time_jg=t; } } } }); } @Override protected void onResume(){ super.onResume(); if (sm1 != null) { sm1.registerListener(sev1,sm1.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); } if (sm2 != null) { sm2.registerListener(sev2,sm2.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_NORMAL); } } private SensorEventListener sev1 = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { accelerometerValues = event.values; } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; private SensorEventListener sev2 = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { magneticFieldValues = event.values; } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; private void inputTitleDialog() { final EditText inputServer = new EditText(this); inputServer.setFocusable(true); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Réglages(Nombre entier naturel)").setIcon(R.drawable.ic_launcher). setView(inputServer).setNegativeButton("Annuler",null); builder.setPositiveButton("OK",new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int which) { inputName=inputServer.getText().toString(); } }); builder.show(); } public void btnClick(View view){ Intent service = new Intent(this, StepCounterService.class); switch (view.getId()) { case R.id.btn_music: turnAround2(); break; case R.id.btn_map: turnAround1(); break; case R.id.btn_start: timer.setBase(SystemClock.elapsedRealtime()); timer.start(); startService(service); btn_start.setEnabled(false); btn_stop.setEnabled(true); if(mThread == null){ mThread = new Thread(){ @Override public void run() { // TODO Auto-generated method stub super.run(); int temp = 0; while (true) { try { sleep(300); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(StepCounterService.FLAG){ Log.i("istrue", "true"); if (temp != StepDetector.CURRENT_SETP) { temp = StepDetector.CURRENT_SETP; } last_time=SystemClock.elapsedRealtime()-timer.getBase(); mHandler.sendEmptyMessage(0x00); } } } }; mThread.start(); } break; case R.id.btn_stop: timer.stop(); stopService(service); btn_start.setEnabled(true); btn_stop.setEnabled(false); StepDetector.CURRENT_SETP = 0; mHandler.removeCallbacks(mThread); break; default: break; } } private void turnAround1() { Intent intent = new Intent(); intent.setClass(MainActivity.this, carteDraw.class); startActivity(intent); } private void turnAround2() { Intent intent = new Intent(); intent.setClass(MainActivity.this, mPlayer.class); startActivity(intent); } private void forceShowOverflowMenu() { try { ViewConfiguration config = ViewConfiguration.get(this); Field menuKeyField = ViewConfiguration.class .getDeclaredField("sHasPermanentMenuKey"); if (menuKeyField != null) { menuKeyField.setAccessible(true); menuKeyField.setBoolean(config, false); } } catch (Exception e) { e.printStackTrace(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.help: turnAround(); return true; case R.id.setting: mDrawerLayout.openDrawer(Gravity.LEFT); return true; case R.id.exit: new AlertDialog.Builder(MainActivity.this).setTitle("Confirmation") .setMessage("Vous êtes sûr de me quitter?\n(⊙ ︿ ⊙)") .setPositiveButton("Oui",new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { finish(); } }).setNegativeButton("Non",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); return true; default: return super.onOptionsItemSelected(item); } } @Override public boolean onMenuOpened(int featureId, Menu menu) { setOverflowIconVisible(featureId, menu); return super.onMenuOpened(featureId, menu); } private void setOverflowIconVisible(int featureId, Menu menu) { if (featureId == Window.FEATURE_ACTION_BAR && menu != null) { if (menu.getClass().getSimpleName().equals("MenuBuilder")) { try { Method m = menu.getClass().getDeclaredMethod( "setOptionalIconsVisible", Boolean.TYPE); m.setAccessible(true); m.invoke(menu, true); } catch (Exception e) { Log.d("OverflowIconVisible", e.getMessage()); } } } } private void turnAround() { Intent intent = new Intent(); intent.setClass(MainActivity.this, aide.class); startActivity(intent); } }主界面效果图
设置界面效果图:
package com.example.pedometre; import android.os.*; import android.content.Intent; import android.app.*; import android.view.*; public class splash extends Activity{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.splash); new CountDownTimer(2000,100) { @Override public void onTick(long millisUntilFinished) { } @Override public void onFinish() { Intent intent = new Intent(); intent.setClass(splash.this, MainActivity.class); startActivity(intent); finish(); } }.start(); } }效果图
第四部分:carteDraw(绘制轨迹路线)
package com.example.pedometre; import com.example.pedometre.MainActivity; import android.annotation.SuppressLint; import android.app.ActionBar; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Bundle; import android.view.MenuItem; import android.view.View; public class carteDraw extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); MyView myView = new MyView(this); setContentView(myView); } private class MyView extends View{ public MyView(Context context) { super(context); } @SuppressLint("DrawAllocation") @Override public void onDraw(Canvas canvas){ super.onDraw(canvas); Paint paint = new Paint(); paint.setAntiAlias(true); paint.setColor(Color.YELLOW); paint.setStyle(Paint.Style.FILL); paint.setStrokeWidth(3); int r_w=canvas.getWidth(); int r_h=canvas.getHeight(); int f_w=(int) (MainActivity.max_width*2); int f_h=(int) (MainActivity.max_height*2); float rate=3; if (MainActivity.total_step<=20){ rate=25; } else if (MainActivity.total_step<=100){ rate=10; } else if (MainActivity.total_step<=400){ rate=5; } else { rate=3;} float x=r_w/2;float y=r_h/2; for (int i=1;i<=MainActivity.total_step;i++){ canvas.drawLine(x, y, (float) (x+rate*Math.sin(MainActivity.da_st[i])), (float) (y+rate*Math.cos(MainActivity.da_st[i])), paint); x=(float) (x+rate*Math.sin(MainActivity.da_st[i])); y=(float) (y+rate*Math.cos(MainActivity.da_st[i])); } } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case android.R.id.home: finish(); return true; default: return super.onOptionsItemSelected(item); } } }效果图:
第五部分:记录步数
package com.example.pedometre; 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 StepDetector implements SensorEventListener { public static int CURRENT_SETP = 0; public static float SENSITIVITY = 3; public static float time_jg=500; public static float step_long=0.5f; 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 StepDetector(Context context){ int h = 480; 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))); } @SuppressWarnings("deprecation") @Override public void onSensorChanged(SensorEvent event) { Sensor mSensor = event.sensor; synchronized (this) { if (mSensor.getType() == Sensor.TYPE_ORIENTATION) { } else { int j = (mSensor.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 changed int 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 > SENSITIVITY) { 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 > time_jg) { 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; } } } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) {} }
package com.example.pedometre; import com.example.pedometre.StepDetector; import android.app.Service; import android.content.Context; import android.content.Intent; import android.hardware.Sensor; import android.hardware.SensorManager; import android.os.IBinder; import android.os.PowerManager; import android.os.PowerManager.WakeLock; public class StepCounterService extends Service { public static boolean FLAG = false; private SensorManager mSensorManager; private StepDetector mStepDetector; private PowerManager mPowerManager; private WakeLock mWakeLock; @Override public IBinder onBind(Intent intent) { return null; } @SuppressWarnings("deprecation") @Override public void onCreate() { super.onCreate(); FLAG = true; mStepDetector = new StepDetector(this); mSensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE); mSensorManager.registerListener(mStepDetector, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_FASTEST); mPowerManager = (PowerManager) this.getSystemService(Context.POWER_SERVICE); mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK|PowerManager.ACQUIRE_CAUSES_WAKEUP, "s"); mWakeLock.acquire(); } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); FLAG = false; if(mStepDetector != null){ mSensorManager.unregisterListener(mStepDetector); } if(mWakeLock != null){ mWakeLock.release(); } } }第六部分:摇一摇切歌
package com.example.pedometre; import android.annotation.SuppressLint; import android.app.ActionBar; import android.app.Activity; import android.content.Intent; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.MenuItem; import android.view.View; import android.widget.Button; public class mPlayer extends Activity{ private int questop=0; private int it=0; private Button but_stop; private SensorManager sensorManager; private static final int SENSOR_SHAKE = 10; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.musicplay); but_stop=(Button)findViewById(R.id.mus_stop); ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); } @Override protected void onResume(){ super.onResume(); if (sensorManager != null) { sensorManager.registerListener(sensorEventListener,sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME); } } @Override protected void onDestroy(){ super.onStop(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case android.R.id.home: finish(); return true; default: return super.onOptionsItemSelected(item); } } private SensorEventListener sensorEventListener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { float[] values = event.values; float x = values[0]; float y = values[1]; float z = values[2]; int medumValue = 17; if (Math.abs(x) > medumValue || Math.abs(y) > medumValue || Math.abs(z) > medumValue) { Message msg = new Message(); msg.what = SENSOR_SHAKE; handler.sendMessage(msg); } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; @SuppressLint("HandlerLeak") Handler handler = new Handler() { @Override public void handleMessage(Message msg){ super.handleMessage(msg); switch (msg.what) { case SENSOR_SHAKE: if (questop==1){ it++; if (it>9){ it=1; } onPlay(it); } break; } } }; public void onClick_exit(View v){ Intent intent=new Intent(mPlayer.this,mPlayerService.class); intent.putExtra("playing", 10); startService(intent); finish(); } public void onClick_stop(View v){ if (questop==0){ Intent intent=new Intent(mPlayer.this,mPlayerService.class); intent.putExtra("playing", 11); startService(intent); but_stop.setText("Arrêter"); questop=1; } else{ Intent intent=new Intent(mPlayer.this,mPlayerService.class); intent.putExtra("playing", 10); startService(intent); but_stop.setText("Continuer"); questop=0; } } private void onPlay(int i) { Intent intent=new Intent(mPlayer.this,mPlayerService.class); intent.putExtra("playing", i); but_stop.setText("Arrêter"); questop=1;it=i; startService(intent); } public void onClick(View v){ onPlay(1); } public void onClick1(View v){ onPlay(2); } public void onClick2(View v){ onPlay(3); } public void onClick3(View v){ onPlay(4); } public void onClick4(View v){ onPlay(5); } public void onClick5(View v){ onPlay(6); } public void onClick6(View v){ onPlay(7); } public void onClick7(View v){ onPlay(8); } public void onClick8(View v){ onPlay(9); } }
<pre name="code" class="java">package com.example.pedometre; import android.app.Service; import android.content.Intent; import android.media.MediaPlayer; import android.os.IBinder; public class mPlayerService extends Service{ private MediaPlayer mp; @Override public void onCreate(){ super.onCreate(); mp=MediaPlayer.create(this,R.raw.music1); } @Override public void onDestroy(){ super.onDestroy(); mp.release(); stopSelf(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { int playing = intent.getIntExtra("playing", 0); switch(playing){ case 1: mp.release(); mp=MediaPlayer.create(this,R.raw.music1); mp.setLooping(true); mp.start(); break; case 2: mp.release();mp=MediaPlayer.create(this,R.raw.music2); mp.setLooping(true); mp.start(); break; case 3: mp.release();mp=MediaPlayer.create(this,R.raw.music3); mp.setLooping(true); mp.start(); break; case 4: mp.release();mp=MediaPlayer.create(this,R.raw.music4); mp.setLooping(true); mp.start(); break; case 5: mp.release();mp=MediaPlayer.create(this,R.raw.music5); mp.setLooping(true); mp.start(); break; case 6: mp.release();mp=MediaPlayer.create(this,R.raw.music6); mp.setLooping(true); mp.start(); break; case 7: mp.release();mp=MediaPlayer.create(this,R.raw.music7); mp.setLooping(true); mp.start(); break; case 8: mp.release();mp=MediaPlayer.create(this,R.raw.music8); mp.setLooping(true); mp.start(); break; case 9: mp.release();mp=MediaPlayer.create(this,R.raw.music9); mp.setLooping(true); mp.start(); break; case 10: if (mp.isPlaying()){ mp.pause(); } break; case 11: if (!(mp.isPlaying())){ mp.start(); } break; } return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent intent) { return null; } }
效果图:
第七部分:帮助信息
package com.example.pedometre; import android.app.ActionBar; import android.app.Activity; import android.os.Bundle; import android.view.MenuItem; public class aide extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.aide); ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case android.R.id.home: finish(); return true; default: return super.onOptionsItemSelected(item); } } }效果图:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" > <FrameLayout android:id="@+id/framelayout" android:layout_width="match_parent" android:layout_height="match_parent" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/bg_chunse" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="60dp" android:layout_marginLeft="@dimen/horizontal" android:orientation="horizontal"> <ImageButton android:layout_height="50dp" android:layout_width="50dp" android:layout_gravity="center_vertical" android:background="@drawable/time_duree"> </ImageButton> <Chronometer android:id ="@+id/chronometer" android:layout_height="match_parent" android:layout_width="wrap_content" android:layout_weight="1" android:format="%s" android:gravity="center" android:textSize="22sp" android:textColor="#030303"/> <ImageButton android:layout_height="50dp" android:layout_width="50dp" android:layout_gravity="center_vertical" android:background="@drawable/distance"/> <TextView android:id="@+id/sy_distance" android:gravity="center" android:text="0 km" android:textSize="22sp" android:textColor="#030303" android:layout_weight="1" android:layout_width="wrap_content" android:layout_height="match_parent"/> </LinearLayout> <LinearLayout android:layout_height="60dp" android:layout_width="match_parent" android:layout_marginLeft="@dimen/horizontal" android:orientation="horizontal"> <ImageButton android:layout_height="50dp" android:layout_width="50dp" android:layout_gravity="center_vertical" android:background="@drawable/sy_caluli"> </ImageButton> <TextView android:id="@+id/sy_caluli" android:gravity="center" android:text="0 kcal" android:textSize="22sp" android:textColor="#030303" android:layout_weight="1" android:layout_width="wrap_content" android:layout_height="match_parent"/> <ImageButton android:layout_height="50dp" android:layout_width="50dp" android:layout_gravity="center_vertical" android:background="@drawable/vitesse"/> <TextView android:id="@+id/sy_vitesse" android:gravity="center" android:text="0 km/h" android:textSize="22sp" android:textColor="#030303" android:layout_weight="1" android:layout_width="wrap_content" android:layout_height="match_parent"/> </LinearLayout> <TextView android:layout_width="match_parent" android:layout_height="10sp"/>" <TextView android:id="@+id/tv_step" android:layout_width="220sp" android:layout_height="220sp" android:background="@drawable/circle_button" android:layout_gravity="center_horizontal" android:gravity="center" android:text="0" android:textColor="#FF0000" android:textSize="60sp" /> <TextView android:layout_width="match_parent" android:layout_height="10sp"/> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_height="wrap_content" android:layout_width="match_parent" android:layout_weight="1" android:orientation="horizontal"> <Button android:id="@+id/btn_start" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:onClick="btnClick" android:text="@string/start" /> <Button android:id="@+id/btn_stop" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:onClick="btnClick" android:text="@string/stop" /> </LinearLayout> <LinearLayout android:layout_height="wrap_content" android:layout_width="match_parent" android:layout_weight="1" android:orientation="horizontal"> <Button android:id="@+id/btn_map" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:onClick="btnClick" android:text="@string/map" /> <Button android:id="@+id/btn_music" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:onClick="btnClick" android:text="@string/music" /> </LinearLayout> </LinearLayout> </LinearLayout> </FrameLayout> <ListView android:id="@+id/left_drawer" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="start" android:background="#8B0000" android:divider="#CD853F" android:dividerHeight="3dp" /> </android.support.v4.widget.DrawerLayout>
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:background="@drawable/bg_chunse" android:layout_width="match_parent" android:layout_height="match_parent" > <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:id="@+id/version_lable" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:paddingLeft="10dip" android:paddingTop="5dip" android:text="@string/version_lable" android:textColor="@color/orange" android:textSize="22sp" /> <TextView android:id="@+id/version_val" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_toRightOf="@+id/version_lable" android:paddingLeft="10dip" android:paddingTop="5dip" android:textColor="@color/green" android:textSize="22sp" /> <TextView android:id="@+id/description" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/version_lable" android:gravity="left" android:paddingLeft="10dip" android:paddingRight="10dip" android:paddingTop="10dip" android:text="@string/about_desc" android:textColor="@color/gray" android:textSize="22sp" > </TextView> </RelativeLayout> </ScrollView>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:background="@drawable/bg_chunse" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5dp" android:scrollX="2dp" android:textColor="#8B4513" android:textSize="18dp" android:text="@string/musicdec"></TextView> <LinearLayout android:layout_width="wrap_content" android:layout_gravity="center_horizontal" android:layout_height="wrap_content"> <Button android:id="@+id/mus_stop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:textColor="#EE0000" android:onClick="onClick_stop" android:text="@string/stop"/> <Button android:id="@+id/mus_exit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#EE0000" android:layout_weight="1" android:onClick="onClick_exit" android:text="@string/exit"/> </LinearLayout> <LinearLayout android:orientation="vertical" android:layout_width="wrap_content" android:layout_gravity="center_horizontal" android:layout_height="match_parent"> <Button android:id="@+id/mus_1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="onClick" android:text="@string/music1"/> <Button android:id="@+id/mus_2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="onClick1" android:text="@string/music2"/> <Button android:id="@+id/mus_3" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="onClick2" android:text="@string/music3"/> <Button android:id="@+id/mus_4" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="onClick3" android:text="@string/music4"/> <Button android:id="@+id/mus_5" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="onClick4" android:text="@string/music5"/> <Button android:id="@+id/mus_6" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="onClick5" android:text="@string/music6"/> <Button android:id="@+id/mus_7" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="onClick6" android:text="@string/music7"/> <Button android:id="@+id/mus_8" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="onClick7" android:text="@string/music8"/> <Button android:id="@+id/mus_9" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="onClick8" android:text="@string/music9"/> </LinearLayout> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <ImageView xmlns:android="http://schemas.android.com/apk/res/android" android:contentDescription="@string/app_name" android:layout_width="match_parent" android:layout_height="match_parent" android:src="@drawable/splash" android:scaleType="fitXY"> </ImageView>第九部分:string_value
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">pédomètre</string> <string name="action_settings">Réglages</string> <string name="help">Assistance</string> <string name="version_lable">Plus d\'infos</string> <string name="about_desc">Bonjour! Bienvenue à l\'utilisation de ce logiciel.\n\nCe logiciel vous permet d\'enregistrer le nombre de pas, de dessiner votre piste et de vous repaître de la musique.\n\nSi vous avez des questions, n\'hésitez pas à me contacter. Mon numéro de téléphone portable est +86 15156293795 et mon e-mail adresse est [email protected].\n\nJe vous souhaite tous mes vœux de bonheur!</string> <string name="edit_text">edit</string> <string name="file">file</string> <string name="about">about</string> <string name="exit">Echapper</string> <string name="music">Musique</string> <string name="map">Carte</string> <string name="start">Commencer</string> <string name="stop">Arrêter</string> <string name="musicdec">Vous pouvez sélectionner une chanson en appuyant sur un bouton.\nPour les changer, il suffit que vous secouiez votre portable.</string> <string name="music1">假如爱有天意..... 李健</string> <string name="music2">年轮...........张碧晨</string> <string name="music3">默........... 那英</string> <string name="music4">小水果..........筷子兄弟</string> <string name="music5">匆匆那年.........王菲</string> <string name="music6">不可说......... 霍建华/赵丽颖</string> <string name="music7">全民共舞........ 正月十五</string> <string name="music8">剩下的盛夏.......TFBOYS</string> <string name="music9">明天你好........ 牛奶咖啡</string> <string name="restart">Continuer</string> </resources>