原文地址:http://blog.csdn.net/yudajun/article/details/9119747
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.*{ *;}
判断指定的服务是否运行:
- 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中
-
-
-
-
-
- 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);
-
-
- 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);
-
-
- 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 {
-
-
-
- @Override
- public void onReceive(Context context, Intent intent) {
-
- Intent bootStartIntent=new Intent(context,MainActivity.class);
- bootStartIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- context.startActivity(bootStartIntent);
-
-
- }
- }
获取未安装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);
- }
-
-
-
- private class ApplicationsIntentReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
-
-
- 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();
-
-
-
- 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.setDataAndType(Uri.fromFile(f), "application/vnd.android.package-archive");
- return intent;
- }
-
-
-
-
-
- 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();
- }
-
-
-
-
-
-
-
-
-
-
- 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;
- }
-
-
-
-
-
-
-
-
- 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);
- }
-
-
-
-
-
-
- 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" />
每个月的第几号执行提醒功能:
- Calendar cal = Calendar.getInstance();
-
- cal.set(Calendar.DAY_OF_MONTH, 4);
- cal.set(Calendar.HOUR_OF_DAY, 10);
- cal.set(Calendar.MINUTE, 0);
- cal.set(Calendar.SECOND, 0);
- Date now = new Date(System.currentTimeMillis());
- if (cal.getTime().before(now)) {
- cal.add(Calendar.MONTH, 1);
- }
- long firstTime = cal.getTime().getTime();
- alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, firstTime, 1000 * 60
- * 60 * 24 * 30, pendingIntent);
上传应用到服务器:
- private String newName = "htys.mp3";
-
- private String uploadFile = "/data/data/com.xzq/htys.mp3";
-
- private String actionUrl = "http://192.168.100.100:8080/upload/upload.jsp";
- private void uploadFile()
- {
- String end = "/r/n";
- String Hyphens = "--";
- String boundary = "*****";
- try
- {
- URL url = new URL(actionUrl);
- HttpURLConnection con = (HttpURLConnection) url.openConnection();
-
- con.setDoInput(true);
- con.setDoOutput(true);
- con.setUseCaches(false);
-
- con.setRequestMethod("POST");
-
- con.setRequestProperty("Connection", "Keep-Alive");
- con.setRequestProperty("Charset", "UTF-8");
- con.setRequestProperty("Content-Type",
- "multipart/form-data;boundary=" + boundary);
-
- DataOutputStream ds = new DataOutputStream(con.getOutputStream());
- ds.writeBytes(Hyphens + boundary + end);
- ds.writeBytes("Content-Disposition: form-data; "
- + "name=/"file1/";filename=/"" + newName + "/"" + end);
- ds.writeBytes(end);
-
- FileInputStream fStream = new FileInputStream(uploadFile);
-
- int bufferSize = 1024;
- byte[] buffer = new byte[bufferSize];
- int length = -1;
-
- while ((length = fStream.read(buffer)) != -1)
- {
-
- ds.write(buffer, 0, length);
- }
- ds.writeBytes(end);
- ds.writeBytes(Hyphens + boundary + Hyphens + end);
- fStream.close();
- ds.flush();
-
- InputStream is = con.getInputStream();
- int ch;
- StringBuffer b = new StringBuffer();
- while ((ch = is.read()) != -1)
- {
- b.append((char) ch);
- }
- System.out.println("上传成功");
- Toast.makeText(MainActivity.this, "上传成功", Toast.LENGTH_LONG)
- .show();
- ds.close();
- } catch (Exception e)
- {
- System.out.println("上传失败" + e.getMessage());
- Toast.makeText(MainActivity.this, "上传失败" + e.getMessage(),
- Toast.LENGTH_LONG).show();
- }
- }
- }
创建两个对话框模式进度样式:
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 垂直滚动条
<TextView
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);
- }
-
- @Override
- protected void onDraw(Canvas canvas) {
- super.onDraw(canvas);
- }
- @Override
- public 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 void t(){
- String before = "2013-5-15";
- String now = "2013-5-17";
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
- try {
- Date d1 = sdf.parse(before);
- Date d2 = sdf.parse(now);
- long daysBetween = (d2.getTime() - d1.getTime() + 1000000)
- / (3600 * 24 * 1000);
- System.out.println("相隔:"+daysBetween+"天");
- } catch (Exception e) {
- System.out.println(e.getMessage());
- }
- }