Android常用功能代码

//非完全原创,大多源自网络向作者致敬!

26.汉字按拼音排序比较器

 

/**
     * 汉字按字母顺序排列的比较器
     */
    class PinyinComarator implements Comparator<Contact> {

        @Override
        public int compare(Contact o1, Contact o2) {
            if (o1 == null || o2 == null) {
                return 0;
            }
            String str1 = o1.getName();
            String str2 = o2.getName();
            if(TextUtils.isEmpty(str1) || TextUtils.isEmpty(str2)){
                return 0;
            }
            String pinyinHead = Pinyin.toPinyin(str1, ",");
            String pinyinRear = Pinyin.toPinyin(str2, ",");

            String a[] = pinyinHead.split(",");
            String b[] = pinyinRear.split(",");
//            String a[] = {"Qiao", "Feng"};
//            String b[] = {"Qiao", "An", "Shan"};
            int len = a.length < b.length ? a.length : b.length;
            for (int i = 0; i < len; i++) {
                String head = a[i];
                String rear = b[i];
                int inLen = head.length() < rear.length()?head.length():rear.length();
                LogUtil.d("Begin compare head:"+head+"|read:"+rear);
                for (int j = 0; j < inLen; j++) {
                    char c1 = head.charAt(j);
                    char c2 = rear.charAt(j);
                    //System.out.println(c1+"比"+c2+"大吗?"+(c1>c2));
                    if (c1 > c2) {
                        //System.out.println(">");
                        LogUtil.d("c1:"+c1+" > |c2:"+c2);
                        return 1;
                    } else if (c1 == c2) {
                        //System.out.println("=");
                        LogUtil.d("c1:"+c1+" == |c2:"+c2);
                        continue;
                    } else if (c1 < c2) {
                        //System.out.println("<");
                        LogUtil.d("c1:"+c1+" <|c2:"+c2);
                        return -1;
                    }
                }
                LogUtil.d("End compare head:"+head+"|read:"+rear);
            }
            return 0;
        }
    }

 

 

 

 

 

25.Java实现统计项目代码行数

 

public class StatisticCodeLines {
private Map<String, Integer> map = new HashMap<>();
	
	public static void main(String[] args) {
		StatisticCodeLines StatisticCodeLines = new StatisticCodeLines();
		//StatisticCodeLines.getTxtFileLineCount();
		File file = new File("x:\\xxx");
		StatisticCodeLines.print(file);
		StatisticCodeLines.printCount();
		/*file = new File("x:\\xxx");
		StatisticCodeLines.print(file);
		StatisticCodeLines.printCount();*/
	}
	
	private void printCount(){
		int totalLines = 0;
		Set<String> nameSet = map.keySet();
		for (String string : nameSet) {
			int temp = map.get(string);
			System.out.println("文件:"+string+" \t\t\t\t代码行数:"+temp);
			totalLines+=temp;
		}
		System.out.println("总代码行数:"+totalLines);
	}
	
	
	// 递归调用此方法列出目录下的所有目录和文件
	public void print(File file) {
		if (file != null) {
			if (file.isDirectory()) {
				File f[] = file.listFiles();// 列出全部的文件
				if (f != null) {
					for (int i = 0; i < f.length; i++) {
						print(f[i]);// 递归调用自身
					}
				}
			} else {
				System.out.println(file);// 输出路径
				int count = getTxtFileLineCount(file.getPath());
				map.put(file.getName(), count);
			}
		}
	}

	private int getTxtFileLineCount(String filePath) {
		try {
			File file = new File(filePath);
			if (file.exists()) {
				FileReader fr = new FileReader(file);
				LineNumberReader lnr = new LineNumberReader(fr);
				int linenumber = 0;
				while (lnr.readLine() != null) {
					linenumber++;
				}
				System.out.println("Total number of lines : " + linenumber);
				lnr.close();
				return linenumber;
			} else {
				System.out.println("File does not exists!");
				return 0;
			}
		} catch (IOException e) {
			e.printStackTrace();
			return 0;
		}
	}
}

 

 

 

 

 

24.遍历Map

 

