android使用技巧知识



EditText ed = new EditText(this);
Editable eb = ed.getEditableText();

//获取光标位置
int position = ed.getSelectionStart();

//指定位置插入字符
eb.insert(position, "XXX");

//给你的EditText设置输入类型 TYPE_CLASS_NUMBER,这样你在点击EditText的时 候,默认弹出的键盘模式就是数字键盘。
ed.setInputType(InputType.TYPE_CLASS_NUMBER);

//插入图片
//定义图片所占字节数(“Tag”的长度)
SpannableString ss = new SpannableString("Tag");
//定义插入图片
Drawable drawable = getResources().getDrawable(R.drawable.icon);
ss.setSpan(new ImageSpan(drawable,ImageSpan.ALIGN_BASELINE), 0, ss.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
drawable.setBounds(2, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
//插入图片
eb.insert(position, ss);


//设置可输入最大字节数
ed.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});


//拉起lancher桌面
Intent i = new Intent(Inten.ACTION_MAIN);
i.addCategory(Inten.CATEGORT_HOME);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);

//去掉List拖动时的阴影
list.setCacheColorHint(0);

// 通过资源名称获取资源id
1.Field f= (Field)R.drawable.class.getDeclaredField("Name");
int id=f.getInt(R.drawable.class);
2.int id = getResources().getIdentifier(getPackageName()+":drawable/Name", null,null);
// timer TimerTask用法
mTimer = new Timer();
mTimerTask = new TimerTask() {
@Override
public void run() {
mProgress.setProgress(mMediaPlayer.getCurrentPosition());
mHandler.sendEmptyMessage(0);
}
};
mTimer.schedule(mTimerTask, 0, 1000);
// 在a.apk启动b.apk的实现
//1.a.apk实现
Intent mIntent = new Intent("package.MainActivity");
startActivity(mIntent);
finish();
// b.apk在mainfest中配置
<intent-filter><action android:name="package.MainActivity"></action><category android:name="android.intent.category.DEFAULT"></category></intent-filter>
//Android 获取存储卡路径和空间使用情况
/** 获取存储卡路径 */
File sdcardDir=Environment.getExternalStorageDirectory();
/** StatFs 看文件系统空间使用情况 */
StatFs statFs=new StatFs(sdcardDir.getPath());
/** Block 的 size*/
Long blockSize=statFs.getBlockSize();
/** 总 Block 数量 */
Long totalBlocks=statFs.getBlockCount();
/** 已使用的 Block 数量 */
Long availableBlocks=statFs.getAvailableBlocks();


//Android 为Activity屏幕的标题添加图标
Window win = getWindow();
  win.requestFeature(Window.FEATURE_LEFT_ICON);
  setContentView(R.layout.mylayout);
  win.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.icon);
//图片缩放
1.ThumbnailUtils.extractThumbnail(bitmap,200,100)
2. //使用Bitmap加Matrix来缩放
public static Drawable resizeImage(Bitmap bitmap, int w, int h)
{
Bitmap BitmapOrg = bitmap;
int width = BitmapOrg.getWidth();
int height = BitmapOrg.getHeight();
int newWidth = w;
int newHeight = h;

float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;

Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
// if you want to rotate the Bitmap
// matrix.postRotate(45);
Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
height, matrix, true);
return new BitmapDrawable(resizedBitmap);
}
3. //使用BitmapFactory.Options的inSampleSize参数来缩放
public static Drawable resizeImage2(String path,
int width,int height)
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//不加载bitmap到内存中
BitmapFactory.decodeFile(path,options);
int outWidth = options.outWidth;
int outHeight = options.outHeight;
options.inDither = false;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inSampleSize = 1;

if (outWidth != 0 && outHeight != 0 && width != 0 && height != 0)
{
int sampleSize=(outWidth/width+outHeight/height)/2;
Log.d(tag, "sampleSize = " + sampleSize);
options.inSampleSize = sampleSize;
}

options.inJustDecodeBounds = false;
return new BitmapDrawable(BitmapFactory.decodeFile(path, options));
}

// 通过WindowManager实现模态窗口效果
mWm = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
Button view = new Button(this);
view.setText("window manager test!");
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mWm.removeView(v);
}
});
WindowManager.LayoutParams mParams = new WindowManager.LayoutParams(100, 100, 2, 0, -1);
mWm.addView(view, mParams);
// 模拟心跳效果
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
long[] pattern = {800, 50, 400, 30}; // OFF/ON/OFF/ON...
vibrator.vibrate(pattern, 2);//-1不重复,非-1为从pattern的指定下标开始重复


