[Android] 開發一款軟體我學到了些什嗎?,android一款

來源:互聯網
上載者:User

[Android] 開發一款軟體我學到了些什嗎?,android一款
子曰:學而時習之,不亦說乎是啊,學習了要經常溫習才行;尤記得大一大二的時候自己愛上了編程;那時的我在地攤上買了一本ASP動態網站編程,還記得花了5塊錢。而後的日子我把那本書翻的幾乎成了一張張的樣子;然後結合老師講的HTML文法;自己就慢慢的搗鼓了一個班級網站出來;想想心裡還是挺激動的。這麼久過去了,VBScript 的知識忘得差不多了;以後找個機會再看看。這次寫這個是為了記錄下我最近接手的一個項目中遇到的一些第一次遇到的問題或者疑惑吧。由於項目還沒有完,所以持續更新...========================================================
作者:qiujuer
部落格:blog.csdn.net/qiujuer
網站:www.qiujuer.net
開源庫:Genius-Android
轉載請註明出處:http://blog.csdn.net/qiujuer/article/details/41849241
========================================================
讀取瀏覽器記錄

<uses-permission android:name="com.android.browser.permission.READ_HISTORY_BOOKMARKS"/>{    String string = null;    ContentResolver contentResolver = getContentResolver();    Cursor cursor = contentResolver.query(Uri.parse("content://browser/bookmarks"), new String[]{"url"}, null, null, null);    while (cursor != null && cursor.moveToNext()) {    string = cursor.getString(cursor.getColumnIndex("url"));        Log.d("debug", string == null ? "null":string);}
類比返回鍵功能1.java.lang.Runtime
Runtime runtime = Runtime.getRuntime();runtime.exec("input keyevent " + KeyEvent.KEYCODE_BACK);
2.android.app.Instrumentation
Instrumentation inst = new Instrumentation();inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
監聽開機啟動廣播
public class BootReceiver extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {            do...        }    }}
<receiver android:name=".BootReceiver">            <intent-filter>                <action android:name="android.intent.action.BOOT_COMPLETED" />            </intent-filter>        </receiver>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
判斷移動網路類型
    /**     * 判斷移動網路類型     *     * @param networkType telephonyManager.getNetworkType()     * @return 網路類型     */    static int getMobileNetworkType(int networkType) {        /*        GPRS       2G(2.5) General Packet Radia Service 114kbps        EDGE       2G(2.75G) Enhanced Data Rate for GSM Evolution 384kbps        UMTS      3G WCDMA 聯通3G Universal Mobile Telecommunication System 完整的3G移動通訊技術標準        CDMA     2G 電信 Code Division Multiple Access 碼分多址        EVDO_0   3G (EVDO 全程 CDMA2000 1xEV-DO) Evolution - Data Only (Data Optimized) 153.6kps - 2.4mbps 屬於3G        EVDO_A  3G 1.8mbps - 3.1mbps 屬於3G過渡,3.5G        1xRTT      2G CDMA2000 1xRTT (RTT - 無線電傳輸技術) 144kbps 2G的過渡,                HSDPA    3.5G 高速下行分組接入 3.5G WCDMA High Speed Downlink Packet Access 14.4mbps        HSUPA    3.5G High Speed Uplink Packet Access 高速上行鏈路分組接入 1.4 - 5.8 mbps        HSPA      3G (分HSDPA,HSUPA) High Speed Packet Access        IDEN      2G Integrated Dispatch Enhanced Networks 整合數字增強型網路 (屬於2G,來自維基百科)        EVDO_B 3G EV-DO Rev.B 14.7Mbps 下行 3.5G        LTE        4G Long Term Evolution FDD-LTE 和 TDD-LTE , 3G過渡,升級版 LTE Advanced 才是4G        EHRPD  3G CDMA2000向LTE 4G的中間產物 Evolved High Rate Packet Data HRPD的升級        HSPAP  3G HSPAP 比 HSDPA 快些        */        switch (networkType) {            case TelephonyManager.NETWORK_TYPE_GPRS:            case TelephonyManager.NETWORK_TYPE_EDGE:            case TelephonyManager.NETWORK_TYPE_CDMA:            case TelephonyManager.NETWORK_TYPE_1xRTT:            case TelephonyManager.NETWORK_TYPE_IDEN:                return Note.NETWORK_TYPE_2G;            case TelephonyManager.NETWORK_TYPE_UMTS:            case TelephonyManager.NETWORK_TYPE_EVDO_0:            case TelephonyManager.NETWORK_TYPE_EVDO_A:            case TelephonyManager.NETWORK_TYPE_HSDPA:            case TelephonyManager.NETWORK_TYPE_HSUPA:            case TelephonyManager.NETWORK_TYPE_HSPA:            case TelephonyManager.NETWORK_TYPE_EVDO_B:            case TelephonyManager.NETWORK_TYPE_EHRPD:            case TelephonyManager.NETWORK_TYPE_HSPAP:                return Note.NETWORK_TYPE_3G;            case TelephonyManager.NETWORK_TYPE_LTE:                return Note.NETWORK_TYPE_4G;            default:                return Note.NETWORK_TYPE_UNKNOWN;        }    }