private void printMap(Map<String, String> params){
//		Map<String, String> params = new HashMap<String, String>();
//		params.put("videoReplay", "addReplay");
//		params.put("userID", "666666");
//		params.put("videoID", "7777");
//		params.put("content", "content");
//		T9 tt = new T9();
//		tt.printMap(params);
//		Iterator<Entry<String, String>> iter = params.entrySet().iterator();
//
//		Entry<String, String> entry;
//		String key;
//		String value;
//		while (iter.hasNext()) {
//
//		    entry = iter.next();
//
//		    key = entry.getKey();
//
//		    value = entry.getValue();
//		    System.out.println(key+":"+value);
//		}
//		System.out.println(params);
		Iterator<Entry<String, String>> iter = params.entrySet().iterator();

		Entry<String, String> entry;
		String key;
		String value;
		while (iter.hasNext()) {

		    entry = iter.next();

		    key = entry.getKey();

		    value = entry.getValue();
		    System.out.println(key+":"+value);
		}
		System.out.println(params);
	}

 

 

 

 

 

23.Java保留指定位数小数

 

/*java保留两位小数问题:

		方式一:

		四舍五入  */
		double   f   =   111231.5585;  
		BigDecimal   b   =   new   BigDecimal(f);  
		double   f1   =   b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();  
		System.out.println(f1);
		//保留两位小数  
		//---------------------------------------------------------------  
		
		/*方式二:

		java.text.DecimalFormat   df   =new   java.text.DecimalFormat("#.00");  
		df.format(你要格式化的数字);

		例:new java.text.DecimalFormat("#.00").format(3.1415926)*/
		
		java.text.DecimalFormat   df   =new   java.text.DecimalFormat("#.00");  
		System.out.println(df.format(3.1415926));

		// #.00 表示两位小数 #.0000四位小数 以此类推...
		//---------------------------------------------------------------
		
		/*方式三:

		double d = 3.1415926;

		String result = String .format("%.2f");

		%.2f %. 表示 小数点前任意位数   2 表示两位小数 格式后的结果为f 表示浮点型*/
		
		double d = 3.1415926;
		String result = String.format("%.2f",d);
		System.out.println(result);
		//---------------------------------------------------------------
		
		/*方式四:

		NumberFormat ddf1=NumberFormat.getNumberInstance() ;

		void setMaximumFractionDigits(int digits) 
		digits 显示的数字位数 
		为格式化对象设定小数点后的显示的最多位,显示的最后位是舍入的*/
		double $xXx = 21.654323;
		NumberFormat ddf1=NumberFormat.getNumberInstance();
		ddf1.setMaximumFractionDigits(3);
		System.out.println(ddf1.format($xXx));

 

 

 

 

 

22.关闭软键盘

 

<span style="font-size:14px;">/**
	 * 如果软键盘处于打开状态,则关闭之
	 * 
	 * @param paramActivity
	 */
	public static void toggleInputMethod(Activity paramActivity) {
		if (paramActivity == null) {
		} else {
			View view = paramActivity.getWindow().peekDecorView();
			if (view != null) {// 隐藏虚拟键盘
				InputMethodManager inputmanger = (InputMethodManager) paramActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
				inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
			}
		}
	}</span>

 

 

 

 

 

21.手机相册照片的方向是否需要旋转

可以读取相片的方向值,然后旋转读取方向值请参照下面的代码:
ExifInterface exifInterface = new ExifInterface(bitmapUrl);
int tag = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1);
然后旋转:
int degree = 0;
if (tag == ExifInterface.ORIENTATION_ROTATE_90) 
{
degree = 90;
} 
else if (tag == ExifInterface.ORIENTATION_ROTATE_180) 
{
degree = 180;
} 
else if (tag == ExifInterface.ORIENTATION_ROTATE_270) 
{
degree = 270;
}
if (degrees != 0 && bitmap != null) 
{
	Matrix m = new Matrix();
	m.setRotate(degrees, (float) bitmap.getWidth() / 2, 
	(float) bitmap.getHeight() / 2);
}


 

