Android Development Tips Summary (ii)

Source: Internet
Author: User

1. Access data for preferences

Write a class, put the access method inside, and then make the call outside

public class Prefsutils {

private static final String prefs_name= "Com.yomoto.util.OtherPrefs";

The name deposited here is the address: data/data/Project Package name/shared_prefs/prefs_name

Get the data in the preferences

public static String GetValue (Context context,string key,string defaultvalue) {

Sharedpreferences prefs=context.getsharedpreferences (Prefs_name, context.mode_private);

if (prefs==null) return "Unknow";

Return prefs.getstring (key, DefaultValue);

}

Storing data in Preferences

public static void SetValue (Context context,string key,string value) {

Sharedpreferences prefs=context.getsharedpreferences (Prefs_name, context.mode_private);

Editor Editor=prefs.edit ();

if (editor==null) return;

Editor.putstring (key, value);

Editor.commit ();

}}

Calling methods in the outside preferences:

Get the data:

0 is the default value when the value of the Intro1 field is not in the case of a value

Prefsutils.getvalue (Baseapplication.this, "Intro1", "0");

Save data:

Prefsutils.setvalue (Logoactivity.this, "Intor1", "1");

2. How to determine the network situation, which can be put into the tool class

public static Boolean isnetworkavailable (Contextcontext) {

try{

Connectivitymanager cm = (Connectivitymanager) context

. Getsystemservice (Context.connectivity_service);

Get Network Information

Networkinfo info = Cm.getactivenetworkinfo ();

Returns the detected network status

Return (info!=null&&info.isconnected ());

}catch (Exceptione) {

E.printstacktrace ();

Returnfalse;

}

}

3. Determine if the SD card exists, can be placed in the tool class method

public static Boolean Hassdcard () {

String state = Environment.getexternalstoragestate ();

if (State.equals (environment.media_mounted)) {

return true;

}else{

return false;

}}

4. Several common settings in activity

The soft keyboard does not eject by default, before Setcontentview

1) GetWindow (). Setsoftinputmode (WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

Set the interface to full screen before Setcontentview

2) GetWindow (). SetFlags (Windowmanager.layoutparams.flag_fullscreen,windowmanager.layoutparams.flag_fullscreen);

or set in manifest, Android:theme= "@android: Style/theme.translucent.notitlebar.fullscreen"

5. Embedding the GridView and ListView in the ScrollView

public class Navigationgridview extends gridview{

Public Navigationgridview (Contextcontext,attributesetattrs) {

Super (CONTEXT,ATTRS);

}

Publicnavigationgridview (Contextcontext) {

Super (context);

}

Publicnavigationgridview (Contextcontext,attributesetattrs,intdefstyle) {

Super (Context,attrs,defstyle);

}

@Override

Publicvoidonmeasure (Intwidthmeasurespec,intheightmeasurespec) {

int expandspec = Measurespec.makemeasurespec (

Integer.max_value>>2,measurespec.at_most);

Super.onmeasure (WIDTHMEASURESPEC,EXPANDSPEC);

}}

The ListView, like the GridView, overrides the same method.

6.Android Life-cycle issues

1) After the software starts, the first time will perform baseapplication and start activity, press the return key to exit the re-open when the baseapplication is not executed, only kill the process, will execute baseapplication and activity .

7. Grammatical problems

1. Set the syntax for date formatting

Private SimpleDateFormat format;

format = new SimpleDateFormat ("yyyy mm month DD Day HH:mm:ss");

Date current = new Date (System.currenttimemillis ());

String str = Format.format (current);

2. Set the return of the control word in the phone

Add \ n to the place where you need to enter

For example: The effect set in Strings.xml is:

<string name= "Vip_content_small11" > Lower prices than ordinary users \ \ More kinds of coupons more favorable than the group \ \ more Convenient </string>

8. Summary of additional knowledge points

1) Mobile phone screen

Xiaomi 1s phone screen height: 854 width: 480

Samsung 5.8 inch Mobile Screen Height: 960 width: 540

9. Problem solving and handling

1) ListView in ScrollView sometimes after adding data, the ListView will get the focus, causing the interface to display from the ListView, at this time in Listview.setadapter (adapter);

Listview.setfocusable (false); To resolve the issue of focus.

10. The phone jumps directly to the webpage

Uriuri=uri.parse ("http://appadmin.ibinggo.com/adm_program/modules/downloads/get_file.php?file_id=7");

Intentintent=newintent (Intent.action_view,uri);

StartActivity (Intent);