讀取通話記錄
final Cursor cursor = cr.query(CallLog.Calls.CONTENT_URI, new String[] {CallLog.Calls.NUMBER, CallLog.Calls.CACHED_NAME,CallLog.Calls.TYPE, CallLog.Calls.DATE }, null, null,CallLog.Calls.DEFAULT_SORT_ORDER);final Cursor cursor = cr.query(資料庫表名,取得的資料數組(裡邊包含欄位名稱),條件,參數組,排序等資訊) //這就相當於一條SQL語句//取得所有通話資訊  這裡邊稍微有點複雜for (int i = 0; i < cursor.getCount(); i++) {    cursor.moveToPosition(i);    str = cursor.getString(0);    type = cursor.getInt(2);    if (type == 3) {    tel = str;    break;    }} //取得值final Cursor cursor = cr.query(CallLog.Calls.CONTENT_URI, new String[] {CallLog.Calls.NUMBER }, "type=3", null,"date desc limit 1");//這個就是取得最近的一次未接來電的電話號碼。if(cursor.moveToFirst()){    tel = cursor.getString(0);}這個取值之後和最上邊的值是一樣的。CallLog.Calls.CONTENT_URI (通話記錄資料庫)CallLog.Calls.NUMBER (通話號碼)CallLog.Calls.CACHED_NAME (通話人姓名)CallLog.Calls.TYPE (通話類型)通訊記錄有三種類型:       來電:CallLog.Calls.INCOMING_TYPE (常量值:1)       已撥:CallLog.Calls.OUTGOING_TYPE(常量值:2)       未接:CallLog.Calls.MISSED_TYPE(常量值:3)       其實還有一種類型-拒接 系統未給出常量。但經測試後得出結論為4.CallLog.Calls.DATE (通話時間) CallLog.Calls.CONTENT_URI : 等價於:Uri.parse("content://call_log/calls");
            //過濾未接電話            //通話時間長度0~11秒            //時間為:開始響鈴~結束時間            String whereStr = CallLog.Calls.TYPE + "!=3 AND " + CallLog.Calls.DURATION + ">0 AND " + CallLog.Calls.DURATION + "<11 AND " + CallLog.Calls.DATE + ">" + startTime + " AND " + CallLog.Calls.DATE + "<" + endTime;            //倒敘並查詢            Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI, new String[]{CallLog.Calls.NUMBER}, whereStr, null, null);            bFlag = cursor.getCount() > 0;            cursor.close();
