常用安卓开发技巧汇总
经常用的一些小技巧都会记录在这边
报这么一个错误:
Call requires API level 11 (current min is 8): android.animation.ObjectAnimator#ofFloat
主要原因是 AndroidManifest.xml中的API权限等级不够:
获取手机号码:
//创建电话管理
TelephonyManager tm = (TelephonyManager)
//与手机建立连接
activity.getSystemService(Context.TELEPHONY_SERVICE);
//获取手机号码
String phoneId = tm.getLine1Number();
//记得在manifest file中添加
//程序在模拟器上无法实现,必须连接手机
// in strings.xml..
Thanks for visiting %s. You age is %d!
// and in the java code:
String.format(getString(R.string.my_text), "oschina", 33);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
ConnectivityManager con=(ConnectivityManager)getSystemService(Activity.CONNECTIVITY_SERVICE);
boolean wifi=con.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
boolean internet=con.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
public static boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List list =
packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
try {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:+110"));
startActivity(intent);
} catch (Exception e) {
Log.e("SampleApp", "Failed to invoke call", e);
}
Intent i = new Intent(Intent.ACTION_SEND);
//i.setType("text/plain"); //模拟器请使用这行
i.setType("message/rfc822") ; // 真机上使用这行
i.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]","[email protected]});
i.putExtra(Intent.EXTRA_SUBJECT,"subject goes here");
i.putExtra(Intent.EXTRA_TEXT,"body goes here");
startActivity(Intent.createChooser(i, "Select email application."));
Intent viewIntent = new
Intent("android.intent.action.VIEW",Uri.parse("http://vaiyanzi.cnblogs.com"));
startActivity(viewIntent);
String android_id = Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID);
public String getLocalIpAddress() {
try {
for (Enumeration en = NetworkInterface.getNetworkInterfaces();
en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration enumIpAddr = intf.getInetAddresses();
enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e(LOG_TAG, ex.toString());
}
return null;
}
/** 获取存储卡路径 */
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();
private Uri insertContact(Context context, String name, String phone) {
ContentValues values = new ContentValues();
values.put(People.NAME, name);
Uri uri = getContentResolver().insert(People.CONTENT_URI, values);
Uri numberUri = Uri.withAppendedPath(uri, People.Phones.CONTENT_DIRECTORY);
values.clear();
values.put(Contacts.Phones.TYPE, People.Phones.TYPE_MOBILE);
values.put(People.NUMBER, phone);
getContentResolver().insert(numberUri, values);
return uri;
}
Intent intentBatteryUsage = new Intent(Intent.ACTION_POWER_USAGE_SUMMARY);
startActivity(intentBatteryUsage);
ActivityManager mActivityManager = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List mRunningProcess = mActivityManager.getRunningAppProcesses();
int i = 1;
for (ActivityManager.RunningAppProcessInfo amProcess : mRunningProcess)
{
Log.e("homer Application", (i++) + " PID = " + amProcess.pid + ";
processName = " + amProcess.processName);
}
在使用弹出框希望点击弹出框外的任意处让弹出框消失,
先把设置弹出框的setOutsideTouchable为true,然后重写onTouch。
win = new PopupWindow(contentView, LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
win.setOutsideTouchable(true);
win.setFocusable(true);
// 点击弹出窗口区域之外的任意区域,则该窗口关闭
win.setTouchInterceptor(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
win.dismiss();
return true;
}
return false;
}
});
Resources myResources = getResources();
String str = myResources.getString(R.string.app_name);
myResources.getDrawable(R.drawable.jhs_button1_h);
am start -a android.intent.action.VIEW -t video/* -d 'url地址'
private int getPixels(int dipValue) {
Resources r = getResources();
int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, r.getDisplayMetrics());
return px;
}
ImageView imageView = (ImageView) findViewById(R.id.videoImage1);
LayoutParams para = imageView.getLayoutParams();
para.height = getPixels(180);
para.width = getPixels(120);
imageView.setLayoutParams(para);
ImageView imageView = new ImageView(this);
imageView.setPadding(5,5,5,5)
//设置margin
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(0, getPixels(13), 0, 0);
public Bitmap returnBitMap(String url){
URL myFileUrl = null;
Bitmap bitmap = null;
try {
myFileUrl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
//使用:
ImageView imageView = (ImageView) findViewById(R.id.imageView);
String url = "http://www.baidu.com/img/bdlogo.gif";
imageView.setImageBitmap(returnBitMap(url));
Uri uri =Uri.fromParts("package", strPackageName, null);
Intent it = newIntent(Intent.ACTION_DELETE, uri);
startActivity(it);
Uri installUri = Uri.fromParts("package","xxx", null);
returnIt = newIntent(Intent.ACTION_PACKAGE_ADDED, installUri);
public static int dip2px(Context context, float dipValue){
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(dipValue * scale + 0.5f);
}
public static int px2dip(Context context, float pxValue){
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(pxValue / scale + 0.5f);
}
ViewGroup viewGroup = (ViewGroup) getLayoutInflater().inflate(R.layout.main, null);
setContentView(viewGroup);
Button button = new Button(this);
button.setText("Heklki");
viewGroup.addView(button);
Button button2 = new Button(this);
button.setText("Heklki2");
button.setPadding(100, 100, 100, 100);
viewGroup.addView(button2);
LayoutInflater i = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
也可以带上ID
LinearLayout layout = (LinearLayout)findViewById(R.id.a);
TableLayout tableLayout = new TableLayout(this);
LinearLayout layout1 = new LinearLayout(this);
TableRow row = new TableRow(this);
ImageView img = new ImageView(this);
Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/a.png");//从本地取图片
img.setLayoutParams(new LayoutParams(100,100));
Drawable drawable = new BitmapDrawable(bitmap);
img.setImageDrawable(drawable);
img.setAlpha(255);
System.out.println(drawable);
System.out.println(img.getDrawable());
layout1.addView(img);
row.addView(layout1);
tableLayout.addView(row);
layout.addView(tableLayout);
row和imageView之间加上 linearLayout
//禁止焦点
sc.setFocusable(false);
sc.setFocusableInTouchMode(false);
Intent intent = new Intent();
intent.setClassName("com.xxx.xxx", "com.xxx.xxx.xxxIndex");
startActivity(intent);
View.setNextFocusDownId //设置向下焦点
View.setNextFocusLeftId //向左
View.setNextFocusUpId //设置向上
View.setNextFocusRightId //向右
TextUtils.isEmpty(edit.getText()) //为空的判断
TextUtils.isEmpty(edit.getText().toString().trim()) //去掉空格
public class SMSReceiver extends BroadcastReceiver
{
/*当收到短信时,就会触发此方法*/
public void onReceive(Context context, Intent intent)
{
Bundle bundle = intent.getExtras();
Object messages[] = (Object[]) bundle.get( "pdus");
SmsMessage smsMessage[] = new SmsMessage[messages.length];
for (int n = 0; n < messages.length; n++)
{
smsMessage[n] = SmsMessage.createFromPdu(( byte[]) messages[n]);
}
//产生一个Toast
Toast toast = Toast.makeText(context, "短信内容: " + smsMessage[0].getMessageBody(), Toast.LENGTH_LONG);
//设置toast显示的位置
//toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 200);
//显示该Toast
toast.show();
}
}
//打印加入变量名的字符串
int count = 5;
String text = String. format(getResources().getString(R.string.flip_view_apk_title),count); //这里的count就是替换里面的$d的值
//找到count字符的位置并显示跟整个字符串不同的颜色
String str = count + "";
int index = text.indexOf(str);
int charCount = str.length();
SpannableStringBuilder style= new SpannableStringBuilder(text);
int color = 0xffff00ff;
style.setSpan( new ForegroundColorSpan(color),index,index+charCount,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
TestView.setText(style);
//不同大小的字体
SpannableStringBuilder style = new SpannableStringBuilder(version);
style.setSpan( new AbsoluteSizeSpan(bigSize), 0, 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE );
style.setSpan( new AbsoluteSizeSpan(normalSize), 1, version.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
verionNameView.setText(style);
strings.xml设置
测试(%1$d个)
%1为第一次设置引用的设置
$d为显示的变量格式,为整型
$s为字符串型
$c等等
//打印两位数00
s = String.format("%02d", 1);
格式化后s就是01
//删除线,中划线
priceTextView.setText(Double.toString((6800 / 100.0)));
priceTextView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//删除线
priceTextView.getPaint().setAntiAlias(true);//解决画到Bitmap上删除线的字符矩齿的问题
//打印小数点后两位
DecimalFormat mDecimalFormat;
mDecimalFormat = new DecimalFormat("#####.00");
mDecimalFormat.format((Double)(2000/ 1000.0);
1. String str = "";
2. DisplayMetrics dm = new DisplayMetrics();
3. // getWindowManager().getDefaultDisplay().getMetrics(dm);
4. dm = this.getApplicationContext().getResources().getDisplayMetrics();
5. int screenWidth = dm.widthPixels;
6. int screenHeight = dm.heightPixels;
7. float density = dm.density;
8. float xdpi = dm.xdpi;
9. float ydpi = dm.ydpi;
10. str += "屏幕分辨率为:" + dm.widthPixels + " * " + dm.heightPixels + "\n";
11. str += "绝对宽度:" + String.valueOf(screenWidth) + "pixels\n";
12. str += "绝对高度:" + String.valueOf(screenHeight)
13. + "pixels\n";
14. str += "逻辑密度:" + String.valueOf(density)
15. + "\n";
16. str += "X 维 :" + String.valueOf(xdpi) + "像素每英尺\n";
17. str += "Y 维 :" + String.valueOf(ydpi) + "像素每英尺\n";
18. Log.i("1", str);
NinePatchDrawable bg = (NinePatchDrawable)mContext.getResources().getDrawable(R.drawable.item_bg);
bg.setBoundsint left, int top, int right, int bottom;
bg.draw(canvas);
在应用的第一个activity的oncreate里面加入:
//当前activity为首页, 如果他前面还有其他的activity,说明用户按过home键
//则无需跑初始化的界面逻辑
ActivityManager am = (ActivityManager) getSystemService( ACTIVITY_SERVICE);
List tasklist = am.getRunningTasks(1);
ActivityManager.RunningTaskInfo runTask = tasklist.get(0);
int n = runTask.numActivities ;
if (n != 1) {
finish();
return ;
}
// 得到TextView控件对象
TextView textView = (TextView) findViewById(R.id.custom);
// 将字体文件保存在assets/fonts/目录下,www.linuxidc.com创建Typeface对象
Typeface typeFace = Typeface.createFromAsset(getAssets(),"fonts/DroidSansThai.ttf");
// 应用字体
textView.setTypeface(typeFace);
显示网页:
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse("xxx://list"));
intent.putExtra("isShowShoppingCart", "true");
startActivity(intent);
}
被调用的应用中,xml配置
这样配置之后,这个Activity就会形成一个单独的进程,进程名称例如:xxx.xx.xxx:DetailActivity
一般将逻辑上一起运行的组件配置在一个进程中。如果逻辑上有一定分离的,可以新开一个进程。这样可以降低主进程的空间和时间开销
安装软件
adb install apk文件名称.apk
重新安装该软件
adb install -r apk文件名称.apk
卸载apk软件
adb uninstall apk包名.apk
查看手机上的运行日志,此项可以用来查错
adb logcat
查看手机是否连接,以及连接了几台手机
adb devices
A为手机路径,B为电脑路径,意思为:把文件从手机中复制到电脑上
adb pull
A为手机路径,B为电脑路径,意思为:把文件从电脑复制到手机上
adb push
进入手机的超级终端Terminal
adb shell
重新挂载文件系统
adb remount
重启手机
adb reboot
重启到Recovery界面
adb reboot recovery
重启到bootloader界面
adb reboot bootloader
例子:刷官方高版本后重新获取ROOT和降级方法(部份操作)
进行adb运行环境
adb shell
设置超级用户模式
su
映射出目录
mount -o remount,rw -t yaffs2 /dev/block/mtdblock3 /system
退出su
exit
退出shell准备接受下一个adb命令
exit
增加flash_image文件到手机上
adb push flash_image.zip /system/bin/flash_image
recovery先复制到卡上
adb push recovery-RA-heroc-v1.6.2.img /sdcard
再次进入adb环境
adb shell
修改文件属性
chmod 0755 /system/bin/flash_image
重启系统
reboot
am start -n com.xx.xx/com.xx.xx.activity.WelcomeActivity
CategoryTitleView goodTitleView = new CategoryTitleView(mContext, null);
Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas2 = new Canvas(bitmap);
goodTitleView.setView(mItemData);
goodTitleView.measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY));
goodTitleView.layout(0, 0, getWidth(), getHeight());
goodTitleView.draw(canvas2);
canvas.drawBitmap(bitmap, 0, 0, null);
// GameView.drawImage(canvas, mBitDestTop, miDTX, mBitQQ.getHeight(), mBitDestTop.getWidth(), mBitDestTop.getHeight()/2, 0, 0);
public static void drawImage(Canvas canvas, Bitmap blt, int x, int y, int w, int h, int bx, int by)
{ //x,y表示绘画的起点,
Rect src = new Rect();// 图片
Rect dst = new Rect();// 屏幕位置及尺寸
//src 这个是表示绘画图片的大小
src.left = bx; //0,0
src.top = by;
src.right = bx + w;// mBitDestTop.getWidth();,这个是桌面图的宽度,
src.bottom = by + h;//mBitDestTop.getHeight()/2;// 这个是桌面图的高度的一半
// 下面的 dst 是表示 绘画这个图片的位置
dst.left = x; //miDTX,//这个是可以改变的,也就是绘图的起点X位置
dst.top = y; //mBitQQ.getHeight();//这个是QQ图片的高度。 也就相当于 桌面图片绘画起点的Y坐标
dst.right = x + w; //miDTX + mBitDestTop.getWidth();// 表示需绘画的图片的右上角
dst.bottom = y + h; // mBitQQ.getHeight() + mBitDestTop.getHeight();//表示需绘画的图片的右下角
canvas.drawBitmap(blt, src, dst, null);//这个方法 第一个参数是图片原来的大小,第二个参数是 绘画该图片需显示多少。也就是说你想绘画该图片的某一些地方,而不是全部图片,第三个参数表示该图片绘画的位置
src = null;
dst = null;
}
Drawable img_on, img_off;
Resources res = getResources();
img_off = res.getDrawable(R.drawable.btn_strip_mark_off);
//调用setCompoundDrawables时,必须调用Drawable.setBounds()方法,否则图片不显示
img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
btn.setCompoundDrawables(img_off, null, null, null); //设置左图标