获得应用的launch_intent

1
PackageManager.getLaunchIntentForPackage(PackageName);

截取应用界面

1
2
3
4
5
6
ImageView im = (ImageView)findViewById(R.id.ImageView);
Bitmap bmp = Bitmap.createBitmap(320, 480, Config.ARGB_8888);
View cv = getWindow().getDecorView();
cv.draw(new Canvas(bmp));
im.setScaleType(ScaleType.FIT_XY);
im.setImageBitmap(bmp);

动态申请权限

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
if (ContextCompat.checkSelfPermission(aty, Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {//返回GRANTED时表示已授权
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS))
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
ActivityCompat.requestPermissions(aty,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);//这是个异步的方法
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults)
{

switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
}
}

捕获程序异常,自定义处理异常的方法

1
2
3
4
5
6
7
8
9
10
11
Intent intent = new Intent();
intent.setClassName("packagename", "packagename+activity");
restartIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
Thread.setDefaultUncaughtExceptionHandler(restartHandler);//程序崩溃时触发线程
public UncaughtExceptionHandler restartHandler = new UncaughtExceptionHandler() {
public void uncaughtException(Thread thread, Throwable ex) {
AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent);//1秒钟后重启应用
new ActivityContrl().finishProgram();// 自定义方法,关闭当前打开的所有avtivity
}
};

判断某个界面是否处于前台显示状态

1.官方不推荐此方法
2.需要加权限android.permission.GET_TASKS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
private boolean isForeground(Context context, String className) {
if (context == null || className == null || className.equalsIgnoreCase("")) {
return false;
}
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List list = am.getRunningTasks(1);
if (list != null && list.size() > 0) {
ComponentName cpn = list.get(0).topActivity;
if (className.equals(cpn.getClassName())) {
return true;
}
}
return false;
}

3.推荐这个方法

1
2
3
4
5
6
7
8
9
10
11
12
13
private boolean isTopActivity(String $packageName) {
ActivityManager am = (ActivityManager) _context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
List list = am.getRunningAppProcesses();
if(list.size() == 0) return false;
for(ActivityManager.RunningAppProcessInfo process:list) {
Log.d(getTAG(),Integer.toString(process.importance));
Log.d(getTAG(),process.processName);
if(process.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && process.processName.equals($packageName)) {
return true;
}
}
return false;
}

LinearLayout最大高度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics metrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(metrics);
int pixelsHeight = metrics.heightPixels;
int maxHeight = (int) (pixelsHeight*0.4427);
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
if (heightMode == MeasureSpec.UNSPECIFIED) {
return;
}
int height = getMeasuredHeight();
int specWidthSize = MeasureSpec.getSize(widthMeasureSpec);
if (height > maxHeight) {
setMeasuredDimension(specWidthSize, maxHeight);
} else {
setMeasuredDimension(specWidthSize, height);
}
}

创建另外一个包的上下文

这个实例不同于它本身的Context实例,但是功能是一样的

1
2
3
4
Context c = createPackageContext("chroya.demo", Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);
Class clazz = c.getClassLoader().loadClass("chroya.demo.Main");
Object owner = clazz.newInstance();
Object obj = clazz.getMethod("print", String.class).invoke(owner, "Hello");

获取设备唯一码

1
2
3
4
//GSM与WCDMA手机是使用IMEI号,IMEI号是15位数字
//CDMA手机则使用MEID号,MEID号是14位的16进制串
TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
tm.getDeviceId();

EditText弹出/隐藏软键盘

