您的位置:首页 > 移动开发 > Android开发

Android常用工具方法(关闭软键盘,安装apk,检测程序是否安装...)

2015-08-13 08:50 483 查看
Android如何关闭系统软键盘:

/**
* 关闭系统的软键盘
* @param activity
*/
public static void dismissSoftKeyboard(Activity activity)
{
View view = activity.getWindow().peekDecorView();
if (view != null)
{
InputMethodManager inputmanger = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}


Android检测程序是否安装:

/**
* 检测某程序是否安装
*/
public static boolean isInstalledApp(Context context, String packageName)
{
Boolean flag = false;

try
{
PackageManager pm = context.getPackageManager();
List<PackageInfo> pkgs = pm.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);
for (PackageInfo pkg : pkgs)
{
// 当找到了名字和该包名相同的时候,返回
if ((pkg.packageName).equals(packageName))
{
return flag = true;
}
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

return flag;
}


Android安装apk文件:

/**
* 安装.apk文件
*
* @param context
*/
public void install(Context context, String fileName)
{
if (TextUtils.isEmpty(fileName) || context == null)
{
return;
}
try
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(fileName)), "application/vnd.android.package-archive");
context.startActivity(intent);
}
catch (Exception e)
{
e.printStackTrace();
}
}

/**
* 安装.apk文件
*
* @param context
*/
public void install(Context context, File file)
{
try
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
context.startActivity(intent);
}
catch (Exception e)
{
e.printStackTrace();
}
}
Android中dp与px互相转换:
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*
* @return 返回像素值
*/
public static int dp2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
<pre name="code" class="java">在strings.xml中添加字符串
string name="text">你好,%s!</string>
代码中使用
textView.setText(String.format(getResources().getString(R.string.text),"Android"));
输出结果:Hello,Android!



strings.xml中s%的用法:

在strings.xml中添加字符串
string name="text">你好,%s!</string>
代码中使用
textView.setText(String.format(getResources().getString(R.string.text),"Android"));
输出结果:你好,Android!


str
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android