一路繁花似锦绣前程
失败的越多,成功才越有价值

导航

 

安卓应用

一、调用打电话接口

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void sendReceiver(View view) {
        EditText et = findViewById(R.id.et);
        String phoneNumber = et.getText().toString().trim();
        if ("".equals(phoneNumber)) {
            // context:如果是在当前类就是this,如果是在内部类则是当前类.this
            Toast.makeText(this, "电话号码不能为空", Toast.LENGTH_SHORT).show();
        } else {
            // 调用打电话接口需要用户开放打电话权限
            // <uses-permission android:name="android.permission.CALL_PHONE" />
            Intent intent = new Intent();// 意图
            intent.setAction(Intent.ACTION_CALL);
            intent.setData(Uri.parse("tel:" + phoneNumber));
            startActivity(intent);
        }
    }
}

二、内部存储读写数据

public class UserInfoUtils {

    public static boolean saveInfo(Context context, String username, String password) {
        try {
            // /data/data/包名/files/
            /**
             *  参数2:Context.MODE_PRIVATE:私有;
             *        Context.MODE_APPEND:追加;
             *        Context.MODE_WORLD_READABLE:其他应用可读;
             *        Context.MODE_WORLD_WRITEABLE:其他应用可写;
             */
            FileOutputStream fos = context.openFileOutput("info.txt", 0);

            String result = username + "##" + password;
            fos.write(result.getBytes());
            fos.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static Map<String, String> readInfo(Context context) {
        try {
            FileInputStream fis = context.openFileInput("info.txt");
            BufferedReader bufr = new BufferedReader(new InputStreamReader(fis));

            String content = bufr.readLine();
            String[] strings = content.split("##");
            HashMap<String, String> map = new HashMap<>();
            map.put("username", strings[0]);
            map.put("password", strings[1]);
            fis.close();
            return map;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

三、外部存储读写数据

  • 添加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  • 获取sd卡信息
// 判断sd卡状态是否可用
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
    Toast.makeText(this, "sd卡可用", Toast.LENGTH_SHORT).show();

    // 获取sd卡总大小和可用空间
    File sdcard = Environment.getExternalStorageDirectory();
    System.out.println("sd卡总大小:" + Formatter.formatFileSize(this, sdcard.getTotalSpace()));
    System.out.println("可用空间:" + Formatter.formatFileSize(this, sdcard.getUsableSpace()));
}
  • 获取sd卡目录
// 外部存储目录:/mnt/sdcard/
String path = Environment.getExternalStorageDirectory().getPath();
File file = new File(path, "info.txt");
FileOutputStream fos = new FileOutputStream(file);

四、SharedPreferences存储数据

// 写入的目录:/data/data/com.wuxi.myandroid/shared_prefs
SharedPreferences sp = getSharedPreferences("info", 0);
SharedPreferences.Editor edit = sp.edit();
edit.putString("uname", uname);
edit.putString("pword", pword);
edit.apply();
SharedPreferences sp = getSharedPreferences("info", 0);
// 参数2:未取到值时返回的值
String uname = sp.getString("uname", "");
String pword = sp.getString("pword", "");

五、XmlSerializer生成xml文件

public void generateXml(View view) {
    try {
        XmlSerializer xml = Xml.newSerializer();
        String path = Environment.getExternalStorageDirectory().getPath();
        File file = new File(path, "info.xml");
        FileOutputStream fos = new FileOutputStream(file);
        xml.setOutput(fos, "utf-8");
        // 头文件属性
        xml.startDocument("utf-8", true);
        // 节点
        xml.startTag(null, "div");
        xml.text("这是一段中文");
        xml.endTag(null, "div");
        xml.endDocument();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

六、XmlPullParser解析xml文件

  • xml放在/src/main/assets目录下,没有则新建该目录
  • MainActivity
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView tv = findViewById(R.id.tv);
        
        try {
            // 获取assets目录
            InputStream is = getAssets().open("person.xml");
            List<Person> persons = PullParserXmlUtil.parserXml(is);
            StringBuffer sb = new StringBuffer();
            for (Person person : persons) {
                sb.append(person.toString());
            }
            tv.setText(sb);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • PullParserXmlUtil
public class PullParserXmlUtil {
    public static List<Person> parserXml(InputStream xml) throws Exception {
        List<Person> persons = null;
        Person person = null;
        // 获取解析实例
        XmlPullParser parser = Xml.newPullParser();
        parser.setInput(xml, "utf-8");
        // 获得事件的类型
        int eventType = parser.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            switch (eventType) {
                case XmlPullParser.START_DOCUMENT:
                    persons = new ArrayList<Person>();
                    break;
                case XmlPullParser.START_TAG:
                    if ("person".equals(parser.getName())) {
                        person = new Person();
                        // 取出属性值
                        int id = Integer.parseInt(parser.getAttributeValue(0));
                        person.setId(id);
                    } else if ("name".equals(parser.getName())) {
                        String name = parser.nextText();// 获取该节点的内容
                        person.setName(name);
                    } else if ("age".equals(parser.getName())) {
                        int age = Integer.parseInt(parser.nextText());
                        person.setAge(age);
                    }
                    break;
                case XmlPullParser.END_TAG:
                    if ("person".equals(parser.getName())) {
                        persons.add(person);
                        person = null;
                    }
                    break;
            }
            eventType = parser.next();
        }
        return persons;
    }
}
posted on 2021-12-21 12:45  一路繁花似锦绣前程  阅读(37)  评论(0编辑  收藏  举报