需要聲明的許可權 在AndroidManifest.xml中加入        <uses-permission android:name="android.permission.READ_CONTACTS" /> 讀記錄        <uses-permission android:name="android.permission.WRITE_CONTACTS" /> 寫記錄這兩條是和<application>節點同級的 如果想加入呼叫許可權,還要加上     <uses-permission android:name="android.permission.CALL_PHONE" />還有傳送簡訊許可權     <uses-permission android:name="android.permission.SEND_SMS" />還有串連互連網許可權     <uses-permission android:name="android.permission.INTERNET" />
再次點擊返回鍵退出程式
    // 複寫返回事件    public boolean onKeyDown(int keyCode, KeyEvent event) {        if (keyCode == KeyEvent.KEYCODE_BACK) {            if ((System.currentTimeMillis() - mExitTime) > 2000) {                Toast.makeText(this, R.string.label_press_main, Toast.LENGTH_SHORT).show();                mExitTime = System.currentTimeMillis();            } else {                finish();            }            return true;        } else            return super.onKeyDown(keyCode, event);    }
ActiveAndroid 與 Gson 衝突

問題描述:ActiveAndroid  Model 中無法通過 Gson 進行執行個體化,原因是 ActiveAndroid  Model 中含有無法通過 Gson 轉換的欄位;

解決方案:在 ActiveAndroid  Model 中對指定的類進行過濾:
import com.google.gson.ExclusionStrategy;import com.google.gson.FieldAttributes;/** * Created by QiuJu * on 2014/9/16. */public class SpecificClassExclusionStrategy implements ExclusionStrategy {    private final Class<?> excludedThisClass;    private final Class<?> excludedThisClassFields;    /**     * 過濾器初始化     *     * @param excludedThisClass       該類和繼承自該類的對象執行個體將被忽略     * @param excludedThisClassFields 該類的屬性將不被序列化     */    public SpecificClassExclusionStrategy(Class<?> excludedThisClass, Class<?> excludedThisClassFields) {        this.excludedThisClass = excludedThisClass;        this.excludedThisClassFields = excludedThisClassFields;    }    @Override    public boolean shouldSkipClass(Class<?> clazz) {        return clazz != null && (clazz.equals(excludedThisClass) || shouldSkipClass(clazz.getSuperclass()));    }    @Override    public boolean shouldSkipField(FieldAttributes f) {        return f.getDeclaringClass().equals(excludedThisClassFields);    }}
        GsonBuilder gsonBuilder = new GsonBuilder();        gsonBuilder.setExclusionStrategies(new SpecificClassExclusionStrategy(null, Model.class));        gsonBuilder.setDateFormat("yyyy-MM-dd HH:mm:ss.SSS");        Gson gson = gsonBuilder.create();        NotePutModel model = new NotePutModel();        model.setPhoneId(Settings.getPhoneId());        model.setPhoneMark(Settings.getPhoneMark());        model.setNotes(Note.getAll(false));        JSONObject jsonObject = null;        try {            jsonObject = new JSONObject(gson.toJson(model));        } catch (JSONException e) {            e.printStackTrace();        }