One. Message with the use of handler

Messagemessage=mhandler.obtainmessage ();//After the data has been downloaded, send a data to handler to update the UI.

Message.what=1;

Message.sendtotarget ();

Handler Mhandler = new Handler () {

@Override

public void Handlemessage (messagemsg) {

Super.handlemessage (msg);

if (msg.what==1) {}

}}

Android Basics Points

1) The Android UI update is done in the main thread.

2) <application

Android:allowbackup= "true"

android:icon= "@drawable/ic_donga"

Make sure to write down its name here.

Android:name= "Com.qianxunnt.xinlife.activity.BaseApplication"

Android:label= "@string/app_name"

Android:theme= "@style/theme.sherlock"

>

3) split strings based on conditions

String[] s = t.split ("sess_id="); Split field

4) Gson Gson =new Gson (); Parsing JSON to Localcouponslist

Working with collection data

Mcoupons = Gson.fromjson (t, new typetoken<list<couponsinfo>> () {}.gettype ());

Working with separate class data

UpdateTime = Gson.fromjson (t, Updatetimeinfo.class);

5) Notificationmanager manager = (Notificationmanager) getsystemservice (Context.notification_service);

Create a notification

Notification Notification = new Notification ();

Set the icon that appears at the top of the phone's status bar

Notification.icon = R.drawable.ic_donga;

When the current notification is placed on the status bar, the prompt content

Notification.tickertext = "You have successfully upgraded to a VIP user!" ";

Add a sound hint

Notification.defaults = Notification.default_sound;

Let the notification click the Vanishing button

Notification.flags |= Notification.flag_auto_cancel;

Intent Intent = new Intent (newcouponsdetailactivity.this, Mainactivity.class);

Pendingintent pendingintent = pendingintent.getactivity (newcouponsdetailactivity.this, 0, intent, PendingIntent.FLAG _one_shot);

Click on the status bar icon to show the message settings

Notification.setlatesteventinfo (Newcouponsdetailactivity.this, "Shopping Tips", "You have successfully upgraded to VIP users, using the term" +usetime+ "Days! ", pendingintent);

Manager.notify (1,notification);

6) String Sdest=urldecoder.decode (Couponscontent.getcontent (), "utf-8");

No execution baseapplication so no value

Kuaicanwebview.getsettings (). Setdefaulttextencodingname ("UTF-8");

Kuaicanwebview.loaddatawithbaseurl (Null,sdest, "text/html", "UTF-8", null);

7) Set a simple animation for the control in your code

Animation Animation = new Translateanimation (one*currindex, one*arg0, 0, 0);//Obviously this is relatively concise, with only one line of code.

Animation.setfillafter (TRUE);//true: The picture stops at the end of the animation

Animation.setduration (300);

Imageview.startanimation (animation);

8) Setting of List dialog

New Alertdialog.builder (this). Settitle ("Error Selection")

. Setitems (

New string[] {"Phone error", "Address Error", "Map location Error"},//list contents

New Dialoginterface.onclicklistener () {//TAP Listen

@Override

public void OnClick (

Dialoginterface dialog, int which) {//click location

}})

. Setnegativebutton ("OK", NULL)

. Show ();

9) Calculate distance according to latitude and longitude

public static double Distancebylnglat (double lng1, double lat1, double lng2,double lat2) {

Double RADLAT1 = lat1 * MATH.PI/180;

Double RADLAT2 = lat2 * MATH.PI/180;

Double A = RADLAT1-RADLAT2;

Double b = lng1 * math.pi/180-lng2 * math.pi/180;

Double s = 2 * Math.asin (MATH.SQRT (Math.pow (Math.sin (A/2), 2)

+ Math.Cos (RADLAT1) * Math.Cos (RADLAT2)

* MATH.POW (Math.sin (B/2), 2)));

s = S * 6378137.0;

s = Math.Round (S * 10000)/10000;

return s;

}

10) Two ways to monitor the return button

(1) @Override

public void onbackpressed () {

TODO auto-generated Method Stub

Super.onbackpressed ();

}

(2) Public boolean onKeyDown (int keycode, keyevent event) {

if (keycode = = Keyevent.keycode_back)

{}}

11)

Xactivitieslistview ListView = (xactivitieslistview) parent; Notificationinfo coupon = (notificationinfo) listview.getitematposition (postion);//Main method

12) Set the activity's horizontal screen and vertical screen

android:screenorientation= "Landscape" property (landscape is Landscape, portrait is portrait)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.