1
2
3
4
5
6
7
8
9
10
11
12
13
//点击EditText的时候弹出软键盘,点击EditText之外空白处软键盘
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) { if (myActivity.this.getCurrentFocus() != null) {
if (myActivity.this.getCurrentFocus().getWindowToken() != null) {
imm.hideSoftInputFromWindow(myActivity.this.getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
return super.onTouchEvent(event);
}

DownloadManager消息通知

1
2
3
4
5
6
//是否显示DownloadManager消息通知的设置
if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
} else {
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
}

监听DownloadManager的下载进度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//监听DownloadManager的下载进度(如果界面上过多元素需要更新,且网速较快不断的执行onChange会对页面性能有一定影响)
public static final Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads");
Uri uri = Uri.parse("http://commonsware.com/1.apk");
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdir();
lastDownloadId = dowanloadmanager.enqueue(
new DownloadManager.Request(uri)
.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI)
.setAllowedOverRoaming(false)
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "1.apk")
);
registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
downloadObserver = new DownloadChangeObserver(null);
getContentResolver().registerContentObserver(CONTENT_URI, true, downloadObserver);
class DownloadChangeObserver extends ContentObserver {
public DownloadChangeObserver(Handler handler) {super(handler);}
@Override
public void onChange(boolean selfChange) {queryDownloadStatus();}
}

线程恢复

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private static final String WORKER_KEY = "thread_id";
private Thread worker;
protected void onCreate(Bundle savedInstanceState) {
if (savedInstanceState != null) {
final long threadId = savedInstanceState.getLong(WORKER_KEY);
worker = findThreadById(threadId);
}
}
protected void onSaveInstanceState(Bundle outState) {
outState.putLong(worker.getId());
}
protected void onDestroy() {
if (worker != null) {
worker.interrupt();
worker = null;
}
}

添加快捷方式到桌面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
private void addShortcut(String name) {
Intent addShortcutIntent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
addShortcutIntent.putExtra("duplicate", false);//不允许重复创建//经测试不是根据快捷方式的名字判断重复的
addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);// 名字
addShortcutIntent.putExtra(
Intent.EXTRA_SHORTCUT_ICON_RESOURCE,// 图标
Intent.ShortcutIconResource.fromContext(MainActivity.this, R.drawable.ic_launcher)
);

Intent launcherIntent = new Intent(Intent.ACTION_MAIN);// 设置关联程序
launcherIntent.setClass(MainActivity.this, MainActivity.class);
launcherIntent.addCategory(Intent.CATEGORY_LAUNCHER);
addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launcherIntent);
sendBroadcast(addShortcutIntent);// 发送广播
}

创建桌面快捷方式

1
2
3
4
5
6
7
8
9
10
11
12
Intent addShortCut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
String title = "快捷方式";
Parcelable icon = Intent.ShortcutIconResource.fromContext(ShortcutRepeatCreateActivity.this, R.drawable.smil);//图标,通常是png格式
Intent intent = new Intent(ShortcutRepeatCreateActivity.this, MainActivityGroup.class);
// 如果删除了应用程序,可是快捷方式无法删除,加下面这两个句代码就OK了(桌面图标与应用程序绑定),
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
addShortCut.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);// 设置快捷方式的标题
addShortCut.putExtra("duplicate", false);// false:不允许重复创建 ;true:允许
addShortCut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);//快捷方式图标
addShortCut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);//快捷方式启动的Intent
sendBroadcast(addShortCut);// 向launcher发送广播,添加快捷方式

用support库自带的API实现网络工具类的封装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
getSupportLoaderManager().initLoader(0, null, new LoaderCallbacks<JSONObject>() {
@Override
public Loader<JSONObject> onCreateLoader(int id, Bundle bundle) {
return new JSONLoader(getApplicationContext(), "http://www.google.com/uds/GnewsSearch?q=Obama&v=1.0");
}
@Override
public void onLoadFinished(Loader<JSONObject> loader, JSONObject result) {
getSupportLoaderManager().destroyLoader(0);
}
@Override
public void onLoaderReset(Loader<JSONObject> loader) {}
});
public class JSONLoader extends AsyncTaskLoader<JSONObject> {
private String url = "http://localhost";
public JSONLoader(Context context, String url) {
super(context);
this.url = url;
forceLoad();
}
@Override
public JSONObject loadInBackground() {
HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse res = null;
try {
res = httpClient.execute(get);
HttpEntity entity = res.getEntity();
String body = EntityUtils.toString(entity);
return new JSONObject(body);
} catch (ParseException e) {
} catch (IOException e) {
} catch (JSONException e) {}
return null;
}
}