擷取基站資訊
    public static String getCellPos(TelephonyManager mTelephonyManager) {        String result = null;        try {            // 傳回值MCC + MNC            String operator = mTelephonyManager.getNetworkOperator();            if (operator != null && operator.length() > 0) {                int mcc = Integer.parseInt(operator.substring(0, 3));                int mnc = Integer.parseInt(operator.substring(3));                // 中國移動和中國聯通擷取LAC、CID的方式                GsmCellLocation location = (GsmCellLocation) mTelephonyManager.getCellLocation();                int lac = location.getLac();                int cellId = location.getCid();                result = " MCC = " + mcc + "\t MNC = " + mnc + "\t LAC = " + lac + "\t CID = " + cellId;                // 中國電信擷取LAC、CID的方式                /*CdmaCellLocation location1 = (CdmaCellLocation) mTelephonyManager.getCellLocation();                lac = location1.getNetworkId();                cellId = location1.getBaseStationId();                cellId /= 16;*/                // 擷取鄰區基站資訊                List<NeighboringCellInfo> infos = mTelephonyManager.getNeighboringCellInfo();                StringBuilder sb = new StringBuilder("Size: " + infos.size() + "\n");                for (NeighboringCellInfo info1 : infos) { // 根據鄰區總數進行迴圈                    sb.append(" LAC : ").append(info1.getLac()); // 取出當前鄰區的LAC                    sb.append(" CID : ").append(info1.getCid()); // 取出當前鄰區的CID                    sb.append(" BSSS : ").append(-113 + 2 * info1.getRssi()).append("\n"); // 擷取鄰區基站訊號強度                }                result += " Neighbor:" + sb.toString();            }        } catch (Exception e) {            e.printStackTrace();        }        return result;    }
Java Android Date Gson Json 解析字串String時間中含有 T 報錯的問題:問題描述:時間字串中含有“T”字元,無法進行對應的格式化。出現:ParseException: unparseable date 
介面方案:設定格式串: “yyyy-MM-dd'T'HH:mm:ss“


   public static Gson getNoteReplyGson() {        GsonBuilder gsonBuilder = new GsonBuilder();        gsonBuilder.setExclusionStrategies(new SpecificClassExclusionStrategy(null, Model.class));        gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");        return gsonBuilder.create();    }
百度定位問題問題描述:在使用百度定位的時候出現,調用 LocationClient.start() 後返回 False 且,不回調回呼函數;但是在有一部手機上能正常使用。
解決辦法:將預設的 JNI(armeabi) 檔案,拷貝為全平台。

附上擷取百度地圖的一個封裝類:
class LocationBuilder implements BDLocationListener {    CountDownLatch mLatch;    LocationClient mClient;    Location mLocation;    public LocationBuilder(final Context context) {        this.mLatch = new CountDownLatch(1);        this.mLocation = new Location();        ToolKit.runOnMainThreadSync(new Runnable() {            @Override            public void run() {                mClient = buildLocation(context);                mClient.registerLocationListener(LocationBuilder.this);                mClient.start();            }        });        try {            this.mLatch.await(15, TimeUnit.SECONDS);        } catch (InterruptedException e) {            e.printStackTrace();            this.stop();        }    }    public Location getLocation() {        Location location = mLocation;        mLocation = null;        return location;    }    private void stop() {        try {            mClient.unRegisterLocationListener(this);            mClient.stop();        } catch (Exception e) {            e.printStackTrace();        }    }    private LocationClient buildLocation(Context context) {        LocationClient locationClient = new LocationClient(context);     //聲明LocationClient類        LocationClientOption option = new LocationClientOption();        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//設定定位元模式        option.setCoorType("bd09ll");//返回的定位結果是百度經緯度,預設值gcj02        option.setScanSpan(1000);//設定發起定位請求的間隔時間為1000ms        option.setIsNeedAddress(true);        locationClient.setLocOption(option);        return locationClient;    }    @Override    public void onReceiveLocation(BDLocation location) {        this.stop();        try {            if (mLatch != null) {                int[] codes = new int[]{61, 65, 66, 68, 161};                if (Arrays.binarySearch(codes, location.getLocType()) >= 0) {                    mLocation.setLongitude(location.getLongitude());                    mLocation.setLatitude(location.getLatitude());                    mLocation.setRadius(location.getRadius());                    mLocation.setAddress(location.getAddrStr());                    mLocation.setAltitude(location.getAltitude());                }                mLatch.countDown();            }        } catch (Exception e) {            e.printStackTrace();        }    }}
IIS 伺服器下載apk檔案報404錯檔案路徑什麼都對,可就是提示404錯誤,最後問題出在了IIS的MIME上,按照下面的辦法即可解決。

========================================================
作者:qiujuer
部落格:blog.csdn.net/qiujuer
網站:www.qiujuer.net
開源庫:Genius-Android
轉載請註明出處:http://blog.csdn.net/qiujuer/article/details/41849241
========================================================

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.