安卓开发19:常用安卓开发技巧汇总

本文汇总了安卓开发中常用的技巧,包括解决API权限错误、获取手机号码、格式化字符串、设置全屏、检查网络状态等,并提供了拨打电话、发送邮件、打开浏览器等实用代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

常用安卓开发技巧汇总

经常用的一些小技巧都会记录在这边


API权限错误提示解决方法:

报这么一个错误:

Call requires API level 11 (current min is 8): android.animation.ObjectAnimator#ofFloat


主要原因是 AndroidManifest.xml中的API权限等级不够:

 <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

修改成:

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="17" />


获取手机号码:

//创建电话管理

TelephonyManager tm = (TelephonyManager)

//与手机建立连接
activity.getSystemService(Context.TELEPHONY_SERVICE);

//获取手机号码

String phoneId = tm.getLine1Number();

//记得在manifest file中添加
    <uses-permission
android:name="android.permission.READ_PHONE_STATE" />

//程序在模拟器上无法实现,必须连接手机

格式化string.xml 中的字符串

// in strings.xml..
<string name="my_text">Thanks for visiting %s. You age is %d!</string>
     
// and in the java code:
String.format(getString(R.string.my_text), "oschina", 33);

android设置全屏的方法

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(); 

在AndroidManifest.xml 增加权限:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

检测某个Intent是否有效

public static boolean isIntentAvailable(Context context, String action) {
    final PackageManager packageManager = context.getPackageManager();
    final Intent intent = new Intent(action);
    List<ResolveInfo> list =
            packageManager.queryIntentActivities(intent,
                    PackageManager.MATCH_DEFAULT_ONLY);
    return list.size() > 0;
}

android 拨打电话

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);
}

android中发送Email

Intent i = new Intent(Intent.ACTION_SEND);  
//i.setType("text/plain"); //模拟器请使用这行
i.setType("message/rfc822") ; // 真机上使用这行
i.putExtra(Intent.EXTRA_EMAIL, new String[]{"test@gmail.com","test@163.com});  
i.putExtra(Intent.EXTRA_SUBJECT,"subject goes here");  
i.putExtra(Intent.EXTRA_TEXT,"body goes here");  
startActivity(Intent.createChooser(i, "Select email application."));

android中打开浏览器

Intent viewIntent = new 
    Intent("android.intent.action.VIEW",Uri.parse("http://vaiyanzi.cnblogs.com"));

startActivity(viewIntent);

android 获取设备唯一标识码

String android_id = Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID);

android中获取IP地址

public String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); 
		en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> 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;
}

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中添加新的联系人

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<ActivityManager.RunningAppProcessInfo> mRunningProcess = mActivityManager.getRunningAppProcesses(); int i = 1; for (ActivityManager.RunningAppProcessInfo amProcess : mRunningProcess) { Log.e("homer Application", (i++) + "  PID = " + amProcess.pid + "; processName = " + amProcess.processName); }	




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值