Android开发中常用技巧汇集
android.content.pm.PackageManager:
首先,用 Context.getPackageManager() 的到这个类。
这个类里提供了各种操作 Package 的方法。
比如 addPermission() 动态的添加许可,
getInstalledApplications() 返回一个内容为所有已安装的程序的ApplicationInfo类(这个类里的uid属性非常有用)的List....
详细的去看文档。
android.net.TrafficStats:
这个类是2.2新加的,主要功能就是获取流量统计相关的信息,使用方法文档都有写,非常简单,不再赘述,有一点要注意,这个类在有的平台上可能用不了,会返回UNSUPPORTED。
java.text.DecimalFormat
这个类是用来格式化整形的,是java本身自带的,详细的还没研究,先记录下。
android.text.format.Time
一个更快的时间格式处理类,用来替换java.util.Calendar和java.util.GregorianCalendar类,一个实例就代表一个时间瞬间,具体看文档。(注意,有的时候别忘了setToNow().....)
android.app.IntentService
Service的子类,用来简便的使用服务的类,主要特点是服务代码运行完就立即返回,并关闭服务,看文档实例就明白了:
/**
* 必须要有构造函数,并且这个构造函数必须调用父类的构造函数 IntentService(String)
*/
public HelloIntentService() {
super("HelloIntentService");
}
/**
* The IntentService calls this method from the default worker thread with
* the intent that started the service. When this method returns, IntentService
* stops the service, as appropriate.
*/
@Override
protectedvoid onHandleIntent(Intent intent) {
// 这里一般放工作代码,比如下载。
// 作为例子,这里就睡眠5秒。
long endTime = System.currentTimeMillis() +5*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
}
}
android.os.Process
这个类用来管理android系统的进程,比如设置优先级方法setThreadPriority(),获取进程所使用的cpu时间getElapsedCpuTime(),发送信号sendSignal(int pid, int signal)...等等,还有一大堆常量,比如优先级系列的THREAD_PRIORITY_*和信号系列SIGNAL_*等等...
android.content.ContextWrapper.getSystemService(String name)
Return the handle to a system-level service by name. The class of the returned object varies by the requested name.
Currently available names are:
WINDOW_SERVICE
("window")- The top-level window manager in which you can place custom windows. The returned object is a
WindowManager
. LAYOUT_INFLATER_SERVICE
("layout_inflater")- A
LayoutInflater
for inflating layout resources in this context. ACTIVITY_SERVICE
("activity")- A
ActivityManager
for interacting with the global activity state of the system. POWER_SERVICE
("power")- A
PowerManager
for controlling power management. ALARM_SERVICE
("alarm")- A
AlarmManager
for receiving intents at the time of your choosing. NOTIFICATION_SERVICE
("notification")- A
NotificationManager
for informing the user of background events. KEYGUARD_SERVICE
("keyguard")- A
KeyguardManager
for controlling keyguard. LOCATION_SERVICE
("location")- A
LocationManager
for controlling location (e.g., GPS) updates. SEARCH_SERVICE
("search")- A
SearchManager
for handling search. VIBRATOR_SERVICE
("vibrator")- A
Vibrator
for interacting with the vibrator hardware. CONNECTIVITY_SERVICE
("connection")- A
ConnectivityManager
for handling management of network connections. WIFI_SERVICE
("wifi")- A
WifiManager
for management of Wi-Fi connectivity. INPUT_METHOD_SERVICE
("input_method")- An
InputMethodManager
for management of input methods. UI_MODE_SERVICE
("uimode")- An
UiModeManager
for controlling UI modes. DOWNLOAD_SERVICE
("download")- A
DownloadManager
for requesting HTTP downloads
Note: System services obtained via this API may be closely associated with the Context in which they are obtained from. In general, do not share the service objects between various different contexts (Activities, Applications, Services, Providers, etc.)
Parameters
name | The name of the desired service. |
---|
Returns
The service or null if the name does not exist.
在外部线程访问UI线程来更新UI:
- Activity.runOnUiThread(Runnable)
- View.post(Runnable)
- View.postDelayed(Runnable, long)
- Handler
更好的LOG,完整的显示调用堆栈:
StackTraceElement stes[] = new Throwable().fillInStackTrace()
.getStackTrace();
for (StackTraceElement a : stes) {
android.util.Log.i("Log === ", a.toString());
}
判断当前线程是否为主UI线程的方法:
long currentId = Thread.currentThread().getId();
long mainId = Looper.getMainLooper().getThread().getId();
如果ID一样,则是主线程,否则不是。
windowSoftInputMode的用法:
这个属性在AndroidManifest.xml中的Activity标签里指定,只有两类值:stateXXXX和adjustXXXX,其中state是表明这个activity在获得焦点时是否自动显示出软件盘,adjust表明软件盘弹出时相应界面的变化。
动态切换EditText是否允许修改:
允许修改:
editText.setFocusableInTouchMode(true);
不允许修改:
editText.setFocusableInTouchMode(false);
editText.clearFocus();
尝试过其他方法包括setFocusable(),setEnable()等,都只能在xml文件中静态设置。setInputType()虽然可以,但会破坏文本的换行显示特性。
正确启动第三方应用:
如果Third应用已经启动,则切换,否则启动该应用的LaunchActivity
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); List<RunningTaskInfo> recentList = am.getRunningTasks(30); for (RunningTaskInfo info : recentList) { if (info.topActivity.getPackageName().equals("com.demo")) { am.moveTaskToFront(info.id, 0); return; } } Intent it = new Intent(); it.setComponent(new ComponentName("com.demo", "com.demo.LoginActivity")); startActivity(it);
需要两个权限:
<uses-permission android:name="android.permission.GET_TASKS" /> <uses-permission android:name="android.permission.REORDER_TASKS" />
或者只使用Intent.FLAG_ACTIVITY_NEW_TASK,不同应用使用这个标志无效。
JAVA反射,调用静态私有方法:
代码如下:
public class Demo { private static String getS(int a) { return ""; } }
Method method = Demo.class.getDeclaredMethod("getS", int.class); method.setAccessible(true); String result = (String) method.invoke(null, 14);
查看Android设备为进程分配内存大小:
dalvik.vm.heapsize=24m
src=/源码或者源码包的绝对路径/acra-4.5.0-sources.jar
然后关闭再打开项目就可以了
Eclipse创建文件时自动添加作者信息注释:
设置eclipse参数
windows-->preference
Java-->Code Style-->Code Templates
code-->new Java files
原来的内容是:
${filecomment}
${package_declaration}
${typecomment}
${type_declaration}
添加自定义内容,添加之后内容如下:
${filecomment}
${package_declaration}
/**
* @author 作者 E-mail:
* @version 创建时间:${date} ${time}
* 类说明
*/
${typecomment}
${type_declaration}