首先,我必須說,我是菜鳥。接觸Android不就久,在這裏記下,第一想讓本身有更加深入的印象,第二也想和你們一塊兒分享。若是出現一些錯誤,還請批評和指正。java
先敘述一下一個小故事。(話說碼農都須要訓練本身的表達能力)。android
one day,朋友說好明天一塊兒去**地方去玩,可是到了次日,lz 等啊等,上午的時候,lz 想,睡睡懶覺也是很正常的,到了中午差很少一點鐘了,lz 有點急了,要出去玩也該行動了,因此lz 決定call朋友問狀況,結果電話一直沒人接,發短信什麼的也沒人回... 而後從腦殼裏面立刻蹦出來的想法是,朋友出事了(如今回想以爲本身確定有某種 神經類的病...)。時候到了晚上的時候,這位朋友qq上說,她手機摔水裏了,沒帶。(情節大概這樣,細節可能有誤,不過這些都不是關鍵,下面開始今天的學習筆記)git
這個小應用和上面這個事情也是能夠扯上那麼一點關係的。網絡
##使用簡介:app
安裝此軟件的用戶能夠經過start按鈕獲取本身位置ide
任何其餘人經過發送短信location到安裝了此軟件的手機上,這手機就會自動經過短信回覆它當前的位置。學習
##使用注意:測試
須要在有數據鏈接的狀況下才能得到具體位置,不然只能得到經緯度this
部分機型和系統不適用(多是權限問題)。(其中多部小米手機測試失敗,其餘都OK)google
###大概實現思路###
這些類的實現是東拼西湊出來的 這裏就再也不多講,代碼都有比較詳細的註釋
下面是code:
短信監視
<!-- lang: java --> // file : Receiver.java package com.example.location; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.telephony.SmsMessage; import android.widget.Toast; public class Receiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { SmsMessage msg = null; Bundle bundle = intent.getExtras(); if (bundle != null) { Object[] pdusObj = (Object[]) bundle.get("pdus"); for (Object p : pdusObj) { msg= SmsMessage.createFromPdu((byte[]) p); String msgTxt =msg.getMessageBody();//獲得消息的內容 String senderNumber = msg.getOriginatingAddress();// 獲得發信人的號碼,用於以後的回覆 // 若是短信內容爲location,這裏的判斷條件,能夠隨便設定,也能夠是 判斷電話號碼 if(msgTxt.equals("location")) // string1.equal(string2):用來判斷兩個字符創是否同樣。不能用 == 來判斷 { Toast.makeText(context, "來自"+senderNumber+"的定位請求", Toast.LENGTH_LONG).show();//Toast 是一個很好的和用戶交互的一個東西 Data.setNum(senderNumber);// 把電話號碼記錄下來,讓它變爲全局的一個變量 Intent i = new Intent(context, Main.class);// i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //在 broadcastreceiver 和activity 的通訊中,須要這句 context.startActivity(i);//啓動主程序 } } } return; } }
定位(這裏使用了百度地圖定位API V4.0, 這裏的主要代碼也是用了它給的demo,因此這裏用到了「依賴庫」須要從本身下載並添加到工程,能夠google或百度一下教程)
LocationDemoActivity.java:
<!-- lang: java --> package com.example.location; import android.annotation.SuppressLint; import android.app.Application; import android.os.Vibrator; import android.telephony.SmsManager; import android.widget.TextView; import android.widget.Toast; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.BDNotifyListener; import com.baidu.location.LocationClient; @SuppressLint("ShowToast") public class LocationDemoActivity extends Application{ public LocationClient mLocationClient = null; private String mData; public MyLocationListener myListener = new MyLocationListener(); public TextView mTv; public NotifyListener mNotifyer = null; public Vibrator mVibrator01; public static String TAG = "LocTest"; public void onCreate(){ mLocationClient = new LocationClient( this); mLocationClient.setAK("Sh4785hU7rESaywsFGAQUHio"); // 這個key須要本身去申請(百度地圖定位API) mLocationClient.registerLocationListener(myListener); super.onCreate(); } public void logMsg(String str){ SmsManager smsManager = SmsManager.getDefault(); try{ mData = str; // if( mTv != null){ // 判判定位是否成功 mTv.setText(mData); if(Data.getNum().equals("0")){ // 判斷是用戶本身在使用定位,仍是別人發短信 Toast.makeText(getApplicationContext(), "定位結束", Toast.LENGTH_SHORT).show(); } else{ smsManager.sendTextMessage(Data.getNum(),null,mData+"定位成功",null,null); Toast.makeText(getApplicationContext(), "正在回覆短信。。。", Toast.LENGTH_LONG).show(); android.os.Process.killProcess(android.os.Process.myPid()); //在定位以後自動關閉程序。 } } else{ Toast.makeText(this, "fail", Toast.LENGTH_LONG ).show(); } } catch(Exception e){ e.printStackTrace(); } } public class MyLocationListener implements BDLocationListener{ // 這裏打code幾乎都是那個demo上面的,詳細解釋能夠參考百度地圖定位API的開發指南 @Override public void onReceiveLocation(BDLocation location){ if(location == null) return ; StringBuffer sb = new StringBuffer(256); Toast.makeText(getApplicationContext(), "獲取經緯度中...", Toast.LENGTH_LONG).show(); sb.append("緯度"+location.getLatitude()+"\n"); sb.append("經度"+location.getLongitude()+"\n"); Toast.makeText(getApplicationContext(), "嘗試獲取詳細地址...", Toast.LENGTH_LONG).show(); if (location.getLocType()==BDLocation.TypeGpsLocation){ sb.append("速度"+location.getSpeed()+"\n"); sb.append("衛星個數"+location.getSatelliteNumber()+"\n"); Toast.makeText(getApplicationContext(), "當前定位模式:GPS定位", Toast.LENGTH_SHORT).show(); } else if(location.getLocType() == BDLocation.TypeNetWorkLocation){ //sb.append("省份:"+location.getProvince()+"\n"); //sb.append("市:"+location.getCity()+"\n"); //sb.append("縣:"+location.getDistrict()+"\n"); Toast.makeText(getApplicationContext(), "當前定位模式:網絡定位", Toast.LENGTH_SHORT).show(); sb.append("地址:"+location.getAddrStr()+"\n"); } logMsg(sb.toString()); System.out.println(sb); } @Override public void onReceivePoi(BDLocation poiLocation) { if(poiLocation == null) { return ; } Toast.makeText(getApplicationContext(), "嘗試得到周圍興趣點...", Toast.LENGTH_LONG).show(); Toast.makeText(getApplicationContext(), "getPoi", Toast.LENGTH_LONG).show(); StringBuffer sb = new StringBuffer(256); sb.append("具體地址: "); if(poiLocation.getLocType() == BDLocation.TypeNetWorkLocation){ sb.append(poiLocation.getAddrStr()); } if(poiLocation.hasPoi()){ sb.append("Poi:"); sb.append(poiLocation.getPoi()); } else{ sb.append("noPoi"); } logMsg(sb.toString()); } } public class NotifyListener extends BDNotifyListener{ public void onNotify(BDLocation mlocation, float distance){ mVibrator01.vibrate(1000); } } }
數據類
<!-- lang: java --> // Data.java package com.example.location; public class Data { public static String num = "0"; public static String getNum(){ return num; } public static void setNum(String s){ Data.num = s; } }
主程序
<!-- lang: java --> package com.example.location; import android.app.Activity; import android.app.Service; import android.os.Bundle; import android.os.Vibrator; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; public class Main extends Activity { private TextView mTv = null; private Button mStartBtn; private boolean mIsStart; private Vibrator mVibrator01 = null; private LocationClient mLocClient; public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); mTv = (TextView)findViewById(R.id.tv); mStartBtn = (Button)findViewById(R.id.btn_start); mIsStart = false; mLocClient = ((LocationDemoActivity)getApplication()).mLocationClient; ((LocationDemoActivity)getApplication()).mTv = mTv; mVibrator01 = (Vibrator)getApplication().getSystemService(Service.VIBRATOR_SERVICE); ((LocationDemoActivity)getApplication()).mVibrator01 = mVibrator01; if(! Data.getNum().equals("0") ) { if(!mIsStart){ setLocationOption(); mLocClient.start(); mStartBtn.setText("stop"); mIsStart = true; } else{ mLocClient.stop(); mIsStart = false; mStartBtn.setText("start"); } } mStartBtn.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v){ if(!mIsStart){ setLocationOption(); mLocClient.start(); mStartBtn.setText("stop"); mIsStart = true; } else{ mLocClient.stop(); mIsStart = false; mStartBtn.setText("start"); } } }); } public void onDestroy(){ mLocClient.stop(); ((LocationDemoActivity)getApplication()).mTv = null; super.onDestroy(); } public void setLocationOption(){ LocationClientOption option = new LocationClientOption(); option.setOpenGps(true); option.setServiceName("con,baidu.location.service_v2.9"); option.setAddrType("all"); option.setPriority(LocationClientOption.GpsFirst); option.setPoiNumber(10); option.disableCache(true); mLocClient.setLocOption(option); } }
main.xml
<!-- lang: xml --> <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/btn_start" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="Start"/> <TextView android:id="@+id/tv" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="18sp" /> </LinearLayout>
AndroidMainfest.xml
<!-- lang: xml -->
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.location" android:versionCode="1" android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8" /> <permission android:name="android.permission.BAIDU_LOCATION_SERVICE" > </permission> <uses-permission android:name="android.permission.SEND_SMS" ></uses-permission> <uses-permission android:name="android.permission.RECEIVE_SMS" ></uses-permission> <uses-permission android:name="android.permission.READ_SMS"></uses-permission> <uses-permission android:name="android.permission.BAIDU_LOCATION_SERVICE" > </uses-permission> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" > </uses-permission> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" > </uses-permission> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" > </uses-permission> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" > </uses-permission> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" > </uses-permission> <uses-permission android:name="android.permission.READ_PHONE_STATE" > </uses-permission> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" > </uses-permission> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" > </uses-permission> <uses-permission android:name="android.permission.READ_LOGS" > </uses-permission> <application android:name="com.example.location.LocationDemoActivity" android:allowBackup="true" android:icon="@drawable/icon" android:label="@string/app_name" > <activity android:name=".Main" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name=".Receiver"> <intent-filter android:priority="1000"> <action android:name="android.provider.Telephony.SMS_RECEIVED"/> </intent-filter> </receiver> <service android:name="com.baidu.location.f" android:enabled="true" android:permission="android.permission.BAIDU_LOCATION_SERVICE" android:process=":remote" > </service> </application>
</manifest>