20.得到状态栏的高度

		Rect rectgle= new Rect();
		Window window= getWindow();
		window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
		int StatusBarHeight= rectgle.top;
		int contentViewTop= 
			    window.findViewById(Window.ID_ANDROID_CONTENT).getTop();
		int TitleBarHeight= contentViewTop - StatusBarHeight;
		Log.i("*** Jorgesys :: ", "StatusBar Height= " + StatusBarHeight + " , TitleBar Height = " + TitleBarHeight);

19.得到系统的语言和地区

String s = Locale.getDefault().getLanguage();
		String s2 = Locale.getDefault().getCountry();
		System.out.println("Language: "+s+" Country: "+s2);
		String locale = this.getResources().getConfiguration().locale.getDisplayName();
		System.out.println("locale:"+locale);


 

18.Bitmap与byte二进制数组互转

<span style="font-size:12px">//将bitmap转换成byte
public byte[] getBitmapByte(Bitmap bitmap){   
    ByteArrayOutputStream out = new ByteArrayOutputStream();   
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);   
    try {   
        out.flush();   
        out.close();   
    } catch (IOException e) {   
        e.printStackTrace();   
    }   
    return out.toByteArray();   
}
//将byte转换成bitmap
public Bitmap getBitmapFromByte(byte[] temp){   
    if(temp != null){   
        Bitmap bitmap = BitmapFactory.decodeByteArray(temp, 0, temp.length);   
        return bitmap;   
    }else{   
        return null;   
    }   
}</span><strong> </strong>

17.代码添加线性布局LinearLayout和按钮Button

LinearLayout ll = new LinearLayout(this);
		ll.setOrientation(LinearLayout.VERTICAL);
		Button b1 = new Button(this);
		b1.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
		Button b2 = new Button(this);
		b2.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
		ll.addView(b1, 0);
		ll.addView(b2, 1);


16.检查apk文件

public boolean checkApkFile(String apkFilePath) {

        boolean result = false;

        try{

            PackageManager pManager = getPackageManager();

            PackageInfo pInfo = pManager.getPackageArchiveInfo(apkFilePath, PackageManager.GET_ACTIVITIES);

            if (pInfo == null) {

                result =  false;

            } else {

                result =  true;

            }

        } catch(Exception e) {

            result =  false;

            e.printStackTrace();

        }

        return result;

    }

 

15.安装apk文件

public void install(File apkFile){

Uri uri = Uri.fromFile(apkFile);

        Intent intent = new Intent(Intent.ACTION_VIEW);

        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        intent.setDataAndType(uri, "application/vnd.android.package-archive");

        startActivity(intent);

    }

 

14.Android Handler延时发送线程队列code

 

public class MainActivity extends Activity {

	Handler handler =new Handler();
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		handler.postDelayed(runnable, 3000);
	}
	
	//跳转线程
	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			Intent intent = new Intent(MainActivity.this, SlidDraw1.class);
			startActivity(intent);
		}
	};
}


13.ListView Cascade Animation

/**
	 * Animation ListView Cascade瀑布
	 */
	protected void animationListView(ListView listView){
		AnimationSet set = new AnimationSet(true);
		
		Animation animation = new AlphaAnimation(0.0f,1.0f);
		animation.setDuration(50);
		set.addAnimation(animation);
		
		animation = new TranslateAnimation(
			Animation.RELATIVE_TO_SELF,0.0f,Animation.RELATIVE_TO_SELF,0.0f,
			Animation.RELATIVE_TO_SELF,-1.0f,Animation.RELATIVE_TO_SELF,0.0f
		);
		animation.setDuration(100);
		set.addAnimation(animation);
		
		LayoutAnimationController controller = new LayoutAnimationController(set, 0.5f);
		listView.setLayoutAnimation(controller);
	}

12.文件下载

 ①java

class FileDownloader implements Runnable {
			String paramUrl;
			
			public FileDownloader(String paramUrl) {
				super();
				this.paramUrl = paramUrl;
			}

