android 学习笔记有用代码片段(2)
apk代码混淆保护4.0
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
proguard.config=${sdk.dir}/tools/proguard/proguard-android-optimize.txt:proguard-project.txt
# Project target.
target=android-17
如果有报异常,例如这样,
java.io.IOException: Please correct the above warnings first.
at proguard.Initializer.execute(Initializer.java:308)
at proguard.ProGuard.initialize(ProGuard.java:210)
at proguard.ProGuard.execute(ProGuard.java:85)
at proguard.ProGuard.main(ProGuard.java:499)
这是由于第三方jar包的原因哦,
你可以这样,
${sdk.dir}\tools\proguard\proguard-android.txt中加入
-dontwarn com.aa.bb.*
-keep class com.aa.bb.*{ *;}
Java 中.class文件保护
http://blog.sina.com.cn/s/blog_6dc41baf01010khy.html
判断指定的服务是否运行:
public static boolean isServiceRunning(Context ctx, String serviceName, String processName) {ActivityManager manager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {if (serviceName.equals(service.service.getClassName()) && processName.equals(service.process))return true;}return false;}
判断指定进程是否正在运行:
public static boolean isProcessRunning(Context ctx, String name) {ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);List<RunningAppProcessInfo> apps = am.getRunningAppProcesses();for (RunningAppProcessInfo app : apps) {if (app.processName.equals(name)) {return true;}}return false;}
汉字转拼音:
百度搜素pinyin4j.jar 获取官网下载。添加至lib中
/** * 汉字转换为拼音 * @author Administrator * */ public class HanZiToPinYinUtil { public static String toPinYin(String str) { String py = ""; String[] t = new String[str.length()]; char [] hanzi=new char[str.length()]; for(int i=0;i<str.length();i++){ hanzi[i]=str.charAt(i); } net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat t1 = new HanyuPinyinOutputFormat(); t1.setCaseType(HanyuPinyinCaseType.LOWERCASE); t1.setToneType(HanyuPinyinToneType.WITHOUT_TONE); t1.setVCharType(HanyuPinyinVCharType.WITH_V); try { for (int i = 0; i < str.length(); i++) { if ((str.charAt(i) >= 'a' && str.charAt(i) < 'z') || (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') || (str.charAt(i) >= '0' && str.charAt(i) <= '9')) { py += str.charAt(i); } else { t = PinyinHelper.toHanyuPinyinStringArray(hanzi[i], t1); py=py+t[0]; } } } catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } return py.trim().toString(); } public static void main(String args[]){ System.out.println(HanZiToPinYinUtil.toPinYin("我屮艸芔茻")); }
开启飞行模式:
boolean isEnabled = Settings.System.getInt( paramContext.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) == 1; if(isEnabled==true) { Settings.System.putInt( paramContext.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, isEnabled ? 0 : 1); // Post an intent to reload Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED); intent.putExtra("state", !isEnabled); paramContext.sendBroadcast(intent); } else { Settings.System.putInt( paramContext.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, isEnabled ? 0 : 1); // Post an intent to reload Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED); intent.putExtra("state", !isEnabled); paramContext.sendBroadcast(intent); }<uses-permission android:name="android.permission.WRITE_SETTINGS"/><uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"/>
开机自启动:(注意:app一定要安装到内存中,在sd卡上无法自启动)
<receiver android:name="com.pioneersoft.aoc.ui.BootBroadcastReceiver" android:enabled="true" android:exported="true"> <intent-filter > <action android:name="android.intent.action.BOOT_COMPLETED" /> <category android:name="android.intent.category.HOME" /> </intent-filter> </receiver>
public class BootBroadcastReceiver extends BroadcastReceiver {//static final String action_boot="android.intent.action.BOOT_COMPLETED"; @Override public void onReceive(Context context, Intent intent) { // if (intent.getAction().equals(action_boot)){ Intent bootStartIntent=new Intent(context,MainActivity.class); bootStartIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(bootStartIntent);// } }}
获取未安装apk信息:
/** 获取未安装的APK信息 * @param context * @param archiveFilePath APK文件的路径。如:/sdcard /download/XX.apk */ public void getUninatllApkInfo(Context context, String archiveFilePath){ PackageManager pm = context.getPackageManager(); PackageInfo info = pm.getPackageArchiveInfo(archiveFilePath, PackageManager.GET_ACTIVITIES); if(info != null){ ApplicationInfo appInfo = info.applicationInfo; String appName = pm.getApplicationLabel(appInfo).toString(); String packageName = appInfo.packageName; Drawable icon = pm.getApplicationIcon(appInfo); } }
监听apk安装,卸载,替换行为:
private void registerIntentReceivers() { IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED); filter.addAction(Intent.ACTION_PACKAGE_REMOVED); filter.addAction(Intent.ACTION_PACKAGE_CHANGED); filter.addAction(Intent.ACTION_PACKAGE_REPLACED); filter.addDataScheme("package"); registerReceiver(mApplicationsReceiver, filter); } /** * Receives notifications when applications are added/removed. */ private class ApplicationsIntentReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // PackageManager manager = context.getPackageManager(); if (intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED)) { String packageName = intent.getData().getSchemeSpecificPart(); Toast.makeText(context, "安装成功"+packageName, Toast.LENGTH_LONG).show(); } if (intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED)) { String packageName = intent.getData().getSchemeSpecificPart(); Toast.makeText(context, "卸载成功"+packageName, Toast.LENGTH_LONG).show(); } if (intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED)) { String packageName = intent.getData().getSchemeSpecificPart(); Toast.makeText(context, "替换成功"+packageName, Toast.LENGTH_LONG).show(); } } }
loadData()中的html data中不能包含'#', '%', '\', '?'四中特殊字符,出现这种字符就会出现解析错误,显示找不到网页还有部分html代码。需要如何处理呢?我们需要用UrlEncoder编码为%23, %25, %27, %3f 。
可以使用以下两种代码,data为string类型的html代码
1 webView.loadData(URLEncoder.encode(data, "utf-8"), "text/html", "utf-8");
这样一些背景效果什么的都不怎么好看了。不推荐。
2 webView.loadDataWithBaseURL(null,data, "text/html", "utf-8", null);
这样就会完美解析了。
计算网络接收byte[] 字节数组的实际接受内容大小:
public static void main(String[] args) {byte[] bt=new byte[1024];String msg="helo! you are very nice! have a good time! happy every day!";byte[] t=msg.getBytes();for(int i=0;i<t.length;i++){bt[i]=t[i];}String message=new String(bt).trim(); System.out.println(" msg= "+message+" len= "+message.length());}
获取现在正调用的方法名
String methodName =Thread.currentThread().getStackTrace()[1].getMethodName(); String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
/** * 安装app */ public static void openAPK(File f, Context context) { context.startActivity(getInstallApp(f, context)); } public static Intent getInstallApp(File f, Context context) { Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //设置应用的安装来源,例如谷歌市场 intent.putExtra("android.intent.extra.INSTALLER_PACKAGE_NAME", context.getPackageName()); intent.setAction(android.content.Intent.ACTION_VIEW); /* 设置intent的file */ intent.setDataAndType(Uri.fromFile(f), "application/vnd.android.package-archive"); return intent; } /** * 卸载APP * @param context * @param packageName */ public static void uninstallApp(Context context,String packageName) { Uri packageURI = Uri.parse("package:" + packageName); Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI); uninstallIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(uninstallIntent); }
Android屏幕解锁和锁定 //屏幕解锁 KeyguardManager keyguardManager = (KeyguardManager)getSystemService(KEYGUARD_SERVICE); KeyguardLock keyguardLock = keyguardManager.newKeyguardLock(LOCK_TAG); keyguardLock.disableKeyguard(); //屏幕锁定 keyguardLock.reenableKeyguard(); Android屏幕常亮/点亮 //保持屏幕常亮 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, LOCK_TAG); mWakeLock.acquire(); //释放屏幕常亮锁 if(null != mWakeLock) { mWakeLock.release(); }/** * 判断桌面是否已添加快捷方式 * * @param cx * @param titleName * 快捷方式名称 * @return */ public static boolean hasShortcut(Context cx) { boolean result = false; // 获取当前应用名称 String title = null; try { final PackageManager pm = cx.getPackageManager(); title = pm.getApplicationLabel( pm.getApplicationInfo(cx.getPackageName(), PackageManager.GET_META_DATA)).toString(); } catch (Exception e) { } final String uriStr; if (android.os.Build.VERSION.SDK_INT < 8) { uriStr = "content://com.android.launcher.settings/favorites?notify=true"; } else { uriStr = "content://com.android.launcher2.settings/favorites?notify=true"; } final Uri CONTENT_URI = Uri.parse(uriStr); final Cursor c = cx.getContentResolver().query(CONTENT_URI, null, "title=?", new String[] { title }, null); if (c != null && c.getCount() > 0) { result = true; } return result; } /** * * 为当前应用添加桌面快捷方式 * * @param cx * @param appName * 快捷方式名称 */ public static void addShortcut(Context cx) { Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT"); Intent shortcutIntent = cx.getPackageManager() .getLaunchIntentForPackage(cx.getPackageName()); shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); // 获取当前应用名称 String title = null; try { final PackageManager pm = cx.getPackageManager(); title = pm.getApplicationLabel( pm.getApplicationInfo(cx.getPackageName(), PackageManager.GET_META_DATA)).toString(); } catch (Exception e) { } // 快捷方式名称 shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, title); // 不允许重复创建(不一定有效) shortcut.putExtra("duplicate", false); // 快捷方式的图标 Parcelable iconResource = Intent.ShortcutIconResource.fromContext(cx, R.drawable.ic_launcher); shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource); cx.sendBroadcast(shortcut); } /*** * 删除当前应用的桌面快捷方式 * * @param cx */ public static void delShortcut(Context cx) { Intent shortcut = new Intent( "com.android.launcher.action.UNINSTALL_SHORTCUT"); // 获取当前应用名称 String title = null; try { final PackageManager pm = cx.getPackageManager(); title = pm.getApplicationLabel( pm.getApplicationInfo(cx.getPackageName(), PackageManager.GET_META_DATA)).toString(); } catch (Exception e) { } // 快捷方式名称 shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, title); Intent shortcutIntent = cx.getPackageManager() .getLaunchIntentForPackage(cx.getPackageName()); shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); cx.sendBroadcast(shortcut); }相关权限配置 <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" /> <uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" /> <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
/** * 添加快捷方式到桌面 要点: * 1.给Intent指定action="com.android.launcher.INSTALL_SHORTCUT" * 2.给定义为Intent.EXTRA_SHORTCUT_INENT的Intent设置与安装时一致的action(必须要有) * 3.添加权限:com.android.launcher.permission.INSTALL_SHORTCUT */ private void addShortcutToDesktop() { Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT"); // 不允许重建 shortcut.putExtra("duplicate", false); // 设置名字 shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,this.getString(R.string.app_name)); // 设置图标 shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,Intent.ShortcutIconResource.fromContext(this, R.drawable.ic_launcher)); // 设置意图和快捷方式关联程序 shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT,new Intent(this, this.getClass()).setAction(Intent.ACTION_MAIN)); // 发送广播 sendBroadcast(shortcut); } 方法二:首先在xml中设置IntentFilter<intent-filter><action android:name="android.intent.action.CREATE_SHORTCUT" /></intent-filter> if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) {Intent shortcut = new Intent(Intent.ACTION_CREATE_SHORTCUT); // 不允许重建 shortcut.putExtra("duplicate", false); // 设置名字 shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, this.getString(R.string.app_name)); // 设置图标 shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, R.drawable.ic_launcher)); // 设置意图和快捷方式关联的程序 shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(this, this.getClass())); //将结果返回到launcher setResult(RESULT_OK, intent); }在launcher中我们运行程序就可以将快捷方式创建在桌面上。由于快捷方式launcher管理的,我们可以通过查看launcher中是否已经有此快捷方式数据,如果有就不在创建添加权限:<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS"/> private boolean hasInstallShortcut() { boolean hasInstall = false; final String AUTHORITY = "com.android.launcher.settings"; Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/favorites?notify=true"); Cursor cursor = this.getContentResolver().query(CONTENT_URI, new String[] { "title", "iconResource" }, "title=?", new String[] { this.getString(R.string.app_name) }, null); if (cursor != null && cursor.getCount() > 0) { hasInstall = true; } return hasInstall; }
上传文件到服务器:
HttpURLConnection connection = null;DataOutputStream outputStream = null;DataInputStream inputStream = null;String pathToOurFile = "/data/file_to_send.mp3";String urlServer = "http://192.168.1.1/handle_upload.php";String lineEnd = "\r\n";String twoHyphens = "--";String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize;byte[] buffer;int maxBufferSize = 1*1024*1024; try{ FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) ); URL url = new URL(urlServer); connection = (HttpURLConnection) url.openConnection(); // Allow Inputs & Outputs. connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); // Set HTTP method to POST. connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary); outputStream = new DataOutputStream( connection.getOutputStream() ); outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd); outputStream.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // Read file bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { outputStream.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } outputStream.writeBytes(lineEnd); outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) serverResponseCode = connection.getResponseCode(); serverResponseMessage = connection.getResponseMessage(); fileInputStream.close(); outputStream.flush(); outputStream.close();}catch (Exception ex){ //Exception handling}
需要授权用户:
tring usernamePassword = yourUsername + “:” + yourPassword;String encodedUsernamePassword = Base64.encodeToString(usernamePassword.getBytes(), Base64.DEFAULT);connection.setRequestProperty (“Authorization”, “Basic ” + encodedUsernamePassword);
创建两个对话框模式进度样式:
ProgressDialog pdialog = new ProgressDialog(SettingActivity.this,0);
ScrollView 嵌套 ListView GridView问题
public class MyListView extends ListView{ public MyListView(Context context, AttributeSet attrs) { super(context, attrs); } public MyListView(Context context) { super(context); } public MyListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = MeasureSpec.makeMeasureSpec( Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); }}
设置texview 垂直滚动条
android:focusable="true"
android:focusableInTouchMode="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:scrollbars="vertical"
android:singleLine="false"
设置textview 文字水平自动滚动(跑马灯效果)
<com.example.playpic.MyTextView
android:id="@+id/myTv"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textColor="#000000"
android:focusable="true"
android:focusableInTouchMode="true"
android:scrollHorizontally="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"
/>
布局文件需添加属性:android:addStatesFromChildren="true"
修改的textview
public class MyTextView extends TextView {public MyTextView(Context context) {super(context);}public MyTextView(Context context, AttributeSet attrs) {super(context, attrs);}public MyTextView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);}@Overridepublic boolean isFocused() {return true;}}setContentView(R.layout.scrollview1);MyTextView tv=(MyTextView)findViewById(R.id.myTv);tv.setText(str);tv.setMovementMethod(ScrollingMovementMethod.getInstance());
大数据量提高sqlite数据存储效率:
在开发过程中解析xml中的数据有上万条之多,发现在想sqlite中插入的时候非常耗时,原因是没有使用事务,默认是每插入一次使用
一次事务,这样如果插入1w条数据,就要开启1w次事务,非常耗时,所以我们可以通过手动开启和关闭的方式控制事务。
public void insertAll(String databaseName, ArrayList<ContentValues> valuesArr) { SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); for (ContentValues val : valuesArr) { db.insert(databaseName, null, val); } db.setTransactionSuccessful(); db.endTransaction(); db.close(); }
计算日期之间相隔几天:
public long compareDataToNow(String date){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date passDate,nowDate; long diff=-100l,days=-100l; try { passDate = sdf.parse(date); String nowStr=sdf.format(new Date()); nowDate=sdf.parse(nowStr); diff = passDate.getTime() - nowDate.getTime(); days = diff / (1000 * 60 * 60 * 24); System.out.println( "相隔:"+days+"天");} catch (ParseException e) {e.printStackTrace();} return diff;}
更多相关文章
- android获取屏幕长宽的方法
- Android单击屏幕获得坐标,屏幕多点触摸测试器
- Android在外部修改了工程名文件夹名称,报错
- Android桌面隐藏图标
- 如何获取Android设备名称(常用ADB命令介绍)
- 【Android】安卓开机禁止锁屏,禁止屏幕休眠
- Android 屏幕适配,分辨率适配
- 设置Android默认锁定屏幕旋转
- android 屏幕适配方案第二版