Android Tips Summary 1

Source: Internet
Author: User

0, Android completely quit the method of referencing the program

1) Local method of Dalvik VM

    Android.os.Process.killProcess (Android.os.Process.myPid ()); Get PID    

2 ) Task Manager Method

The first thing to illustrate is that the method executes at Android 1.5 API level above 3 talents enough. Need permission at the same time

   Get Activitymanager instance    activitymanager am = (activitymanager) getsystemservice (context.activity_service);    Am.restartpackage (Getpackagename ());
The system will be, under the package, all processes. Service, all killed. You're going to be able to kill yourself. Add a permission statement:

  <!--rights Statement--  <uses-permission android:name= "Android.permission.RESTART_PACKAGES" ></ Uses-permission>

3) According to the activity's declaration cycle  

we know that the Android form class provides a history stack. We are able to use the principle of the stack of ingenious implementation, here we in a form opens B form in Intent directly add the flag intent.flag_activity_clear_top, Opening B will clear all activity for that process space.

Use the following code in a form to invoke the B form

    Intent Intent = new Intent ();    Intent.setclass (Android123.this, cwj.class);    Intent.setflags (intent.flag_activity_clear_top);  Note The bank's flag setting    startactivity (Intent);

the next step in the B form is to exit directly using the Finish method.

4) Use Singletask mode

Set the main activity (recorded as mainactivity) to Singletask mode, you can jump to mainactivity if you need to exit the program. Then call the finish function to exit the program.

5) Register all activity with a broadcast that receives the finish message :

@Overrideprotected void OnCreate (Bundle savedinstancestate) {    super.oncreate (savedinstancestate);    Intentfilter filter = new Intentfilter ();    Filter.addaction ("Finish");    Registerreceiver (mfinishreceiver, filter);    ......} Private Broadcastreceiver Mfinishreceiver = new Broadcastreceiver () {    @Override public    void OnReceive (Context Context, Intent Intent) {        if ("Finish". Equals (Intent.getaction ())) {            finish ();}}    ;

6) Define an activity stack by itself , and just use a singleton activity stack to manage all activity, and add a way to get out of all activity. The code is as follows:

