Useful code snippets of Android learning notes (5)

Source: Internet
Author: User

Webview supports online document parsing (supports office documents, PDF documents, common documents, and archive file types (. Zip and. rar ))

private class HelloWebViewClient extends WebViewClient {    @Override    public boolean shouldOverrideUrlLoading(WebView view, String url)    {        String googleDocs = "https://docs.google.com/viewer?url=";                 if (url.endsWith(".pdf"))        {            // Load "url" in google docs        mWebView.loadUrl(googleDocs + url);        }        else        {            // Load all other urls normally.            view.loadUrl(url);        }        return true;    }}

Solve the problem that the android AVD direction key DPAD cannot be used
The solution is as follows:
Find the config. ini file under c: \ Documents and Settings \ Administrator \. Android \ AVD \ avd2.avd.
Modify "no" of DPAD to "yes" and restart.

Java thread pool simple use case:

public class ThreadPool {private AtomicBoolean mStopped = new AtomicBoolean(Boolean.FALSE);private ThreadPoolExecutor mQueue;public ThreadPool() {mQueue = new ThreadPoolExecutor(10, 10, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), sThreadFactory);mQueue.allowCoreThreadTimeOut(true);}public void start(Runnable run) {mQueue.execute(run);}public void stop() {if (!mStopped.get()) {mQueue.shutdownNow();mStopped.set(Boolean.TRUE);}}private static final ThreadFactory sThreadFactory = new ThreadFactory() {private final AtomicInteger mCount = new AtomicInteger(1);@Overridepublic Thread newThread(Runnable r) {return new Thread(r, "ThreadPool #" + mCount.getAndIncrement());}};}

Protected executorservice; // thread pool private final int pool_size = 20; // single CPU thread pool size executorservice = executors. newfixedthreadpool (runtime. getruntime (). availableprocessors () * pool_size1_executorservice.exe cute (client (runnable); executorservice. shutdown ();

Newsinglethreadexecutor: creates a single-threaded thread pool. This thread pool only has one thread working, which is equivalent to a single thread serial execution of all tasks. If this unique thread ends due to an exception, a new thread will replace it. This thread pool ensures that all tasks are executed in the order they are submitted.
Newfixedthreadpool: Creates a fixed thread pool. Each time a task is submitted, a thread is created until the thread reaches the maximum size of the thread pool. The size of the thread pool remains unchanged once it reaches the maximum value. If a thread ends due to an execution exception, the thread pool will add a new thread.
Newcachedthreadpool: Creates a cache-able thread pool. If the thread pool size exceeds the thread required to process the task, some Idle threads (not executed in 60 seconds) will be reclaimed. When the number of tasks increases, this thread pool can intelligently add new threads to process tasks. This thread pool does not limit the thread pool size. The thread pool size depends entirely on the maximum thread size that can be created by the operating system (or JVM.
Newscheduledthreadpool: creates an infinite thread pool. This thread pool supports regular and periodic task execution requirements.
Newsinglethreadexecutor: creates a single-threaded thread pool. This thread pool supports regular and periodic task execution requirements.

When an application needs to be associated with several APK files, or an application is divided into several APK files, we need to bind and install them:

Put the bundled APK in the project assets file directory:

Private imageview baoxian_zhushou; arraylist <string> packagnamelist; private myreceiver extends er; Public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); initpackagnamelist (); // listen to the broadcast receiver of the new installation program = new myreceiver (); intentfilter filter = new intentfilter (intent. action_package_added); // register the broadcast mechanism filter. adddatascheme ("package"); // This item must be added; otherwise, the broadcast registerreceiver (filter) cannot be blocked );

Check whether it is installed:

// Check whether Boolean installed = detectapk ("CN. oncomm. activity "); If (installed) {// start intent = new intent () directly after installation; // component name. The first parameter is the package name, the second package name set in the main configuration file manifest is the class name, which must contain the package name intent. setcomponent (New componentname ("com. your. pakagename "," com. your. pakagename. mailactivity "); intent. setaction (intent. action_view); startactivity (intent);} else {// do not install first /// get the cachedir. file filedir = getfilesdir (); final string cachepath = filedir. getabsolutepath () + "/androidemail.apk"; retrieveapkfromassets (mainactivity. this, "androidemail.apk", cachepath); showinstallconfirmdialog (mainactivity. this, cachepath );}

// Install public Boolean retrieveapkfromassets (context, string filename, string path) {Boolean Bret = false; try {file = new file (PATH); If (file. exists () {return true;} else {file. createnewfile (); inputstream is = context. getassets (). open (filename); fileoutputstream Fos = new fileoutputstream (File); byte [] temp = new byte [1024]; int I = 0; while (I = is. read (temp ))! =-1) {FOS. write (temp, 0, I);} FOS. flush (); FOS. close (); is. close (); Bret = true ;}} catch (ioexception e) {toast. maketext (context, E. getmessage (), 2000 ). show (); Builder = new Builder (context); builder. setmessage (E. getmessage (); builder. show (); E. printstacktrace ();} return Bret;}/*** prompts the user to install the Program */Public void showinstallconfirmdialog (final context, final string filepath) {alertdialog. builder tdialog = new alertdialog. builder (context); tdialog. settitle ("this program is not installed"); tdialog. setmessage ("Please install this program"); tdialog. setpositivebutton ("OK", new dialoginterface. onclicklistener () {public void onclick (dialoginterface Diener, int which) {// modify the APK permission try {string command = "chmod" + "777" + "" + filepath; runtime runtime = runtime.getruntime(io;runtime.exe C (command);} catch (ioexception e) {e. printstacktrace ();} // install the APK. intent intent = new intent (intent. action_view); intent. addflags (intent. flag_activity_new_task); intent. setdataandtype (URI. parse ("file: //" + filepath), "application/vnd. android. package-Archive "); context. startactivity (intent) ;}}); tdialog. setnegativebutton ("cancel", new dialoginterface. onclicklistener () {public void onclick (dialoginterface dialog, int which) {}}); tdiener. show ();}/*** check whether @ Param packagename * @ return true is installed. False is not installed. */private Boolean detectapk (string packagename) {return packagnamelist. contains (packagename. tolowercase ();} private void initpackagnamelist () {// initialize the small module list packagnamelist = new arraylist <string> (); packagemanager manager = This. getpackagemanager (); List <packageinfo> pkglist = manager. getinstalledpackages (0); For (INT I = 0; I <pkglist. size (); I ++) {packageinfo Pi = pkglist. get (I); packagnamelist. add (Pi. packagename. tolowercase () ;}}/***** set broadcast listener **/private class myreceiver extends broadcastreceiver {public void onreceive (context, intent) {If (intent. getaction (). equals (intent. action_package_added) {string packname = intent. getdatastring (). substring (8); log. E (intent. getdatastring () + "====", packname); // package: CN. oncomm. activity CN. oncomm. activity // packname is the package name of the installed program packagnamelist. add (packname. tolowercase (); // delete all installed APK files in the file directory file = getfilesdir (); file [] files = file. listfiles (); For (file F: Files) {If (F. getname (). endswith (". APK ") {f. delete ();}}}}}

Network Status Monitoring (preferably in the Service ):

Broadcast implementation:

Private broadcastreceiver mnetmonitor = new broadcastreceiver () {@ overridepublic void onreceive (context, intent) {networkinfo netinfo = connectmanager. getactivenetworkinfo (); If (null = netinfo) {toast. maketext (context, "No network... ", 100 ). show (); return;} state = netinfo. getstate ();/* State winfi = connectmanager. getnetworkinfo (connectivitymanager. type_wifi ). getstate (); State GPRS = connectmanager. getnetworkinfo (connectivitymanager. type_mobile ). getstate (); */If (state. equals (state. connecting) {toast. maketext (context, "connecting network... ", 100 ). show ();} else if (state. equals (state. connected) {toast. maketext (context, "connected to network", 100 ). show ();} else if (state. equals (state. disconnecting) {toast. maketext (context, "disconnecting the network... ", 100 ). show ();} else if (state. equals (state. disconnected) {toast. maketext (context, "network connection disconnected", 100 ). show ();} else {toast. maketext (context, "your network connection has been interrupted", 100 ). show ();}}};

Registration listening:

if(connectManager==null)connectManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);if(!this.registerNetLis){IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);registerReceiver(mNetMonitor, filter);registerNetLis=true;}

When the program crashes, restart the application:

Method 1:

Reconfigure appliacation

 <application        android:allowBackup="true"        android:name="com.pioneersoft.aoc.crashexception.CrashApplication"        android:icon="@drawable/icon"        android:theme="@android:style/Theme.NoTitleBar"        android:label="@string/app_name" >

Public class crashapplication extends application {private pendingintent restartintent; @ overridepublic void oncreate () {super. oncreate (); // The following is used to capture the program crash exception intent = new intent (); // parameter 1: package name, parameter 2: Activity intent of the program entry. setclassname (getpackagename (), "com. pioneersoft. AOC. UI. mainactivity "); restartintent = pendingintent. getactivity (getapplicationcontext (), 0, intent, intent. flag_activity_new_task); t Hread. handler (restarthandler); // triggered thread upon program crash} public uncaughtexceptionhandler restarthandler = new uncaughtexceptionhandler () {@ override public void uncaughtexception (thread, throwable ex) {alarmmanager Mgr = (alarmmanager) getsystemservice (context. alarm_service); Mgr. set (alarmmanager. RTC, system. currenttimemillis () + 5000, restartintent); // restart the application log in 1 second. E ("CRAs H "," intent restart! "); // Exit the program Android. OS. process. killprocess (Android. OS. process. mypid ());}};

Method 2:

Package COM. pioneersoft. AOC. crashexception; import Java. lang. thread. uncaughtexceptionhandler; import android. app. alarmmanager; import android. app. pendingintent; import android. content. context; import android. content. intent; import android. OS. logoff; import android. util. log; import android. widget. toast; public class crashhandler implements uncaughtexceptionhandler {public static final string tag = "crashhandle R "; // The default uncaughtexception class private thread. uncaughtexceptionhandler mdefaulthandler; // crashhandler instance Private Static crashhandler instance = new crashhandler (); // The context object of the program private context mcontext; private pendingintent restartintent; /** ensure that only one crashhandler instance */private crashhandler () {}/ ** obtains the crashhandler instance. Singleton mode */public static crashhandler getinstance () {return instance ;} public void Init (context) {mcontext = context; // obtain the default uncaughtexception processor mdefaulthandler = thread. getdefaultuncaughtexceptionhandler (); // The following is used to capture the program crash exception intent = new intent (); // parameter 1: package name, parameter 2: Activity intent of the program entry. setclassname (mcontext. getpackagename (), "com. pioneersoft. AOC. UI. mainactivity "); restartintent = pendingintent. getactivity (mcontext, 0, intent, intent. flag_activity_clear_top); // sets the CRA. Shhandler is the default processor thread of the program. setdefaultuncaughtexceptionhandler (this);} private void restartapp () {alarmmanager Mgr = (alarmmanager) mcontext. getsystemservice (context. alarm_service); Mgr. set (alarmmanager. RTC, system. currenttimemillis () + 2000, restartintent); // restart the application after 1 second} @ overridepublic void uncaughtexception (thread, throwable ex) {If (! Handleexception (Ex) & mdefaulthandler! = NULL) {// if the user does not process the mdefaulthandler, the system's default exception processor is used to process the mdefaulthandler. uncaughtexception (thread, ex); // exit the android program. OS. process. killprocess (Android. OS. process. mypid ();} else {restartapp (); // exit the program and wait to restart android. OS. process. killprocess (Android. OS. process. mypid ();}/*** custom error handling, collecting error information and sending error reports are all completed here. ** @ Param ex * @ return true: If the exception information is processed, false is returned. */private Boolean handleexception (throwable ex) {If (EX = NULL) {return false;} // use toast to display exception information new thread () {@ override public void run () {logoff. prepare (); toast. maketext (mcontext, "Sorry, the program encountered an exception. Prepare to restart... ", toast. length_long ). show (); logoff. loop ();}}. start (); Return true ;}}

package com.pioneersoft.aoc.crashexception;import java.lang.Thread.UncaughtExceptionHandler;import android.app.AlarmManager;import android.app.Application;import android.app.PendingIntent;import android.content.Context;import android.content.Intent;import android.util.Log;public class CrashApplication extends Application {private PendingIntent restartIntent;@Overridepublic void onCreate() {super.onCreate();CrashHandler crashHandler = CrashHandler.getInstance();crashHandler.init(getApplicationContext());}}

Android help, about, author, help, and other prompt pages

Method 1:

Alertdialog ad = new alertdialog. builder (settingpreference. this ). settitle (R. string. about_dlg_title ). setmessage (R. string. about_dlg_message ). setpositivebutton (gettext (R. string. OK), null ). create (); Ad. show (); // Add link function linkify. addlinks (textview) AD. findviewbyid (Android. r. id. message), linkify. all );

Method 2:

Design an aboutdialog class to inherit from alertdialog

Public class aboutdialog extends alertdialog {public aboutdialog (context) {super (context); final view = getlayoutinflater (). inflate (R. layout. about, null); setbutton (context. gettext (R. string. close), (onclicklistener) null); seticon (R. drawable. icon_about); settitle ("program version v1.0.0"); setview (View );}

Layout file about. xml

<?xml version="1.0" encoding="utf-8"?>  <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="fill_parent" android:layout_height="wrap_content">      <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"         android:layout_width="fill_parent" android:layout_height="fill_parent">             <TextView android:layout_height="fill_parent"             android:layout_width="fill_parent" android:text="@string/help_dialog_text"             android:padding="6dip" android:textColor="#FFFFFF" />      </ScrollView>  </FrameLayout>  

Related Article

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.