android常用接口(二)
时间:2022-04-26
本文章向大家介绍android常用接口(二),主要内容包括bitmap转Byte数组(微信分享就需要用到)、Resources转Bitmap、保存图片到SD卡、判断是否APK是否安装过、安装APK、卸载APK、判断SD卡是否可用、创建快捷方式:、判断快捷方式是否创建:、过滤特殊字符:、执行shell语句:、获得文件MD5值:、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。
=图片==========================
bitmap转Byte数组(微信分享就需要用到)
public byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
ByteArrayOutputStream output = new ByteArrayOutputStream();
bmp.compress(CompressFormat.PNG, 100, output); if (needRecycle) {
bmp.recycle();
} byte[] result = output.toByteArray(); try {
output.close();
} catch (Exception e) {
e.printStackTrace();
} return result;
}
Resources转Bitmap
public Bitmap loadBitmap(Resources res, int id) {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inPurgeable = true;
opt.inInputShareable = true;
InputStream is = res.openRawResource(id);// 获取资源图片
return BitmapFactory.decodeStream(is, null, opt);
}
保存图片到SD卡
public void saveBitmapToFile(String url, String filePath) {
File iconFile = new File(filePath); if (!iconFile.getParentFile().exists()) {
iconFile.getParentFile().mkdirs();
} if (iconFile.exists() && iconFile.length() > 0) { return;
}
FileOutputStream fos = null;
InputStream is = null; try {
fos = new FileOutputStream(filePath);
is = new URL(url).openStream(); int data = is.read(); while (data != -1) {
fos.write(data);
data = is.read();
}
} catch (IOException e) {
e.printStackTrace();
} finally { try { if (is != null) {
is.close();
} if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
=系统==============================
#根据包名打开一个应用程序 public boolean openApp(String packageName) {
PackageInfo pi = null; try {
pi = mPM.getPackageInfo(packageName, 0);
} catch (NameNotFoundException e) {
e.printStackTrace(); return false;
} if (pi == null) { return false;
}
Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
resolveIntent.setPackage(pi.packageName);
List<ResolveInfo> apps = mPM.queryIntentActivities(resolveIntent, 0);
ResolveInfo ri = null; try {
ri = apps.iterator().next();
} catch (Exception e) { return true;
} if (ri != null) {
String tmpPackageName = ri.activityInfo.packageName;
String className = ri.activityInfo.name;
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
ComponentName cn = new ComponentName(tmpPackageName, className);
intent.setComponent(cn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MarketApplication.getMarketApplicationContext().startActivity(
intent);
} else { return false;
} return true;
}
判断是否APK是否安装过
public boolean checkApkExist(Context context, String packageName) { if (packageName == null || "".equals(packageName)) return false; try {
ApplicationInfo info = context.getPackageManager()
.getApplicationInfo(packageName,
PackageManager.GET_UNINSTALLED_PACKAGES); return true;
} catch (NameNotFoundException e) { return false;
} catch (NullPointerException e) { return false;
}
}
安装APK
public void installApk(Context context, String strFileAllName) {
File file = new File(strFileAllName);
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
String type = "application/vnd.android.package-archive";
intent.setDataAndType(Uri.fromFile(file), type);
context.startActivity(intent);
}
卸载APK
public void UninstallApk(Context context, String strPackageName) {
Uri packageURI = Uri.parse("package:" + strPackageName);
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
context.startActivity(uninstallIntent);
}
判断SD卡是否可用
public boolean CheckSD() { if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) { return true;
} else { return false;
}
}
创建快捷方式:
public void createShortCut(Context contxt) { // if (isInstallShortcut()) {// 如果已经创建了一次就不会再创建了
// return;
// }
Intent sIntent = new Intent(Intent.ACTION_MAIN);
sIntent.addCategory(Intent.CATEGORY_LAUNCHER);// 加入action,和category之后,程序卸载的时候才会主动将该快捷方式也卸载
sIntent.setClass(contxt, Login.class);
Intent installer = new Intent();
installer.putExtra("duplicate", false);
installer.putExtra("android.intent.extra.shortcut.INTENT", sIntent);
installer.putExtra("android.intent.extra.shortcut.NAME", "名字");
installer.putExtra("android.intent.extra.shortcut.ICON_RESOURCE",
Intent.ShortcutIconResource
.fromContext(contxt, R.drawable.icon));
installer.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
contxt.sendBroadcast(installer);
}
判断快捷方式是否创建:
private boolean isInstallShortcut() { boolean isInstallShortcut = false; final ContentResolver cr = MarketApplication
.getMarketApplicationContext().getContentResolver();
String AUTHORITY = "com.android.launcher.settings";
Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
+ "/favorites?notify=true");
Cursor c = cr.query(CONTENT_URI, new String[] { "title", "iconResource" }, "title=?", new String[] { "名字" }, null); if (c != null && c.getCount() > 0) {
isInstallShortcut = true;
} if (c != null) {
c.close();
} if (isInstallShortcut) { return isInstallShortcut;
}
AUTHORITY = "com.android.launcher2.settings";
CONTENT_URI = Uri.parse("content://" + AUTHORITY
+ "/favorites?notify=true");
c = cr.query(CONTENT_URI, new String[] { "title", "iconResource" }, "title=?", new String[] { "名字" }, null); if (c != null && c.getCount() > 0) {
isInstallShortcut = true;
} if (c != null) {
c.close();
}
AUTHORITY = "com.baidu.launcher";
CONTENT_URI = Uri.parse("content://" + AUTHORITY
+ "/favorites?notify=true");
c = cr.query(CONTENT_URI, new String[] { "title", "iconResource" }, "title=?", new String[] { "名字" }, null); if (c != null && c.getCount() > 0) {
isInstallShortcut = true;
} if (c != null) {
c.close();
} return isInstallShortcut;
}
过滤特殊字符:
private String StringFilter(String str) throws PatternSyntaxException { // 只允许字母和数字
// String regEx = "[^a-zA-Z0-9]";
// 清除掉所有特殊字符
String regEx = "[`~!@#$%^&*()+=|{}':;',//[//].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str); return m.replaceAll("").trim();
}
执行shell语句:
public int execRootCmdSilent(String cmd) { int result = -1;
DataOutputStream dos = null; try {
Process p = Runtime.getRuntime().exec("su");
dos = new DataOutputStream(p.getOutputStream());
dos.writeBytes(cmd + "n");
dos.flush();
dos.writeBytes("exitn");
dos.flush();
p.waitFor();
result = p.exitValue();
} catch (Exception e) {
e.printStackTrace();
} finally { if (dos != null) { try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} return result;
}
获得文件MD5值:
public String getFileMD5(File file) { if (!file.isFile()) { return null;
}
MessageDigest digest = null;
FileInputStream in = null; byte buffer[] = new byte[1024]; int len; try {
digest = MessageDigest.getInstance("MD5");
in = new FileInputStream(file); while ((len = in.read(buffer, 0, 1024)) != -1) {
digest.update(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace(); return null;
} finally { if (in != null) { try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
BigInteger bigInt = new BigInteger(1, digest.digest()); return bigInt.toString(16);
}
- 如何从微信公众平台上下载关注用户(备份微信关注用户)
- 使用hive客户端java api读写hive集群上的信息
- 大数据算法设计模式(1) - topN spark实现
- redis性能调优笔记(can not get Resource from jedis pool和jedis connect time out)
- thrift例子:python客户端/java服务端
- springboot与thrift集成实现服务端和客户端
- 调用{dede:likewords}为dedecms添加相关搜索词
- 重新调整Keras中长短期记忆网络的输入数据
- Linux内存(手动释放cache)
- django中间件Middleware
- springboot kafka集成(实现producer和consumer)
- 分布式锁的实现(redis)
- springboot scheduled并发配置
- RabbitMQ高可用集群配置
- java教程
- Java快速入门
- Java 开发环境配置
- Java基本语法
- Java 对象和类
- Java 基本数据类型
- Java 变量类型
- Java 修饰符
- Java 运算符
- Java 循环结构
- Java 分支结构
- Java Number类
- Java Character类
- Java String类
- Java StringBuffer和StringBuilder类
- Java 数组
- Java 日期时间
- Java 正则表达式
- Java 方法
- Java 流(Stream)、文件(File)和IO
- Java 异常处理
- Java 继承
- Java 重写(Override)与重载(Overload)
- Java 多态
- Java 抽象类
- Java 封装
- Java 接口
- Java 包(package)
- Java 数据结构
- Java 集合框架
- Java 泛型
- Java 序列化
- Java 网络编程
- Java 发送邮件
- Java 多线程编程
- Java Applet基础
- Java 文档注释
- 工作流和状态机
- CentOS 6.x 搭建:Headless Chrome + ChromeDriver + Selenium的爬虫环境系统
- 聊聊dubbo-go的registryAwareCluster
- 同样是空值,null和undefined有什么异同?
- 强大到没朋友的mysql-shell及插件
- android JavaPoet记录
- JavaScript里的分号,你加还是不加?
- 技术干货 | Docker 容器逃逸案例汇集
- 一张千万级别数据的表想做分页,如何优化?
- 一文学会爬虫技巧
- 为什么机器学习应用交易那么难(中)
- 消息队列的消费幂等性如何保证
- js中数组Array.reduce方法介绍及使用场景
- 推荐一套基于go开发的文档管理系统
- 如何通过容器搭建稳定可靠的私有网盘(NextCloud)