public class Screenmanager {private static stack<activity> activitystack;    private static Screenmanager instance;            Private Screenmanager () {} public static Screenmanager Getscreenmanager () {if (instance = = null) {        Instance = new Screenmanager ();    } return instance; }//exit stack top activity public void popactivity (activity activity) {if (activity! = null) {activity.fi            Nish ();            Activitystack.remove (activity);        activity = NULL; }}//get current stack top activity public activity currentactivity () {Activity activity = activitystack.lastelement ()        ;    return activity; }//pushes the current Activity into the stack public void pushactivity (activity activity) {if (Activitystack = = null) {A        Ctivitystack = new stack<activity> ();    } activitystack.add (activity);      }//exit stack all activity public void Popallactivityexceptone (Class cls) {while (true) {      Activity activity = currentactivity ();            if (activity = = null) {break;            } if (Activity.getclass (). Equals (CLS)) {break;        } popactivity (activity); }    }}

extension: Press two times return key to exit the program:
    Listen for the return key, click two times to exit    @Override public    boolean onKeyDown (int keycode, keyevent event) {        if (keycode = = Keyevent.keycode_back) {            onbackcodepressed ();        }        return false;    }       private int mpressedtime = 0;    private void onbackcodepressed () {        //indicates first click        if (mpressedtime = = 0) {            toast.maketext (this, "continuous Click to Exit program", Toast.length_short). Show ();            ++mpressedtime;                       New Thread () {                @Override public                void Run () {                    try {                        sleep ()                    } catch (Exception e) {                        LOG.E (TAG, e.tostring ());                    } finally {                        mpressedtime = 0;}}}            ;        } else {            android.os.Process.killProcess ( Android.os.Process.myPid ());        }    }

1. Draw the Border
<?xml version= "1.0" encoding= "Utf-8"?

><!--Draw Border--><layer-list xmlns:android= "http://schemas.android.com/apk/res/android" > <item android:right= "0DP" > <shape android:shape= "Rectangle" > <solid android:color= "@color/white"/ > </shape> </item> <item android:bottom= "1DP" android:left= "1DP" android:right= "1DP" android:top= "1DP" > <shape android:shape= "Rectangle" > <solid Android:color= "@color/orchid"/> </shape> </item> </layer-list>


2, infer whether the string is null in Android, or whether the string is empty, can be used directly

textutils.isempty (str);

Textutils.isempty Source code:

public static Boolean isEmpty (Charsequence str) {    if (str = = NULL | | str.length () = = 0)        return true;    else        return false;}

3. Extrapolate the vertical screen and switch:
if (This.getresources (). GetConfiguration (). Orientation = = Configuration.orientation_landscape) {    Setcontentview (r.layout. horizontal screen);} else if (this.getresources (). GetConfiguration (). Orientation = = configuration.orientation_portrait) {    Setcontentview (r.layout. Vertical screen);}

4, replace the repeated Findviewbyid writing:
   Public <T> T $ (int viewID) {        return (t) Findviewbyid (ViewID);    }

Usage examples:
    TextView A;    A = $ (r.id.a_id);

5. Get the current time of the system and format itmethod One:
        SimpleDateFormat formatter = new SimpleDateFormat (                "yyyy mm month DD day   HH:mm:ss");        Date curdate = new Date (System.currenttimemillis ());//Gets the current time        String str = Formatter.format (curdate);

Method Two:
    String label = Dateutils.formatdatetime (             getapplicationcontext (),             System.currenttimemillis (),             Dateutils.format_show_time                     | Dateutils.format_show_date                     | Dateutils.format_abbrev_all);


6, Get a string (containing the Chinese string) with the first letter of the alphabet:
Private final static int[] Li_secposvalue = {1601, 1637, 1833, 2078, 2274, 2302, 2433, 2594, 2787, 3106, 3212, 347 2, 3635, 3722, 3730, 3858, 4027, 4086, 4390, 4558, 4684, 4925, 5249, 5590};p rivate final static string[] Lc_firstl etter = {"A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "W" , "X", "Y", "Z"};//gets the first letter of each String/** * Gets the first letter of a given Chinese character, that is, the initials * @param Chinese given kanji * @return the initials of a given Chinese character */public String GetFirst    Letter (String Chinese) {if (Chinese = = NULL | | Chinese.trim (). Length () = = 0) {return "";    } Chinese = this.conversionstr (Chinese, "GB2312", "iso8859-1"); if (Chinese.length () > 1) {//inference is not a chinese character int li_sectorcode = (int) chinese.charat (0);//Kanji Area code int Li_positi Oncode = (int) chinese.charat (1);        Chinese character bit code li_sectorcode = li_sectorcode-160;        Li_positioncode = li_positioncode-160; int Li_secposcode = Li_sectorcode * + li_positioncode;        Chinese character Location Codeif (Li_secposcode > && Li_secposcode < 5590) {for (int i = 0; i < i++) { if (Li_secposcode >= li_secposvalue[i] && Li_secposcode < Li_secposvalue[i + 1])                    {Chinese = lc_firstletter[i];                Break }}}} else {//non-kanji character, form symbol or ASCII code Chinese = this.conversionstr (Chinese, "iso8859-1", "GB2312")            ;        Chinese = chinese.substring (0, 1); }} return Chinese;} /** * String Encoding conversion * @param STR to convert encoded String * @param charsetname Original encoding * @param tocharsetname converted encoding * @return encoded converted string */priv Ate string Conversionstr (String str, string charsetname,string tocharsetname) {try {str = new String (str.getby    TES (CharsetName), tocharsetname);    } catch (Unsupportedencodingexception ex) {System.out.println ("string encoding Conversion Exception:" + Ex.getmessage ()); } return str;}

7. The Chinese alphabet is sorted by dictionary order:
Private arraylist<string> Mitems; Collections.sort (Mitems, Collator.getinstance (Java.util.Locale.CHINA)); Sort

8. Check if WiFi is on or connected:
    Whether to connect WiFi public static Boolean iswificonnected (context context) {Connectivitymanager Connectivitymanag        ER = (connectivitymanager) context.getsystemservice (Context.connectivity_service);        Networkinfo wifinetworkinfo = Connectivitymanager.getnetworkinfo (Connectivitymanager.type_wifi);    return wifinetworkinfo.isconnected ();    }/**** Open wifi***/public static Boolean Openwifi (context context) {return Opclwifi (context, true);    }/**** Close wifi***/public static Boolean Closewifi (context context) {return Opclwifi (context, false); }/**** turns off wifi****/private static Boolean Opclwifi (context context, Boolean type) {Boolean result = Tru        E           Get Wifimanager instance Wifimanager Wifimanager = (wifimanager) context.getsystemservice (Context.wifi_service); if (wifimanager.iswifienabled () ^ type) {//Turn off WiFi result = wifimanager.setwifienabled (type)        ; } return ResULt }

Join permissions:

    <uses-permission android:name= "Android.permission.CHANGE_WIFI_STATE"/>    <uses-permission android: Name= "Android.permission.ACCESS_NETWORK_STATE"/>    <uses-permission android:name= " Android.permission.ACCESS_WIFI_STATE "/>

9, int data into 16 binary. Binary. Octal. Unsigned number string:

    public static void Printint (int i) {    System.out.println (integer.tobinarystring (i));   Binary output    System.out.println (integer.tohexstring (i));      Hex Output    System.out.println (integer.tooctalstring (i));    Octal output    System.out.println (integer.tounsignedstring (i));//Convert to unsigned number output    System.out.println ( Integer.tostring (i));         Convert to string Output    }
Test:

    System.out.println ("======== output positive =========");        int i = +;        Printint (i);        System.out.println ("======== output negative =========");        i = -100;        Printint (i);
Output Result:

======== output positive =========110010064144100100======== output negative ========= 11111111111111111111111110011100ffffff9c377777776344294967196-100

Android Tips Summary 1

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.