android实用方法收集

这篇博客汇总了Android开发中的多个实用方法,包括获取状态栏高度、设置无滑动ListView、检测SD卡、设置壁纸、获取应用列表等,涵盖了设备信息获取、UI操作和文件管理等多个方面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.获取状态栏的高度

/**
	 * 用于获取状态栏的高度。
	 * 
	 * @return 返回状态栏高度的像素值。
	 */
	private int getStatusBarHeight() {
		if (statusBarHeight == 0) {
			try {
				Class<?> c = Class.forName("com.android.internal.R$dimen");
				Object o = c.newInstance();
				Field field = c.getField("status_bar_height");
				int x = (Integer) field.get(o);
				statusBarHeight = getResources().getDimensionPixelSize(x);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return statusBarHeight;
	}


2.设置listview的高度,使其无滑动效果

	/**
	 * 根据listitem的数量来listview确定高度
	 * 使listview无需滑动
	 * @param listView
	 */
	private void setListViewHeightBasedOnChildren(ListView listView) 
	{
		ListAdapter listAdapter = (ListAdapter) listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) 
        {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }


3.得到设备所有内存

		 	/**
			 * 得到设备的所有RAM
			 * @return 返回所有内存大小,单位:kb
			 */
			private int getAllMemory() {
				String filePath = "/proc/meminfo";
				int ram = 0;
				FileReader fr = null;
				BufferedReader localBufferedReader = null;
				try {
					fr = new FileReader(filePath);
					localBufferedReader = new BufferedReader(fr, 8192);
					String line = localBufferedReader.readLine();
					int a = line.length() - 3;
					int b = line.indexOf(' ');
					String str = line.substring(b, a);
					while (str.substring(0, 1).equals(" ")) {
						str = str.substring(1, str.length());
					}
					ram = Integer.parseInt(str);
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					try {
						fr.close();
						localBufferedReader.close();
					} catch (Exception e) {
						// TODO: handle exception
						e.printStackTrace();
					}
				}
				return ram;
			}

4.得到设备可用内存

			/**
			 * 得到设备的可用RAM
			 * @return 返回所有内存大小,单位:kb
			 */
			private long getAvailMemory(Context context) 
			{
				ActivityManager am = (ActivityManager) context
						.getSystemService(Context.ACTIVITY_SERVICE);
				ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
				am.getMemoryInfo(mi);
				return mi.availMem / 1024;
			}

5.判断指定Service是否正在运行

	/**
	 * 判断指定Service是否正在运行
	 * @param serviceName
	 * @return
	 */
	public boolean isServiceRunning(String serviceName)
	{
		ActivityManager manager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE); 
	    for (RunningServiceInfo service :manager.getRunningServices(Integer.MAX_VALUE)) 
	    { 
	    	if(serviceName.equals(service.service.getClassName()))
	    	{ 
	    		return true; 
	    	} 
	    }
	    return false;
	}

6.获取所有应用列表

	/**
	 * 获取系统的应用列表
	 * @return
	 */
	private List<AppItem> getAppItem()
	{
		List<AppItem> appList = new ArrayList<AppItem>(); //用来存储获取的应用信息数据
		List<AppItem> appListSystem = new ArrayList<AppItem>();
		List<PackageInfo> packages = getPackageManager().getInstalledPackages(0);
		for(int i=0;i<packages.size();i++) 
		{
			PackageInfo packageInfo = packages.get(i);
			//非系统应用加上下面条件
			//packageInfo.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM)==0
			if(!packageInfo.packageName.equals("android")&&!packageInfo.packageName.equals("com.tang.demo360"))
			{
				AppItem item =new AppItem();
				item.setAppName(packageInfo.applicationInfo.loadLabel(getPackageManager()).toString());
				item.setPkgName(packageInfo.packageName);
				item.setIcon(packageInfo.applicationInfo.loadIcon(getPackageManager()));
				if((packageInfo.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM)==0)
				{
                                   //非系统应用
                                   appList.add(item);
				 }
				 else
				 {
					 appListSystem.add(item);
				}
			 }
		}
		 appList.addAll(appListSystem);
		return appList;
	}


7.修改listview的快速滑块

	/**
	 * 修改listview的快速滑块
	 * @param context
	 * @param resId
	 */
	   private void setNewDrawable(Context context,int resId)  
	    {  
	        try {  
	            Field  field = AbsListView.class.getDeclaredField("mFastScroller");  
	            field.setAccessible(true);  
	            Object obj = field.get(this);  
	            field =field.getType().getDeclaredField("mThumbDrawable");        
	            field.setAccessible(true);  
	            Drawable drawable = (Drawable)field.get(obj);  
	            drawable = context.getResources().getDrawable(resId);  
	            field.set(obj, drawable);  
	        } catch (Exception e) {  
	            // TODO Auto-generated catch block  
	            e.printStackTrace();  
	        }  
	    } 


8.textview中插入图片,实现表情发送功能

	private void showImageFace(String s,String[] subString,int[]resId,View v)  
    {  
        Bitmap bitmap;  
        ImageSpan imageSpan;  
        // 创建一个SpannableString对象,以便插入用ImageSpan对象封装的图像  
        SpannableString spannableString = new SpannableString(s);  
        for(int i=0;i<subString.length;i++)  
        {  
            //搜索s中是否存在字串name[i]
        	//字串的长度为3
        	//subString与表情resId一一对应
        	//如果有将imageSpan替换字串name[i]
            int j=0;  
            int start=0;  
            while(s.indexOf(subString[i],start)>=0)  
            {  
                start = s.indexOf(subString[i],start);  
                bitmap = BitmapFactory.decodeResource(getResources(), resId[i]);  
                imageSpan = new ImageSpan(this, bitmap);  
                // 用ImageSpan对象替换字符  
                spannableString.setSpan(imageSpan, start-1, start+2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);     
                start=start+3;  
            }  
        }  
        ((TextView)v).setText(spannableString);  
    } 

9.获取UTC时间

/**
  * 获取UTC时间
  * 
  * UTC + 时区差 = 本地时间(北京为东八区)
  * 
  * @return
  */
 public static long getUTCTime() 
 { 
     //取得本地时间
        Calendar cal = Calendar.getInstance(Locale.CHINA);
        //取得时间偏移量
        int zoneOffset = cal.get(java.util.Calendar.ZONE_OFFSET); 
        //取得夏令时差
        int dstOffset = cal.get(java.util.Calendar.DST_OFFSET); 
        //从本地时间里扣除这些差量,即可以取得UTC时间
        cal.add(java.util.Calendar.MILLISECOND, -(zoneOffset + dstOffset)); 
        return cal.getTimeInMillis();
  }

10.创建桌面快捷方式

private void createShortcut(int iconId,String pkgName,String className)
	{
		 Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
		 String name = getResources().getString(R.string.app_name);
	     shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,name);
	     //不允许重复创建
		 shortcut.putExtra("duplicate", false);  
		 Intent shortcutIntent = new Intent();
		 ComponentName componentName = new ComponentName(pkgName, className);
		 shortcutIntent.setComponent(componentName);
		 shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
		 ShortcutIconResource iconRes=null;
		 iconRes = Intent.ShortcutIconResource.fromContext(this, iconId);
		 shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes); 
		 sendBroadcast(shortcut); 
	}