//打印cursor消息
DatabaseUtils.dumpCurrentRow(cursor);


[/code]// 防止代码被反编译
将android-sdk-windows\tools\lib\地下的文件proguard.cfg拷贝到你的项目工程下,然后修改default.properties文件。在最后面加上proguard.config=proguard.cfg即可。完整的default.properties文件如下:
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system use,
# "build.properties", and override values to adapt the script to your
# project structure.

# Project target.
target=android-9
proguard.config=proguard.cfg
[/code]
//监听数据库变化
class SmsContent extends ContentObserver {
private Cursor cursor = null;

public SmsContent(Handler handler) {
super(handler);
}

@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
}
}
}

SmsContent content = new SmsContent(new Handler());
// 注册短信变化监听
this.getContentResolver().registerContentObserver(
Uri.parse("content://sms/"), true, content);


// 获取系统时间是24小时制还是12小时制
ContentResolver cv = this.getContentResolver();
String strTimeFormat = android.provider.Settings.System.getString(cv,
android.provider.Settings.System.TIME_12_24);

if(strTimeFormat.equals("24")) {
Log.i("activity","24");
}


// 设置菜单的背景
/**
* 设置菜单的背景色
* ActionMenuItemView ActionMode菜单
* IconMenuItemView 普通菜单
*/
protected void setMenuBackground(){
getLayoutInflater().setFactory(new Factory() {
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
if(name.equalsIgnoreCase("com.android.internal.view.menu.ActionMenuItemView")) {
try {
final View view = getLayoutInflater().createView(name, null, attrs);
new Handler().post(new Runnable() {
public void run() {
view.setBackgroundResource(R.drawable.list_item_bg_selector);
}
});
return view;
} catch(InflateException e) {
Log.e(TAG, "InflateException exception !");
} catch(ClassNotFoundException e) {
Log.e(TAG, "ClassNotFoundException exception !");
}
}
return null;
}
});
}


// 不让弹出键盘挡住view
<activity
android:name=".activity.SMSInterceptActivity"
android:windowSoftInputMode="adjustResize|stateHidden"/>
// windowSoftInputMode影响两件事情:1.软键盘的状态(隐藏,显示)2.活动主窗口的调整(平移,收缩)


//拉起后台正在通话的界面
/**
* 判断当前是否处于通话状态
* @return
*/
private boolean isCallStateIdle(){
TelephonyManager mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
int stateSim1 = mTelephonyManager.getCallState();
return stateSim1 != TelephonyManager.CALL_STATE_IDLE;
}
/**
* @return true if the phone is "in use", meaning that at least one line is
* active (ie. off hook or ringing or dialing).
*/
private boolean phoneIsInUse() {
boolean phoneInUse = false;
try {
ITelephony phone = ITelephony.Stub.asInterface(ServiceManager
.checkService("phone"));
if (phone != null)
phoneInUse = !phone.isIdle();
} catch (RemoteException e) {
Log.w(TAG, "phone.isIdle() failed", e);
}
return phoneInUse;
}

if(isCallStateIdle()) {
try {
String pkg="com.android.phone";
Context context=createPackageContext(pkg, Context.CONTEXT_IGNORE_SECURITY);
Intent it =new Intent();
it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
it.setClassName(context, "com.android.phone.InCallScreen");
context.startActivity(it);
} catch (NameNotFoundException e) {
Log.e(TAG, "com.android.phone.InCallScreen is not find");
}
}


 
//判断service是否已经在运行
public static boolean isServiceExisted(Context context, String className) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(Integer.MAX_VALUE);

if(!(serviceList.size() > 0)) {
return false;
}

for(int i = 0; i < serviceList.size(); i++) {
RunningServiceInfo serviceInfo = serviceList.get(i);
ComponentName serviceName = serviceInfo.service;

if(serviceName.getClassName().equals(className)) {
return true;
}
}
return false;
}



