关键技术
- 内容解析者Resolver
- ListView
- Socket网络编程
权限申请
//需要在Manifest.xml文件中申请权限
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />
布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="读取联系人"
android:textSize="20sp"/>
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
这里的布局就很简单,一个按钮和一个ListView组件
main_activity文件
package com.example.resolver;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import static android.provider.ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
import static android.provider.ContactsContract.CommonDataKinds.Phone.NUMBER;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btn;
TextView lv;
ContentResolver resolver;
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.btn);
// lv=findViewById(R.id.lv);
listView = findViewById(R.id.listview);
resolver = this.getContentResolver();
btn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btn) {
//需要动态申请权限,适用于Android 6.0以上版本
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.READ_CONTACTS,Manifest.permission.INTERNET}, 1);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
for (int i = 0; i < permissions.length; i++) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
readContacts();//读取联系人
} else {
Toast.makeText(this, "未授权读取联系人", Toast.LENGTH_LONG).show();
}
}
}
}
private void readContacts() {
List<ContactInfo> contactInfos = new ArrayList<>();
//创建游标对查询通讯录信息
Cursor cursor = resolver.query(CONTENT_URI,
null, null, null, null);
while (cursor.moveToNext()) {
if (cursor != null) {
String Number = cursor.getString(cursor.getColumnIndexOrThrow(NUMBER));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
ContactInfo contactInfo = new ContactInfo(name, Number);
contactInfos.add(contactInfo);
}
}
cursor.close();
String[] data = new String[contactInfos.size()];
int count = 0;
//将列表contactInfos的数据填充进一个数组,方便后面将联系人信息填入ListView
for (ContactInfo info : contactInfos) {
data[count] = info.getName() + "电话:" + info.getNumber();
count += 1;
}
ContactUpload contactUpload=new ContactUpload(data);//上传联系人信息,需要单独创建一个实体类
//创建适配器对象,将联系人填入ListView组件中去
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
listView.setAdapter(adapter);
}
}
上传通讯录:contactUpload
package com.example.resolver;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class ContactUpload {
public ContactUpload(final String[] contact) {
//创建一个线程用于实现上传通讯录,否则会报错
new Thread(new Runnable() {
@Override
public void run() {
try {
//创建Socket对象,绑定IP地址、端口号
Socket socket = new Socket("192.168.137.1", 6800);
OutputStream outputStream = socket.getOutputStream();
for (int i = 0; i < contact.length; i++) {
outputStream.write((contact[i] + "\n").getBytes());
}
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
服务端数据
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* Created by 29173 on 2020/4/12.
*/
public class server {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(6800);
Socket socket = ss.accept();
InputStream is = socket.getInputStream();
byte[] bytes = new byte[1024];
int len;
StringBuilder sb = new StringBuilder();
while ((len = is.read(bytes)) != -1) {
sb.append(new String(bytes, 0, len, "UTF-8"));
}
String userID=UserID();
File file = new File(userID+".txt");
FileOutputStream fis = new FileOutputStream(file);
StringBuffer sbf = new StringBuffer(sb);
fis.write(sb.toString().getBytes());
System.out.println(sb);
socket.shutdownInput();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String UserID(){
String date= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
String userID=date.toString();
return userID;
}
}
结束
这个项目总体上来说非常简单,入门实践作品,Android开发中很容易遇到各种坑,欢迎联系我,相互交流学习经验。
大家有兴趣的可以到我的个人博客看一看:点击这里到我的博客看一看