android 常用代码片段,前1-10条是从网上摘录,向原作者致谢。后面为自己整理。
1、设置窗口格式为半透明getWindow().setFormat(PixelFormat.TRANSLUCENT);2、Android中在非UI线程里更新View的不同方法:* Activity.runOnUiThread( Runnable )* View.post( Runnable )* View.postDelayed( Runnable, long )* Hanlder3、全屏显示窗口requestWindowFeature(Window.FEATURE_NO_TITLE);getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);4、取得屏幕大小方法A:WindowManager windowManager = getWindowManager();Display display = windowManager.getDefaultDisplay();hAndW[0] = display.getWidth();hAndW[1] = display.getHeight();方法B:DisplayMetrics dm = new DisplayMetrics();getWindowManager().getDefaultDisplay().getMetrics(dm);hAndW[0] = dm.widthPixels;hAndW[1] = dm.heightPixels;5、调浏览器 载入网址Uri uri = Uri.parse("http://www.google.com");Intent it = new Intent(Intent.ACTION_VIEW, uri);startActivity(it);6、取得内存大小ActivityManager.MemoryInfo outInfo = new ActivityManager.MemoryInfo();activityManager.getMemoryInfo(outInfo);//可用内存outInfo.availMem//是否在低内存状态outInfo.lowMemory取得ScrollView的实际高度scrollview.getHeight()scrollview.getMeasuredHeight()scrollview.compute()scrollview.getLayoutParams().height7、监听App安装/卸载事件A.Define a class derived from class BroadcastReceiver;B.Register broadcast receiver;MyBroadcastReceiver myReceiver = new MyBroadcastReceiver();IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_INSTALL);filter.addAction(Intent.ACTION_PACKAGE_REMOVED);filter.addAction(Intent.ACTION_PACKAGE_ADDED);filter.addAction(Intent.ACTION_PACKAGE_CHANGED);filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);...filter.addDataScheme("package"); //This line is very important. Otherwise, broadcast can't be received.registerReceiver(myReceiver, filter);Notes: The package name is Intent.mData. Intent.mData is not available in SDK 1.0, but it can be retrieved by calling Intent.getDataString();8、取得IP地址A.//Connect via WIFI 通过wifiWifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);WifiInfo wifiInfo = wifiManager.getConnectionInfo();int ipAddress = wifiInfo.getIpAddress();B.//Connect via GPRS通过gprspublic String getLocalIpAddress(){try{for(Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();){NetworkInterface intf = en.nextElement();for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();){InetAddress inetAddress = enumIpAddr.nextElement();if (!inetAddress.isLoopbackAddress()){return inetAddress.getHostAddress().toString();}}}}catch (SocketException ex){Log.e(S.TAG, ex.toString());}return null;}9、ListView 后面adapter数据已更改,但是ListView没有收到Notification首先,必须将 更新adapter数据的代码放在:Handler.post(Runnable)方法中执行;然后,如果Adapter数据的来源如果是cursor(CursorAdapter)的话 可以cursor.requery一下,如果是别的可以强制调用一下notifyChange, notifyChange 会调用 invalidate 进行重绘;10、模拟HOME键Intent i=new Intent(Intent.ACTION_MAIN);i.addCategory(Intent.CATEGORY_HOME);i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);context.startActivity(i);11、设置焦点editText.setFocusable(true);editText.requestFocus();editText.setFocusableInTouchMode(true);12:在一个应用中去调用另一个app例如:if (Utils.isAvilible(context, "com.netschool.main.ui")) { Intent i = new Intent(); ComponentName cn = new ComponentName("com.netschool.main.ui", "com.netschool.main.ui.SplashScreenActivity"); i.setComponent(cn); startActivity(i); } else { Uri uri = Uri.parse(context.getString(R.string.url_zhuanti_download)); Intent it = new Intent(Intent.ACTION_VIEW, uri); it.setData(uri); startActivity(it); }13:andoroid TextView 显示特殊字符 String course_jianjie ="xxxxxxxxxx";//字符串中有 \r\n 需要替换为 <br/> String temp =course_jianjie.replaceAll("\\r\\n", "<br/>");//用html 来显示 CharSequence styledText = Html.fromHtml(temp); //设置要显示的控件 mCourseDescTv.setText(styledText);14:使用NotificationManager触发多个Notification,只显示最后一个的问题只要每个不同的Intent对应传递一个独立的ID就可以了,以上函数修改如下(增加ID参数):private Notification genreNotification(Context context, int icon, String tickerText, String title, String content, Intent intent, int id){ Notification notification = new Notification(icon, tickerText, System.currentTimeMillis()); // 问题就在这里的id了 PendingIntent pendIntent = PendingIntent.getActivity(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT); notification.setLatestEventInfo(context, title, content, pendIntent); notification.flags |= Notification.FLAG_AUTO_CANCEL; return notification; }...mNotificationManager.notify(ID_1, genreNotification(mContext, ICON_RES, notifyText1, notifyTitle1, notifyText1, intent_1, ID_1));...mNotificationManager.notify(ID_2, genreNotification(mContext, ICON_RES, notifyText2, notifyTitle2, notifyText2, intent_2, ID_2));...mNotificationManager.notify(ID_3, genreNotification(mContext, ICON_RES, notifyText3, notifyTitle3, notifyText3, intent_3, ID_3));15: adb 命令截图adb shell /system/bin/screencap -p /sdcard/screenshot.png(保存到SDCard)adb pull /sdcard/screenshot.png d:/screenshot.png(保存到电脑) 16:跳出for循环OK: for(int i=0;i<100;i++){ if(i==10){ break OK; } }17:使用viewPager加载超过3页 有时会报出 The specified child already has a parent. You must call removeView() on the child's parent first 的错误此时:可以简单的用mViewPager.setOffscreenPageLimit(3);解决备注:单这不是万能之策,也不是优选之策18: /** * @Description:调节音量大小 * @author: jrh * @date: 2014-11-13 下午3:06:46 * @return: void * @param percent */ private void onVolumeSlide(float percent) { if (mVolume == -1) { mVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC); if (mVolume < 0) { mVolume = 0; } mOperationBg.setImageResource(R.drawable.video_volumn_bg); mVolumeBrightnessLayout.setVisibility(View.VISIBLE); } int index = (int) ((percent * mMaxVolume) + mVolume); if (index > mMaxVolume) { index = mMaxVolume;// 最大音量 } else if (index < 0) { index = 0;// 静音 } // 变更声音 mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, index, 0); // 变更进度条 ViewGroup.LayoutParams lp = mOperationPercent.getLayoutParams(); lp.width = findViewById(R.id.operation_full).getLayoutParams().width * index / mMaxVolume; mOperationPercent.setLayoutParams(lp); }19 /** * @Description:调节屏幕亮度 * @author: jrh * @date: 2014-11-13 下午3:17:40 * @return: void * @param percent */ private void onBrightnessSlide(float percent) { if (mBrightness < 0) { mBrightness = getWindow().getAttributes().screenBrightness; if (mBrightness <= 0.00f) { mBrightness = 0.50f; } else if (mBrightness < 0.01f) { mBrightness = 0.01f; } // 显示 mOperationBg.setImageResource(R.drawable.video_brightness_bg); mVolumeBrightnessLayout.setVisibility(View.VISIBLE); } WindowManager.LayoutParams lpa = getWindow().getAttributes(); lpa.screenBrightness = mBrightness + percent; if (lpa.screenBrightness > 1.0f) { lpa.screenBrightness = 1.0f;// 最亮 } else if (lpa.screenBrightness < 0.01f) { lpa.screenBrightness = 0.01f; } getWindow().setAttributes(lpa); ViewGroup.LayoutParams lp = mOperationPercent.getLayoutParams(); lp.width = (int) (findViewById(R.id.operation_full).getLayoutParams().width * lpa.screenBrightness); mOperationPercent.setLayoutParams(lp); }20:viewpager + fragment 布局时有时会报下面的错误11-14 13:52:45.266: E/AndroidRuntime(4561): FATAL EXCEPTION: main11-14 13:52:45.266: E/AndroidRuntime(4561): java.lang.NullPointerException11-14 13:52:45.266: E/AndroidRuntime(4561): at android.support.v4.app.FragmentManagerImpl.saveFragmentBasicState(FragmentManager.java:1576)解决方法:在继承fragment的里面重写 @Override public void onSaveInstanceState(Bundle outState) { // TODO Auto-generated method stub super.onSaveInstanceState(outState); setUserVisibleHint(true); }21:service 服务并不是另开一个线程 ,处理service 时最好单独开线程进行处理22:不要在receiver 里面处理耗时工作23:如果布局时: 想要在字中间加空格 可以使用 " ;" html 的空格实体编号添加。注意:一个汉字相当于 两个空格字符。24:volatile java 关键字 保证了线程可以读取其他线程的写入值、 Thread.join() 方法保证了该线程优先执行 其他线程等待 Thread.yied() 方法 让出时间让其它线程可以执行 如何停止线程? 不要随意调用 Thread.stop()方法 ,该方法不是正确的停止线程方法 会导致一些其他的问题 使用推出的旗杆标志 :如设置 boolean 值等 结束时及时清理资源 使用代码逻辑来使得线程执行结束 (使thread 线程内部的代码 任务执行完毕)25:如何在TextVeiw下加入一条线TextView tv = new TextView();tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);26:android 4.4 以上无法在外置SD卡创建文件夹 解决方法: @A File dirFile = new File(temp.trim()); if (!dirFile.exists()) {// 对于4.4以上版本特别重要 getApplicationContext().getExternalFilesDir(null); dirFile.mkdirs(); } @B 文件路径:/android/data/包名/27:在: android:targetSdkVersion="18" 随着版本号的改变 界面元素,显示方式是不一样的28:android 获取所有存储卡的地址 private String[] getSdCard() { StorageManager sm = (StorageManager) getSystemService(Context.STORAGE_SERVICE); String[] paths = null; try { paths = (String[]) sm.getClass().getMethod("getVolumePaths", null) .invoke(sm, null); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } return paths; }29:百度地图 出现问题A:报错java.lang.UnsatisfiedLinkError: Couldn't load BaiduMapSDK_v3_2_0_15 from loader dalvik.system.PathClassLoader[dexPath=/data/app/com.znxh.haohao-1.apk,libraryPath=/data/app-lib/com.znxh.haohao-1]: findLibrary returned null解决方法:1:现在libs下建armeabi文件夹,然后加入.so库文件;2:如果上述方法不行:再在libs下建armeabi-v7a文件夹,再导入相应.so库文件3:定位时一定要在mainfest 文件中注册服务: <service android:name="com.baidu.location.f" android:enabled="true" android:process=":remote" > </service>30:处理图片上传的工具类 /* * 上传头像 * * @param urlStr url地址 * * @param userid 用户id * * @param urlStr 要上传的图片 */ public static Runnable upLoadFile(final Handler handler, final String urlString, final String userid, final File file) { Runnable runnable = new Runnable() { @Override public void run() { int res = 0; String result = null; String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成 String PREFIX = "--", LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data"; // 内容类型 try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(2000); conn.setConnectTimeout(2000); conn.setDoInput(true); // 允许输入流 conn.setDoOutput(true); // 允许输出流 conn.setUseCaches(false); // 不允许使用缓存 conn.setRequestMethod("POST"); // 请求方式 conn.setRequestProperty("Charset", "UTF-8"); // 设置编码 conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); if (file != null) { /** * 当文件不为空时执行上传 */ DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); StringBuffer sb = new StringBuffer(); sb.append("--" + BOUNDARY + "\r\n"); sb.append("Content-Disposition: form-data; name=\"userid\"" + "\r\n"); sb.append("\r\n"); sb.append(userid + "\r\n"); sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); /** * 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件 filename是文件的名字,包含后缀名 */ sb.append("Content-Disposition: form-data; name=\"photo\"; filename=\"" + file.getName() + "\"" + LINE_END); sb.append("Content-Type: image/pjpeg; charset=" + "UTF-8" + LINE_END); sb.append(LINE_END); dos.write(sb.toString().getBytes()); InputStream is = new FileInputStream(file); byte[] bytes = new byte[1024]; int len = 0; while ((len = is.read(bytes)) != -1) { dos.write(bytes, 0, len); } is.close(); dos.write(LINE_END.getBytes()); byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes(); dos.write(end_data); dos.flush(); /** * 获取响应码 200=成功 当响应成功,获取响应的流 */ res = conn.getResponseCode(); Log.i("return code", "response code:" + res); Log.i("userid", "" + userid); if (res == 200) { InputStream input = conn.getInputStream(); StringBuffer sb1 = new StringBuffer(); int ss; while ((ss = input.read()) != -1) { sb1.append((char) ss); } result = sb1.toString(); Log.i("return", "result : " + result); Message message = Message.obtain(); message.what = 666; handler.sendMessage(message); } else { Log.i("return", "request error"); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }; return runnable; }