需要权限:

4.4以下<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>

4.4以上<uses-permission android:name="com.android.launcher3.permission.INSTALL_SHORTCUT"/>


11.将指定图片设为壁纸

 

	public void setWallpaper(Object wallpaper)
	{
		WallpaperManager manager = WallpaperManager.getInstance(this);
		try {
			if(wallpaper instanceof Integer)
				manager.setResource((Integer)wallpaper);
			else if(wallpaper instanceof String)
			{
				Bitmap bitmap = BitmapFactory.decodeFile((String)wallpaper);
				manager.setBitmap(bitmap);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
权限:<uses-permission android:name="android.permission.SET_WALLPAPER" />


12.检测SD卡是否存在

		//检测是否存在SD卡
		public static boolean isSDCardExist()
		{
			String sdStatus = Environment.getExternalStorageState();
			if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) 
			{ 
				return false;
			}
			else return true;
		}

13.搜索指定路径下的所有图片

		 private static boolean isWallpaper(String extension) 
		 {  
	            if (extension == null)  
	                return false;  
	      
	            final String ext = extension.toLowerCase();  
	            if (ext.endsWith("jpg") || ext.endsWith("jpeg") || ext.endsWith("gif") || ext.endsWith("png") ||   
	                    ext.endsWith("bmp") || ext.endsWith("wbmp")) {  
	                return true;  
	            }  
	            return false;  
	     }  
		
		public static List<String> scanWallpaper(String path)
		{
	        File file = new File(path);  
	        if (file==null) 
	        {  
	           Log.d("AAA", "path:"+path+"  路径不存在");
	           return null;
	        }
	        else
	        {  
	        	return wallpaperScanning(file);  
	        }  
		}
		 
		private static List<String> wallpaperScanning(File folder) 
		{  
            Pattern mPattern = Pattern.compile("([^\\.]*)\\.([^\\.]*)");  
            final String[] filenames = folder.list();  
            List<String> wallPaperPath =new ArrayList<String>();
            if (filenames != null) 
            {  
                // 遍历当前目录下的所有文件  
                for (String name : filenames) 
                {
                    File file = new File(folder, name);  
                    // 如果是文件夹则继续递归当前方法  
                    if (file.isDirectory())
                    {  
                    	wallpaperScanning(file);  
                    }   
                    // 如果是文件则对文件进行相关操作  
                    else 
                    {  
                        Matcher matcher = mPattern.matcher(name);  
                        if (matcher.matches()) 
                        {  
                            // 文件名称  
                            String fileName = matcher.group(1);  
                            // 文件后缀  
                            String fileExtension = matcher.group(2);  
                            // 文件路径  
                            String filePath = file.getAbsolutePath();  
                            if (isWallpaper(fileExtension)) 
                            {  
                            	wallPaperPath.add(filePath);
                            }  
                        }  
                    }  
                }  
            }
            return wallPaperPath;
        }  


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值