android 學習筆記有用程式碼片段(5)

來源:互聯網
上載者:User

webView 實現線上解析文檔功能(支援office文檔,pdf文檔,常見文檔,封存檔案類型(.ZIP 和 .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;    }}

解決Android AVD的方向鍵DPAD不能用的問題
解決方式如下 :
找到C:\Documents and Settings\Administrator\.android\avd\avd2.avd下的config.ini檔案。
修改dpad的no為yes重啟即可。

java 線程池簡單使用案例:

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 executorService;// 線程池private final int POOL_SIZE = 20;// 單個CPU線程池大小executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * POOL_SIZE);executorService.execute(client(runnable));executorService.shutdown();

newSingleThreadExecutor:建立一個單線程的線程池。這個線程池只有一個線程在工作,也就是相當於單線程串列執行所有任務。如果這個唯一的線程因為異常結束,那麼會有一個新的線程來替代它。此線程池保證所有任務的執行順序按照任務的提交順序執行。
newFixedThreadPool:建立固定大小的線程池。每次提交一個任務就建立一個線程,直到線程達到線程池的最大大小。線程池的大小一旦達到最大值就會保持不變,如果某個線程因為執行異常而結束,那麼線程池會補充一個新線程。
newCachedThreadPool:建立一個可快取的線程池。如果線程池的大小超過了處理任務所需要的線程,那麼就會回收部分空閑(60秒不執行任務)的線程,當任務數增加時,此線程池又可以智能的添加新線程來處理任務。此線程池不會對線程池大小做限制,線程池大小完全依賴於作業系統(或者說JVM)能夠建立的最大線程大小。
newScheduledThreadPool:建立一個大小無限的線程池。此線程池支援定時以及周期性執行任務的需求。
newSingleThreadExecutor:建立一個單線程的線程池。此線程池支援定時以及周期性執行任務的需求。

當一個應用程式需要關聯幾個apk時,或者一個應用分為幾個部分apk時我們需要捆綁安裝:

將要捆綁apk放到項目 assets檔案目錄下:

private ImageView baoxian_zhushou;ArrayList<String> packagNameList;private MyReceiver receiver;public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initpackagNameList();// 監聽系統新安裝程式的廣播receiver = new MyReceiver();IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);// 註冊廣播機制filter.addDataScheme("package"); // 必須添加這項,否則攔截不到廣播registerReceiver(receiver, filter);

檢測是否已安裝:

// 檢查是否已經安裝boolean installed = detectApk("cn.oncomm.activity");if (installed) {// 已經安裝直接起動Intent intent = new Intent();// 組件名稱,第一個參數是包名,也是主設定檔Manifest裡設定好的包名 第二個是類名,要帶上包名intent.setComponent(new ComponentName("com.your.pakagename","com.your.pakagename.MailActivity"));intent.setAction(Intent.ACTION_VIEW);startActivity(intent);} else {// 未安裝先安裝//// get the cacheDir.File fileDir = getFilesDir();final String cachePath = fileDir.getAbsolutePath()+ "/AndroidEmail.apk";retrieveApkFromAssets(MainActivity.this,"AndroidEmail.apk", cachePath);showInstallConfirmDialog(MainActivity.this, cachePath);}

// 捆綁安裝public boolean retrieveApkFromAssets(Context context, String fileName,String path) {boolean bRet = false;try {File 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 builder = new Builder(context);builder.setMessage(e.getMessage());builder.show();e.printStackTrace();}return bRet;}/** *提示使用者安裝程式 */public void showInstallConfirmDialog(final Context context,final String filePath) {AlertDialog.Builder tDialog = new AlertDialog.Builder(context);tDialog.setTitle("未安裝該程式");tDialog.setMessage("請安裝該程式");tDialog.setPositiveButton("確定", new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {// 修改apk許可權try {String command = "chmod " + "777" + " " + filePath;Runtime runtime = Runtime.getRuntime();runtime.exec(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("取消", new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {}});tDialog.show();}/** * 檢測是否已經安裝 *  * @param packageName * @return true已安裝 false未安裝 */private boolean detectApk(String packageName) {return packagNameList.contains(packageName.toLowerCase());}private void initpackagNameList() {// 初始化小模組列表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());}}/** *  * 設定廣播監聽 *  */private class MyReceiver extends BroadcastReceiver {public void onReceive(Context context, Intent 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為所安裝的程式的包名packagNameList.add(packName.toLowerCase());// 刪除file目錄下的所有以安裝的apk檔案File file = getFilesDir();File[] files = file.listFiles();for (File f : files) {if (f.getName().endsWith(".apk")) {f.delete();}}}}}

網路狀態監聽(最好是在service裡面實現):

廣播實現:

private BroadcastReceiver mNetMonitor=new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {NetworkInfo netInfo=connectManager.getActiveNetworkInfo();if(null==netInfo){Toast.makeText(context, "沒有網路...", 100).show();return;}State 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, "正在串連網路...", 100).show();}else if(state.equals(State.CONNECTED)){Toast.makeText(context, "已經串連到網路", 100).show();}else if(state.equals(State.DISCONNECTING)){Toast.makeText(context, "正在斷開網路連接...", 100).show();}else if(state.equals(State.DISCONNECTED)){Toast.makeText(context, "網路連接已斷開", 100).show();}else{Toast.makeText(context, "您的網路連接已中止", 100).show();}}};

註冊監聽:

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;}

程式崩潰時,重啟應用:

方法一:

重新設定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(); // 以下用來捕獲程式崩潰異常          Intent intent = new Intent();          // 參數1:包名,參數2:程式入口的activity          intent.setClassName(getPackageName(), "com.pioneersoft.aoc.ui.MainActivity");          restartIntent = PendingIntent.getActivity(getApplicationContext(), 0,                  intent, Intent.FLAG_ACTIVITY_NEW_TASK);          Thread.setDefaultUncaughtExceptionHandler(restartHandler); // 程式崩潰時觸發線程 }public UncaughtExceptionHandler restartHandler = new UncaughtExceptionHandler() {          @Override          public void uncaughtException(Thread thread, Throwable ex) {                     AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);              mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 5000,                      restartIntent); // 1秒鐘後重啟應用              Log.e("crash", "intent restart!");            //退出程式         android.os.Process.killProcess(android.os.Process.myPid());         }      };  

方法二:

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.Looper;import android.util.Log;import android.widget.Toast;public class CrashHandler implements UncaughtExceptionHandler{public static final String TAG ="CrashHandler";  //系統預設的UncaughtException處理類  private Thread.UncaughtExceptionHandler mDefaultHandler; //CrashHandler執行個體 private static CrashHandler INSTANCE = new CrashHandler(); //程式的Context對象 private Context mContext; private PendingIntent restartIntent;/** 保證只有一個CrashHandler執行個體 */ private CrashHandler() {}  /** 擷取CrashHandler執行個體 ,單例模式 */ public static CrashHandler getInstance() {     return INSTANCE; }  public void init(Context context) {     mContext =context;     //擷取系統預設的UncaughtException處理器     mDefaultHandler =Thread.getDefaultUncaughtExceptionHandler();     // 以下用來捕獲程式崩潰異常          Intent intent = new Intent();          // 參數1:包名,參數2:程式入口的activity          intent.setClassName(mContext.getPackageName(), "com.pioneersoft.aoc.ui.MainActivity");          restartIntent = PendingIntent.getActivity(mContext, 0,                  intent, Intent.FLAG_ACTIVITY_CLEAR_TOP);      //設定該CrashHandler為程式的預設處理器    Thread.setDefaultUncaughtExceptionHandler(this); } private void restartApp(){AlarmManager mgr = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);          mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 2000,                  restartIntent); // 1秒鐘後重啟應用  }@Overridepublic void uncaughtException(Thread thread, Throwable ex) { if(!handleException(ex) && mDefaultHandler != null) {         //如果使用者沒有處理則讓系統預設的異常處理器來處理        mDefaultHandler.uncaughtException(thread, ex);        //退出程式        android.os.Process.killProcess(android.os.Process.myPid());     } else {     restartApp();        //退出程式 等待重啟       android.os.Process.killProcess(android.os.Process.myPid());     } }/** * 自訂錯誤處理,收集錯誤資訊發送錯誤報表等操作均在此完成. *  * @param ex * @return true:如果處理了該異常資訊;否則返回false. */ private boolean handleException(Throwable ex) {     if (ex == null){         return false;     }     //使用Toast來顯示異常資訊     new Thread() {         @Override         public void run() {            Looper.prepare();            Toast.makeText(mContext, "很抱歉,程式出現異常,準備重啟中...",Toast.LENGTH_LONG).show();            Looper.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的協助、about、關於作者、HELP等的提示頁面

方法一:

 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();//加入連結功能                Linkify.addLinks((TextView) ad.findViewById(android.R.id.message),                        Linkify.ALL);

方法二:

設計一個AboutDialog類繼承於AlertDialog

public class AboutDialog extends AlertDialog {       public AboutDialog(Context context) {           super(context);           final View view = getLayoutInflater().inflate(R.layout.about,                   null);           setButton(context.getText(R.string.close), (OnClickListener) null);           setIcon(R.drawable.icon_about);           setTitle("程式版本   v1.0.0" );           setView(view);       }   

布局檔案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>  

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.