Sometimes, you need some small functions. After finding them, you can post them to your blog and leave a message. It is inconvenient to find them. So you can sort them out to help yourself and others.
1. Obtain the System Version Number:
PackageInfo info = this.getPackageManager().getPackageInfo(this.getPackageName(), 0);int versionCode=nfo.versionCodestring versionName=info.versionNam
2. Obtain system information:
String archivefilepath = "sdcard/download/law.apk"; // installation packagemanager PM = getpackagemanager (); packageinfo info = PM. Equals (archivefilepath, packagemanager. get_activities); If (info! = NULL) {applicationinfo appinfo = info. applicationinfo; string appname = PM. getapplicationlabel (appinfo ). tostring (); string packagename = appinfo. packagename; // get the installation package name string version = info. versionname; // get the version information toast. maketext (test4.this, "packagename:" + packagename + "; version:" + version, toast. length_long ). show (); drawable icon = PM. getapplicationicon (appinfo); // get the icon information textview TV = (textview) findviewbyid (R. id. TV); // display the icon TV. setbackgrounddrawable (icon );
3. Obtain the installation path and list of installed programs
(1) Get the current program path getapplicationcontext () in Android (). getfilesdir (). getabsolutepath () (2) Android obtains the list of installed programs <packageinfo> packageinfolist = getpackagemanager (). getinstalledpackages (0 );
4. Image Retrieval, application name, and package name
PackageManager pManager = MessageSendActivity.this.getPackageManager(); List<PackageInfo> appList = Utils.getAllApps(MessageSendActivity.this); for(int i=0;i<appList.size();i++) { PackageInfo pinfo = appList.get(i); ShareItemInfo shareItem = new ShareItemInfo(); //set Icon shareItem.setIcon(pManager.getApplicationIcon(pinfo.applicationInfo)); //set Application Name shareItem.setLabel(pManager.getApplicationLabel(pinfo.applicationInfo).toString()); //set Package Name shareItem.setPackageName(pinfo.applicationInfo.packageName); }5. solve the problem that the item itself cannot be clicked when there is a button on the item on the listview:
1. Add the code Android: descendantfocusability = "blocksdescendants" 2. Add the code Android: focusable = "true" to the listview"
6. Do not enter Chinese characters in the text box:
In the XML file
Android: digits = "1234567890qwertyuiopasdfghjklzxcvbnm '-= [] \;,./~! @ # $ % ^ * () _ + }{:? & <> "'" Does not input Chinese characters.
7. Obtain the screen width and height
DisplayMetrics displayMetrics = new DisplayMetrics(); this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); int height = displayMetrics.heightPixels; int width = displayMetrics.widthPixels;
8. display the tabwidget at the bottom of the screen
Set the attribute of tabwidget for Android: layout_alignparentbottom = "true"
To display the tabhost at the bottom, set layout_gravity of radiogroup to bottom, and set layout_weight of framelayout to 1, so that the radiogroup can be stretched to the bottom. Style = "@ style/main_tab_bottom" defines the Style File
9. Obtain the thread ID and thread Name:
Log.v("@@@@@@@@@@",Thread.currentThread().getId()+" "+Thread.currentThread().getName());
10. Call other android applications in Android
ComponentName comp = new ComponentName("com.Test","com.login.Main"); intent = new Intent(); intent.setComponent(comp); intent.setAction("android.intent.action.VIEW"); startActivity(intent);11. Disable the soft keyboard
Edittext has focus (focusable is true) to prevent the input method from popping up edittext. setinputtype (inputtype. type_null); // disable the soft keyboard when eidttext has no focus (focusable = false ).
InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
[Android] The edittext tag calls the keyboard.
In an XML file, the edittext tag has an attribute Android: editable = "false" and Android: Numeric = "integer"
Android: Numeric = "integer" indicates that only numbers are allowed. This attribute allows users to enter only numbers.
Android: editable indicates whether the content can be input. "True" indicates that the content can be input. "false" indicates that the content cannot be input;
When it is Android: editable = "false", click the input box and the virtual keyboard cannot be displayed. However, when the Android: editable = "" attribute is set, whether it is false or true, when the Android: Numeric = "integer" attribute is added later, you can enter the number content. Here, you do not understand what is going on. Maybe numeric overwrites the previous attribute.
When Android: editable = "false" and edittext. setenabled (true) are specified in the Java class, the virtual keyboard is not displayed.
12. Comparison between the specifications and Resolutions of the simulator:
Unit: pixel wvga854: 854*480wvga800: 800*480 hvga: 480*320 qvga: 320*240wqvga432: 432*240 wqvga400: 400*240
13. Call activity of other android Context
Context c = createpackagecontext ("chroya. demo ", context. context_include_code | context. context_ignore_security); // load this class clazz = C. getclassloader (). loadclass ("chroya. demo. main "); // create an instance object owner = clazz. newinstance (); // obtain the print method, input parameters, and execute object OBJ = clazz. getmethod ("print", String. class ). invoke (owner, "hello ");
This method has two parameters:
1. packagename package name. Obtain the package name of the context.
2. Flags. Two options are available: context_include_code and context_ignore_security. Context_include_code indicates that the code in this package can be executed. Context_ignore_security indicates that the security warning is ignored. If this flag is not added, some functions cannot be used and a security warning will appear.
14. Tips for android4.0dialog Style
If theme. dialog is used in 4.0, it can only be said to be very earthy, which is very different from the overall UI style.
Please use Android: theme = "@ Android: style/theme. holo. dialogwhenlarge"
15. Install APK in the program
Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.setAction(android.content.Intent.ACTION_VIEW);intent.setDataAndType(Uri.fromFile(“APK”),"application/vnd.android.package-archive");startActivity(intent);
Here, "APK" is the file you want to install.
16. Obtain the device model, SDK version, and system version.
String device_model = build. Model; // device model string version_sdk = build. version. SDK; // device SDK version string version_release = build. version. Release; // system version of the device
17. image analysis functions
public void SharePhoto(String photoUri,final Activity activity) { Intent shareIntent = new Intent(Intent.ACTION_SEND); File file = new File(photoUri); shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); shareIntent.setType("image/jpeg"); StartActivity(Intent.createChooser(shareIntent, activity.getTitle())); }
October 18. Linux shutdown command
In Windows, press the power key for 4 seconds to force shutdown. in Linux, it is strongly not recommended to do so. Windows is a single-user, "fake" task, so even if your computer is shut down, it will not affect others. However, in Linux, because every program is executed in the background, many people may work on your host at the same time behind the screen that you don't see. Otherwise, the file system may be damaged. Therefore, under normal circumstances, pay attention to the following things When shutting down:
(1) view the system usage status.
To see who is online, you can use the who command. To view the online status of the network, run the netstat-a command. The program running in the background can execute the PS-Aux command.
(2) Notify online users of the shutdown time
In this case, you can use the shutdown command.
Shutdown command: Syntax: shutdown [-T seconds] [-arkhncff] Time Warning Message-T: The following description indicates shutdown after several seconds. -K: only a warning message is sent if the instance is not shut down. -R: restart after the system service is stopped. -H: Shut down immediately after the system service is stopped. -F: force The fsck disk check to be skipped after the instance is shut down and started. -F: After the system is restarted, force the fsck disk check. -C: cancels the content of the shutdown command. In addition, the restart and shutdown Commands include reboot, halt, and poweroff. In fact, the same job is done by default. Halt calls shutdown first, while shutdown calls halt at last. However, shutdown can be stopped only after the service is disabled based on the services already started. However, halt can perform special hardware shutdown functions in the current system. In addition, there is also a shutdown command, init 0init, which is a command to switch the execution level. There are 7 execution levels in Linux. The most important level is the following four: Run level 0: Run level 3: Run level 5 in command line mode: Run level 6 in graphic interface mode: restart
19. If your application is not killed, you can add a condition in the forcestoppackage of the class frameworks \ base \ Services \ Java \ com \ Android \ Server \ am \ activitymanagerservice. Java:
Public void forcestoppackage (final string packagename) {If (checkcallingpermission (Android. manifest. Permission. force_stop_packages )! = Packagemanager. permission_granted) {string MSG = "permission Denial: forcestoppackage () from pid =" + binder. getcallingpid () + ", uid =" + binder. getcallinguid () + "requires" + android. manifest. permission. force_stop_packages; slog. W (TAG, MSG); throw new securityexception (MSG);} Long callingid = binder. clearcallingidentity (); try {ipackagemanager PM = activitythread. getpackagemanager (); int pkguid =-1; synchronized (this) {try {pkguid = PM. getpackageuid (packagename);} catch (RemoteException e) {}if (pkguid =-1) {slog. W (TAG, "invalid packagename:" + packagename); return;} // begin: Add a judgment condition if (packagename. equals ("Your process name") {return;} // end: Add a judgment condition forcestoppackagelocked (packagename, pkguid);} finally {binder. restorecallingidentity (callingid );}}
In this way, you can ensure that the kiss cannot be dropped in the task manager;
There is also a method in this method clearapplicationuserdata to ensure that the forcestoppackage () method will not be called if the process is used. Other methods:
1. First, write your own code in the ondestory method of your service. Why do you need to write this? Because if you kill your service in Settings> Application> running service, the ondestory method will be called. You can start it here. 2: when the monitoring screen is disabled and the screen is disabled, the service is started. 3: Listen to the screen to unlock the broadcast. In this way, basically, your service will never stop. It is a little abnormal for users, but it is true for many software.
20. Obtain the focus of edittext:
EditText.requestFoucus()
Due to the large amount of collected content, it is decided that every 20 articles will be divided into one article. Sorry for any inconvenience! View other parts: Useful Android code snippets (2)
The above code is excerpted from others' blogs and does not specify the source. Sorry.