			@Override
			public void run() {
				try {
					long threadID = Thread.currentThread().getId();
					Log.v(LOG_TAG, threadID+" begin run");
					URL downurl = new URL(paramUrl);
					URLConnection connection = downurl.openConnection();
					connection.connect();
					int fileLength = connection.getContentLength();
					// Returns the value of the content-length header field
					InputStream ins = downurl.openStream();// 上面的那个办法已经有一个缓存,下面又自定义了一个缓存,多此一举。直接读取输入流放入自定义缓存
					File f = new File(dir+File.separator+FileUtil.getFileNamefromUrl(paramUrl));
					if (!f.getParentFile().exists()) {
						f.getParentFile().mkdirs();
					}
					OutputStream ous = new FileOutputStream(f);
					Log.v(LOG_TAG, threadID+" file length " + fileLength);
					byte[] buf = new byte[8192];
					long total = 0;
					int count;
					while ((count = ins.read(buf)) != -1) {
						total += count;
						int p = (int) (total * 100 / fileLength);
						ous.write(buf, 0, count);
						//Log.v(LOG_TAG, " read bytes- " + count);
					}
					ous.flush();
					ous.close();
					ins.close();
					Log.v(LOG_TAG, threadID+" finish");
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}

		}


②android

class DownloadThread2 extends Thread{
		public void run(){
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(example_url);
			HttpResponse response;
			try {
				response = client.execute(get);
				HttpEntity entity = response.getEntity();
				long fileLength = entity.getContentLength();
				InputStream is = entity.getContent();
				FileOutputStream fos = null;
				long total = 0;
				if(is != null){
					final String f = SDCardUtil.getFileNamefromUrl(example_url);
					File file = new File(SDCardUtil.makeDir(DOWNLOADDIR)+File.separator+f);
					fos = new FileOutputStream(file);
					byte[] buf = new byte[1024];
					int ch = -1;
					int count = 0;
					while((count = is.read(buf)) != -1){
						fos.write(buf,0,count);
						total += count;
						int p = (int)(total * 100 / fileLength);
						Log.v(Constants.LOG_TAG, " progress- "+p);
						handler.sendEmptyMessage(p);
					}
				}
				fos.flush();
				if(fos != null){
					fos.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

③打印HTTP头信息

final String example_url = "http://support.helloworld.com/Support/Download.jsp?DownloadAudio=2025/11/2025_11_2055.ogg&VoiceFileID=134556879";
					URL downurl = new URL(example_url);
					HttpURLConnection connection = (HttpURLConnection) downurl.openConnection();

					//不自动重定向
					connection.setInstanceFollowRedirects(false);
					int responsecode = connection.getResponseCode();
					System.out.println("responsecode:"+responsecode);
					
					Map<String, List<String>> params = connection.getHeaderFields();
					for(Map.Entry<String, List<String>> header : params.entrySet()){
						System.out.println("key:\t"+header.getKey()+"\tvalue:\t"+header.getValue());
					}

 

 

 

 

 

 

11.纯代码逐帧动画

public void onClick(View v) {
				AnimationDrawable anim = new AnimationDrawable();
				for (int i = 58; i <= 68; i++) {
					int id = getResources().getIdentifier("loadingblack" + i, "drawable", getPackageName());
					Drawable drawable = getResources().getDrawable(id);
					anim.addFrame(drawable, 300);
				}
				anim.setOneShot(false);
				image.setBackgroundDrawable(anim);
				anim.start();
			}

10.Intent传值

Intent it = new Intent();
			it.putExtra(CONTENT, content);
			it.setClass(mActivity, NewsDetailActivity.class);
			mActivity.startActivity(it);


 getIntent:

Intent it = getIntent();
		Log.v(Constants.LOG_TAG, it.getStringExtra(CONTENT));

 

 

9.返回键(方法)函数模板

/**
	 * 返回键的事件处理
	 * 结束这个Activity
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event){
		if(keyCode == KeyEvent.KEYCODE_BACK){
			this.finish();
			Log.i(Constants.LOGTAG, " " + CLASS_TAG + " I'm gone...");
		}
		return true;
	}


 

8.判断SDCard的状态

自定义的一个方法判断SDCard的当前状态,参考的API文档。

访问SD卡权限切记<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

/**
     * 判断SDCard的状态。
     * @return 2:读、写;1:只读;0:不可读不可写
     */
    public int isSDCardAvailable(){
        String state = Environment.getExternalStorageState();

        if (Environment.MEDIA_MOUNTED.equals(state)) {
            // We can read and write the media
            return 2;
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            // We can only read the media
            return 1;
        } else {
            // Something else is wrong. It may be one of many other states, but all we need
            // to know is we can neither read nor write
            return 0;
        }
    	
    }


 

7.判断是否联网

if判断条件中第二个条件也可以用netInfo.isConnected();

/**
	 * 判断网络是否连通
	 */
	private void judgeNetwork() {
		/*
		 * The primary responsibilities of this class(ConnectivityManager) are
		 * to: 
		 * 1.Monitor network connections (Wi-Fi, GPRS, UMTS, etc.) 
		 * 2.Send broadcast intents when network connectivity changes 
		 * 3.Attempt to "fail over" to another network when connectivity to a network is lost
		 * 4.Provide an API that allows applications to query the coarse-grained
		 * or fine-grained state of the available networks
		 * 千万不要忘了在manifest里面加个权限 ,粗心的朋友一定要记住:
		 * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
		 */
		ConnectivityManager conman = (ConnectivityManager) this
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo netInfo = conman.getActiveNetworkInfo();

		if (netInfo != null && netInfo.isAvailable()) {// 可以联网
			Toast.makeText(this, "OK网!", Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(this, "貌似断网了!", Toast.LENGTH_SHORT).show();
		}
	}


 

6.对话框模板

/**
	 * 弹出对话框
	 * @param title 对话框标题
	 * @param msg 对话框内容
	 */
	public void dialog(String title,String msg){
		Builder builder = new AlertDialog.Builder(this);
		
		builder.setTitle(title);	// 对话框标题
		builder.setMessage(msg);	// 对话框内容
		builder.setIcon(R.drawable.ic_launcher);// 对话框的icon
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener(){
			
			@Override
			public void onClick(DialogInterface dialog, int which){
				
			}
		}).setNegativeButton("取消", new DialogInterface.OnClickListener(){
			
			@Override
			public void onClick(DialogInterface dialog, int which){
			
			}
		}).create();
		
		builder.show();
		
	}


 

 

1.获取屏幕宽度和高度

WindowManager wm=getWindowManager();
Display    dp=wm.getDefaultDisplay();
System.out.println(dp.getWidth());
System.out.println(dp.getHeight());
Toast.makeText(this,dp.getWidth()+"=="+dp.getHeight(),  3000).show();

 

2.去除标题栏和状态栏

//取消标题
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//取消状态栏
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
     WindowManager.LayoutParams.FLAG_FULLSCREEN);

 或者在Manifest文件中修改:(android:theme="@android:style/Theme.NoTitleBar.Fullscreen",如果想只是去除标题栏就后面不用加Fullscreen了,另外,如果想要整个应用都去除标题栏和状态栏,就把这句代码加到<application。。标签里面,如果只是想某个activity起作用,这句代码就加到相应的activity上):

3.获取SDcard路径

访问SD卡权限切记<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

// 2.1以及以前的版本用这个获取SDCARD,保存缓存文件等
        File mResPath = Environment.getExternalStorageDirectory();//Environment是android.os.Environment包中的类
        Log.i(CLASS_TAG, " "+mResPath);	// 获取SDCARD根目录/mnt/sdcard
        System.out.println(this.getExternalFilesDir(null).toString());// 获取files的绝对路径
        System.out.println(this.getExternalCacheDir().toString());// 获取cache的绝对路径
        System.out.println(this.getFilesDir().toString());// 获取files的相对路径




4.Java获取系统时间

private String getVideosNames() {
	Date date = new Date();
	SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH-mm");
		return simpleDateFormat.format(date);
	}


5.判断字符串是不是数字

//isNumeric();判断参数是不是一个数字,返回值boolean型
private boolean isNumeric(String s) {
        try {
            Integer.parseInt(s);
        } catch (NumberFormatException e) {
            return false;
        } catch (NullPointerException e) {
            return false;
        }
        return true;
}
 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值