一些常用的代码片段,摘录下来留着用...
/**
* 子线程更新UI示例
*/
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
// a potentially time consuming task
final Bitmap bitmap =
processBitMap("image.png");
imageView.post(new Runnable() {
public void run() {
imageView.setImageBitmap(bitmap);
}
});
}
}).start();
}
/**
* 弱引用使用
*/
public void setData(String key, Object object) {
WeakReference value =new WeakReference<>(object);
dataList.put(key, value);
}
/**
* 泛型示例
*/
double a = FanTest1.MaxNum(2.3, 3.5, 5.4);
public static <T extends Comparable<T>> T MaxNum(T x, T y, T z)
{
T max = x;
if(y.compareTo(max)>0)
{
max = y;
}
return max;
}
/**
* Thread带Looper示例
*/
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler(Looper.myLooper()) {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
/**
* 打开一个网页
*/
private void clickMall() {
String requestURL = "http://applink.dossav.com/shop";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(requestURL));
startActivity(intent);
}
/**
* 判断时间差
*/
public static Date g_LastDate = new Date(System.currentTimeMillis());
long diff = new Date(System.currentTimeMillis()).getTime()
- g_LastDate.getTime();
if (diff < 5000) { //5秒
return;
}
/**
* Handler发送消息示例
*/
private static final int MSG_SHOW_NETWORKNOTACCESS = 200;
private Handler mHandler = new Handler(Looper.getMainLooper())
{
@Override
public void handleMessage(Message msg) {
switch (msg.what)
{
case MSG_SHOW_NETWORKACCESS:
//do something
break;
}
}
};
mHandler.sendEmptyMessage(MSG_SHOW_NETWORKACCESS);
/**
* UI线程执行
*/
runOnUiThread(new Runnable() {
@Override
public void run() {
//刷新UI
}
});
/**
* 创建子线程
*/
new Thread() {
public void run() {
System.out.println("Thread is running.");
}
}.start();
/**
* 判断WIFI连接的是2.4G还是5G WIFI
*/
WifiManager wifiManager = (WifiManager)getApplicationContext(). getSystemService(Context.WIFI_SERVICE);//注意用getApplicationContext可以避免android内存泄漏.
WifiInfo wifiInfo= wifiManager.getConnectionInfo();
int frequency = wifiInfo.getFrequency();//以5开关是5G WIFI, 2开头是2.4G
Log.i(TAG, "frequency = " + frequency );
//备注:AndroidManifest.xml权限要加
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
参考示例:
1.
Android开发人员不得不收集的代码(持续更新中)_饭小粒的博客-CSDN博客
2. 安卓开发示例代码总结(持续更新中...)_achirandliu的博客-CSDN博客_android应用开发案例教程代码