获取设备ID

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//android.permission.READ_PHONE_STATE
public static String getPhoneId(Context context) {
String id = "";
TelephonyManager mTelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
// 获取IMSI号
id = mTelephonyMgr.getSimSerialNumber();
if (!StringTools.IsNullOrEmpty(id))
return "S" + id;
// 获取IMEI号
id = mTelephonyMgr.getDeviceId();
if (!StringTools.IsNullOrEmpty(id))
return "E" + id;
if (StringTools.IsNullOrEmpty(id)) {
// 通过ID生成器获取编码
id = DBTools.getDataFromCommonDB(context, PHONE_ID);
if (StringTools.IsNullOrEmpty(id)) {
try {
id = "R" + IdGeneratorTools.Instance().NextLong();
DBTools.saveDataForCommonDB(context, new KeyValuePair<String, String>(PHONE_ID, id));
} catch (Exception e) {}
}
}
return id;
}

带实时进度的对话框

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
progressDialog = new ProgressDialog(this);
progressDialog.setIcon(R.drawable.ic_launcher);
progressDialog.setTitle("实时进度...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);//设置模态窗口
progressDialog.setButton(ProgressDialog.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
isRun = false;//中断线程
Toast.makeText(getBaseContext(), "确定按钮被点击!", Toast.LENGTH_SHORT).show();
}
});
progressDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
isRun = false;//中断线程
Toast.makeText(getBaseContext(), "取消按钮被点击!", Toast.LENGTH_SHORT).show();
}
});
progressDialog.show();
progressDialog.setProgress(0);
progressDialog.incrementProgressBy(100/20);

下拉菜单

1
2
3
4
5
6
7
8
9
10
11
12
13
pop = new PopupWindow(listView, etLoginName.getWidth(),LayoutParams.WRAP_CONTENT);
pop.showAsDropDown(etLoginName);//下拉框显示在文本框etLoginName的下方

<Spinner android:id="@+id/planets_spinner" android:layout_width="fill_parent" android:layout_height="wrap_content" />
Spinner spinner = (Spinner) findViewById(R.id.planets_spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.planets_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new SelectListener());
private class SelectListener implements AdapterView.OnItemSelectedListener {}

进程管理

1
2
3
4
5
6
7
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> pi = am.getRunningAppProcesses();
ActivityManager.RunningAppProcessInfo pii = (ActivityManager.RunningAppProcessInfo) pi.get(i);
Debug.MemoryInfo[] mi = am.getProcessMemoryInfo(mem);
int size = mi[0].dalvikPrivateDirty;//占用的内存大小,通常是kb
String name = pii.processName;//进程名
am.killBackgroundProcesses(name);

统一Toast动画,使Toast动画不再因不同系统而产生差异

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private static void updateToastAnim(Toast toast) {
if (toast != null) {
try {
Object mTN = ReflectUtils.getField(toast, "mTN");
if (mTN != null) {
Object mParams = ReflectUtils.getField(mTN, "mParams");
if (mParams != null && mParams instanceof WindowManager.LayoutParams) {
WindowManager.LayoutParams params = (WindowManager.LayoutParams) mParams;
params.windowAnimations = R.style.Lite_Animation_Toast;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

自定义Spinner样式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
1.layout里的定义
<Spinner android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/edit_text_bg"
android:spinnerMode="dropdown" android:popupBackground="@android:color/transparent"/>

2.代码里的设置
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.war_result_spinner_selection, R.id.war_result_server_name, List<String>);
adapter.setDropDownViewResource(R.layout.war_result_spinner_item);
spinner.setAdapter(adapter);
3.war_result_spinner_selection.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">

<TextView android:layout_width="match_parent" android:layout_height="wrap_content"
android:id="@+id/war_result_server_name" style=""/>

</LinearLayout>
4.war_result_spinner_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">

<TextView android:layout_width="match_parent" android:layout_height="29dp"
android:id="@+id/war_result_server_name" style=""/>

</LinearLayout>