// 保存图片
try {
// 写入文件
Bitmap image = BitmapFactory.decodeResource(getResources(),
R.drawable.bg);
String directory = String.format(
"%s/%s",
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)
.getAbsolutePath(), "zhy");
File dir = new File(directory);
if (!dir.exists()){
dir.mkdirs();
}
File file = new File(directory, "zhy.jpeg");
OutputStream outputStream = new FileOutputStream(file);
if (image != null) {
image.compress(CompressFormat.JPEG, 100, outputStream);
}
outputStream.close();
} catch (Throwable e) {
e.printStackTrace();
}


// 修改系统语言
// 需要权限<uses-permission android:name="android.permission.CHANGE_CONFIGURATION"/>
private void setLanguage() {
try {
IActivityManager am = ActivityManagerNative.getDefault();
Configuration config = am.getConfiguration();
config.locale = Locale.ENGLISH;
am.updateConfiguration(config);
BackupManager.dataChanged("com.android.providers.settings");
} catch (RemoteException e) {
e.printStackTrace();
}
}


// TextView图文混排
// 1.Html标签实现
CharSequence c = Html.fromHtml(getString(R.string.html_text), new ImageGetter() {
@Override
public Drawable getDrawable(String arg0) {
Drawable d = getResources().getDrawable(R.drawable.pen);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
return d;
}
}, null);
mTv1.setText(c);

// 2.ImageSpan实现
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.pen);
ImageSpan is = new ImageSpan(this, b);
SpannableString ss = new SpannableString("FUCKimaFuck");
ss.setSpan(is, 4, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
mTv2.setText(ss);
//TExtview自定义链接跳转
SpannableString ss2 = new SpannableString("Link------");
ss2.setSpan(new ClickableSpan() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(mContext, ImageTextActivity.class);
startActivity(intent);
}
}, 0, 10, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

mTv2.setText(ss2);
mTv2.setMovementMethod(LinkMovementMethod.getInstance());

// 字符串的灵活使用
<string name="html_text"><![CDATA[电话<font color="#fd7320">%1s</font>]]></string>
textView = (TextView) findViewById(R.id.my_textview);
String text = getString(R.string.html_text); textView.setText(Html.fromHtml(String.format(text, "18658810629")));

CharSequence s2 = Html.fromHtml("afd<font color=\"#4399c8\">1233435</font>");
b.setText(s2);

//效果:
[img]http://dl.iteye.com/upload/attachment/0071/5827/bd7ec1dd-cacb-33fa-9633-519df97a89a6.jpg[/img]

// 检测系统是否存在你定义action的activity
PackageManager pm = getPackageManager();
Intent i = new Intent("your defined action");
List<ResolveInfo> data = pm.queryIntentActivities(i, PackageManager.GET_INTENT_FILTERS);
if(data.size() <= 0){
Log.e("XXX", "Activity action not exist");
}
// 检测系统是否存在你定义action的Receivers
pm.queryBroadcastReceivers(i, PackageManager.GET_INTENT_FILTERS);

// 检测系统是否存在你定义action的Service
pm.queryIntentServices(i, PackageManager.GET_INTENT_FILTERS);
// 对于aidl service,可以通过bindservice来确定
if(!bindService(i,serviceConnection,Context.BIND_AUTO_CREATE)){
Log.e("XXX", "service not exist");
}

// 检测系统是否存在你定义action的queryContentProviders
pm.queryContentProviders("uri", arg1, arg2);
// 通过这种方式判断
Uri uri = Uri.parse("uri");
Cursor c = getContentResolver().query(uri, new String[]{"",""}, null, null, null);
if(c == null){
Log.e("XXX", "ContentProvider not exist");
}


//将日期格式化为系统的日期格式
String date = DateFormat.getDateFormat(mContext).format(new Date());



// 竖直进度条的简单实现,通过imageview做
// 定义背景图片xml
<clip xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/bg_cling5"
android:clipOrientation="vertical"
android:gravity="top">
</clip>
// 使用方法
ImageView seekbar = (ImageView)findViewById(R.id.seekbar);
ClipDrawable bg = (ClipDrawable) seekbar.getDrawable();
// 从图顶端截取图像的30%
bg.setLevel(3000);


LockPatternUtils mLockPatternUtils = new LockPatternUtils(this);
// 图案 true
mLockPatternUtils.isLockPatternEnabled();
mLockPatternUtils.savedPatternExists()
// 密码 true
mLockPatternUtils.isLockPasswordEnabled();
// 无 true
mLockPatternUtils.isLockScreenDiseabled();
// 以上全false就是滑动
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值