[Android] What have I learned to develop a software ?, Android
Zi Yue: Learn and study at the same time, not to mention, yes, it is only necessary to study frequently after learning; especially remember that I fell in love with programming when I was a sophomore; at that time, I bought an ASP dynamic website programming on the stall, and I still remember spending 5 RMB. In the days that followed, I turned the book into a simple one. Then I combined the teacher's HTML syntax, and slowly started a class website; think about it. After so long, the knowledge of VBScript is almost forgotten; I will try again later. This is to record some of the first problems or doubts I encountered in a recently claimed project. As the project is not complete, it is constantly updated... ========================================================== ======================
Author: qiujuer
Blog: blog.csdn.net/qiujuer
Website: www.qiujuer.net
Open-source Library: Genius-Android
Reprinted please indicate the source: http://blog.csdn.net/qiujuer/article/details/41849241
========================================================== ======================
Read browser history
<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);}
Simulate the return key function 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);
Listen to boot Broadcast
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" />
Determine the mobile network type
/*** Determine the mobile network type ** @ param networkType telephonyManager. getNetworkType () * @ return network type */static int getMobileNetworkType (int networkType) {/* GPRS 2G (2.5) General Packet Radia Service 114 kbps EDGE 2G (2.75G) enhanced Data Rate for GSM Evolution 384 kbps UMTS 3g wcdma Unicom 3G Universal Mobile Telecommunication System complete 3G Mobile communication technology standard CDMA 2G Telecom Code Division Multiple Access EVDO_0 3G (EVDO full Process of CDMA 2000 1xEV-DO) evolution-Data Only (Data Optimized) 153.6kps-2.4 mbps belongs to 3G EVDO_A 3G 1.8 mbps-3.1 mbps belongs to 3G transition, 3.5G 1 xRTT 2G cdma 2000 1 xRTT (RTT-radio transmission technology) 144 kbps 2G transition, HSDPA 3.5G High-Speed Downlink grouping Access 3.5g wcdma High Speed Downlink Packet Access 14.4 mbps HSUPA 3.5G High Speed Uplink Packet Access High Speed Uplink grouping Access 1.4-5.8 mbps HSPA 3G (divided into HSDPA, HSUPA) High Speed Packet Access IDEN 2G Integrated Dispatch Enhanced Networks Integrated digital Reinforced Network (belonging to 2G, from Wikipedia) EVDO_ B 3G EV-DO Rev. B 14.7 Mbps downlink 3.5G LTE 4G Long Term Evolution FDD-LTE and TDD-LTE, 3G transition, the upgraded version of LTE Advanced is the intermediate product of 4g ehrpd 3G cdma 2000 to LTE 4G Evolved High Rate Packet Data HRPD. The upgraded version of heat-tolerant AP 3G is faster than that of 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 ;}}
Read call records
Final Cursor cursor = cr. query (CallLog. CILS. CONTENT_URI, new String [] {CallLog. CILS. NUMBER, CallLog. CILS. CACHED_NAME, CallLog. CILS. TYPE, CallLog. CILS. DATE}, null, null, CallLog. CILS. DEFAULT_SORT_ORDER); final Cursor cursor = cr. query (database table name, obtained data array (including field names), conditions, parameter groups, sorting, and other information) // This is equivalent to an SQL statement // It is a little complicated to obtain all the call information here for (int I = 0; I <cursor. getCount (); I ++) {cursor. moveToPosition (I); str = cursor. getStr Ing (0); type = cursor. getInt (2); if (type = 3) {tel = str; break ;}// obtain the final Cursor cursor = cr. query (CallLog. CILS. CONTENT_URI, new String [] {CallLog. CILS. NUMBER}, "type = 3", null, "date desc limit 1"); // This is the NUMBER of the last missed call. If (cursor. moveToFirst () {tel = cursor. getString (0);} the value is the same as the top value. CallLog. CILS. CONTENT_URI (call record database) CallLog. CILS. NUMBER (call NUMBER) CallLog. CILS. CACHED_NAME (caller name) CallLog. CILS. there are three types of call records: call log. CILS. INCOMING_TYPE (Constant Value: 1) dialed: CallLog. CILS. OUTGOING_TYPE (Constant Value: 2) not connected: CallLog. CILS. MISSED_TYPE (Constant Value: 3) is actually another type-the rejection system does not provide a constant. However, after the test, the conclusion is 4. callLog. CILS. DATE (call time) CallLog. CILS. CONTENT_URI: equivalent to: Uri. parse ("content: // call_log/CILS ");
// Filter out missed calls. // The Call duration ranges from 0 ~ 11 S // time: Start to ring the bell ~ End Time String whereStr = CallLog. CILS. TYPE + "! = 3 AND "+ CallLog. CILS. DURATION + "> 0 AND" + CallLog. CILS. DURATION + "<11 AND" + CallLog. CILS. DATE + ">" + startTime + "AND" + CallLog. CILS. DATE + "<" + endTime; // flashback and query Cursor cursor = context. getContentResolver (). query (CallLog. CILS. CONTENT_URI, new String [] {CallLog. CILS. NUMBER}, whereStr, null, null); bFlag = cursor. getCount ()> 0; cursor. close ();
The permission to be declared is in AndroidManifest. add <uses-permission android: name = "android. permission. READ_CONTACTS "/> Read record <uses-permission android: name =" android. permission. WRITE_CONTACTS "/> write records are the same as those of the <application> node. If you want to add the call permission, you must add <uses-permission android: name =" android. permission. CALL_PHONE "/> has the permission to send text messages <uses-permission android: name =" android. permission. SEND_SMS "/> permission to connect to the Internet <uses-permission android: name =" android. permission. INTERNET "/>
Click the return key again to exit the program.
// Return the event 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 conflicts with Gson
Problem description:ActiveAndroid Model cannot be instantiated through Gson because ActiveAndroid Model contains fields that cannot be converted by Gson;
Solution:Filter the specified class in 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; /*** filter initialization ** @ param excludedThisClass and the object instance inherited from this Class will be ignored * @ param excludedThisClassFields the attributes of this Class will not be serialized */public SpecificClassExclusionStrategy (Class <?> ExcludedThisClass, Class <?> Extends) {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(); }
Obtain Base Station Information
Public static String getCellPos (TelephonyManager mTelephonyManager) {String result = null; try {// return value 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); // The method used by China Mobile and China Unicom to obtain the LAC and CID is GsmCellLocation = (GsmCellLocation) mTelephonyManager. getCellLocation (); int lac = location. getLac (); int cellId = location. getCid (); result = "MCC =" + mcc + "\ t MNC =" + mnc + "\ t LAC =" + lac + "\ t CID =" + cellId; // China Telecom's method of obtaining the LAC and CID/* CdmaCellLocation location1 = (CdmaCellLocation) mTelephonyManager. getCellLocation (); lac = location1.getNetworkId (); cellId = location1.getBaseStationId (); cellId/= 16; * // obtain the information List of neighboring base stations <NeighboringCellInfo> infos = mTelephonyManager. getNeighboringCellInfo (); StringBuilder sb = new StringBuilder ("Size:" + infos. size () + "\ n"); for (NeighboringCellInfo info1: infos) {// cyclically sb according to the total number of neighboring areas. append ("LAC :"). append (info1.getLac (); // retrieves the LAC sb of the current neighboring region. append ("CID :"). append (info1.getCid (); // retrieves the CID sb of the current neighboring area. append ("BSSS :"). append (-113 + 2 * info1.getarg ()). append ("\ n"); // obtain the signal strength of the neighboring base station} result + = "Neighbor:" + sb. toString () ;}} catch (Exception e) {e. printStackTrace ();} return result ;}
Java Android Date Gson Json parses String time and contains T errors:
Problem description:The time string contains the "T" character and cannot be formatted accordingly. Appearance: ParseException: unparseable date
Interface solution:Set the format string:
"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(); }
Baidu locating problems
Problem description:When Baidu is used for locating, the system returns False after LocationClient. start () is called, and the callback function is not called, but can be used normally on a mobile phone.
Solution:Set the default
JNI (armeabi)File, which is copied to the entire platform.
The following is an encapsulation class for obtaining Baidu maps:
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 LocationCli Ent buildLocation (Context context) {LocationClient locationClient = new LocationClient (context); // declare LocationClient class LocationClientOption option = new LocationClientOption (); option. setLocationMode (LocationClientOption. locationMode. hight_Accuracy); // sets the positioning mode option. setCoorType ("bd09ll"); // The return result is Baidu longitude and latitude. The default value is gcj02 option. setScanSpan (1000); // set the interval between initiating a request for locating to 1000 ms option. setIsNeedAddress (true); locationC Lient. setLocOption (option); return locationClient;} @ Override public void onid elocation (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. setlongpolling (location. getlongpolling (); mLocation. setLatitude (location. getLatitude (); mLocation. setRadius (location. getRadius (); mLocation. setAddress (location. getAddrStr (); mLocation. setAltitude (location. getAltitude ();} mLatch. countDown () ;}} catch (Exception e) {e. printStackTrace ();}}}
Error 404 is reported when the IIS server downloads the apk file.
The file path is correct, but the Error 404 is prompted. The final problem lies in the MIME of IIS. Follow the methods below to solve the problem.
========================================================== ======================
Author: qiujuer
Blog: blog.csdn.net/qiujuer
Website: www.qiujuer.net
Open-source Library: Genius-Android
Reprinted please indicate the source: http://blog.csdn.net/qiujuer/article/details/41849241
========================================================== ======================