Android Studio 2 -1 手机联系人(多布局)与 okhttp
- 手机联系人
- OkHttp get请求 post请求 上传文件 下载文件
手机联系人
主要代码
package com.example.day0.fragment;
import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import com.example.day0.R;
import com.example.day0.Util.Search;
import com.example.day0.adapter.ListAdapter;
import com.example.day0.entity.Phone;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class ContactsFragment extends Fragment {
private static final String TAG = "ContactsFragment";
private ListAdapter listAdapter;
private List<Phone> phoneList = new ArrayList<>();
private List<Character> stringList = new ArrayList<>();
private String titles = "";
public ContactsFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View inflate = inflater.inflate(R.layout.fragment_contacts, container, false);
ListView listView = inflate.findViewById(R.id.list_item);
LinearLayout linearLayout = inflate.findViewById(R.id.ll_item);
final EditText ed_search = inflate.findViewById(R.id.ed_search);
for (int i = 0; i < 27; i++) {
char zi = (char) (65+i);
stringList.add(zi);
}
for (int i = 0; i < stringList.size(); i++) {
TextView textView = new TextView(getActivity());
textView.setText(stringList.get(i).toString());
linearLayout.addView(textView);
}
String[] permission = {Manifest.permission.READ_CONTACTS,Manifest.permission.CALL_PHONE};
requestPermissions(permission,8848);
ed_search.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
if (editable.toString().length() > 0) {
String search = ed_search.getText().toString();
Log.i(TAG, "afterTextChanged: "+search);
List<Map<String, String>> maps = Search.searchContacts(getActivity(), search);
} else {
}
}
});
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
ContentResolver resolver = getActivity().getContentResolver();
Cursor cursor = resolver.query(uri, null, null, null, "phonebook_label");
if (cursor != null){
while (cursor.moveToNext()){
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String tel = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String title = cursor.getString(cursor.getColumnIndex("phonebook_label"));
if (title.equals(titles)){
phoneList.add(new Phone(name, tel, title, Phone.TYPE_NAME));
}else {
phoneList.add(new Phone(name, tel, title, Phone.TYPE_TITLE));
phoneList.add(new Phone(name, tel, title, Phone.TYPE_NAME));
}
}
listAdapter = new ListAdapter(getActivity(), phoneList);
listView.setAdapter(listAdapter);
}else {
Toast.makeText(getActivity(), "读取数据失败", Toast.LENGTH_SHORT).show();
}
cursor.close();
listAdapter.notifyDataSetChanged();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneList.get(i).getTel()));
startActivity(intent);
}
});
return inflate;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 8848 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
}else {
Toast.makeText(getActivity(), "同意权限才能进行", Toast.LENGTH_SHORT).show();
}
}
}
适配器
package com.example.day0.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.day0.R;
import com.example.day0.entity.Phone;
import java.util.List;
public class ListAdapter extends BaseAdapter {
private Context context;
private List<Phone> phoneList;
private LayoutInflater layoutInflater;
public ListAdapter(Context context, List<Phone> phoneList) {
this.context = context;
this.phoneList = phoneList;
layoutInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return phoneList.size();
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public int getItemViewType(int position) {
return phoneList.get(position).getType();
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
TitleViewHoder titleViewHoder = new TitleViewHoder();
ContansViewHoder contansViewHoder = new ContansViewHoder();
if (view == null) {
if (getItemViewType(i) == Phone.TYPE_TITLE){
view = LayoutInflater.from(context).inflate(R.layout.layout_title,null);
titleViewHoder.title = view.findViewById(R.id.tv_phone_title);
view.setTag(titleViewHoder);
}else {
view = LayoutInflater.from(context).inflate(R.layout.layout_list,null);
contansViewHoder.name = view.findViewById(R.id.tv_phone_name);
contansViewHoder.tel = view.findViewById(R.id.tv_phone_tel);
view.setTag(contansViewHoder);
}
} else {
if (getItemViewType(i) == Phone.TYPE_TITLE){
titleViewHoder = (TitleViewHoder) view.getTag();
}else {
contansViewHoder = (ContansViewHoder) view.getTag();
}
}
if (getItemViewType(i) == Phone.TYPE_TITLE){
titleViewHoder.title.setText(phoneList.get(i).getTitle());
}else {
contansViewHoder.name.setText(phoneList.get(i).getName());
contansViewHoder.tel.setText(phoneList.get(i).getTel());
}
return view;
}
private class ContansViewHoder {
private TextView name;
private TextView tel;
}
private class TitleViewHoder {
private TextView title;
}
}
实体类
package com.example.day0.entity;
public class Phone {
public static final int TYPE_TITLE = 0;
public static final int TYPE_NAME = 1;
private String name;
private String tel;
private String title;
private int type;
public Phone(String name, String tel, String title, int type) {
this.name = name;
this.tel = tel;
this.title = title;
this.type = type;
}
@Override
public String toString() {
return "Phone{" +
"name='" + name + '\'' +
", tel='" + tel + '\'' +
", title='" + title + '\'' +
", type=" + type +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
OkHttp get请求 post请求 上传文件 下载文件
布局文件
<?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:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/btn_get"
android:text="GET"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn_post"
android:text="POST"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn_uploading"
android:text="上传"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn_downloading"
android:text="下载"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<SeekBar
android:id="@+id/seek"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
代码
package com.example.dayex01;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MainActivity";
private Button btnGet;
private Button btnPost;
private Button btnUploading;
private Button btnDownloading;
private SeekBar seekBar;
private int zhi;
private Handler handler = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
}
};
private String getURL = "http://api.yunzhancn.cn/api/app.interface.php?siteid=78703&itemid=2&act=ad_app";
private String postURL = "http://api.yunzhancn.cn/api/app.interface.php?siteid=78703&";
private String mp4URL = "http://uvideo.spriteapp.cn/video/2019/0512/56488d0a-7465-11e9-b91b-1866daeb0df1_wpd.mp4";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnGet = (Button) findViewById(R.id.btn_get);
btnPost = (Button) findViewById(R.id.btn_post);
btnUploading = (Button) findViewById(R.id.btn_uploading);
btnDownloading = (Button) findViewById(R.id.btn_downloading);
btnGet.setOnClickListener(this);
btnPost.setOnClickListener(this);
btnUploading.setOnClickListener(this);
btnDownloading.setOnClickListener(this);
seekBar = findViewById(R.id.seek);
seekBar.setProgress(zhi);
String[] permission = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permission, 8848);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 8848 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
Toast.makeText(this, "必须同意", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_get:
get();
break;
case R.id.btn_post:
post();
break;
case R.id.btn_uploading:
try {
upload();
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.btn_downloading:
down();
break;
default:
}
}
private void upload() throws IOException {
OkHttpClient client = new OkHttpClient.Builder()
.callTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.build();
MultipartBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", "JinSiYu.mp3",
RequestBody.create(MediaType.parse("Media/mp3"), new File("/sdcard/Music/Ice Paper - 心如止水.flac")))
.build();
final Request request = new Request.Builder()
.url("http://169.254.142.167/hfs")
.post(requestBody)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
}
private void down() {
OkHttpClient client = new OkHttpClient.Builder()
.callTimeout(1, TimeUnit.MINUTES)
.readTimeout(1, TimeUnit.MINUTES)
.build();
Request request = new Request.Builder()
.url(mp4URL)
.get()
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
long l = body.contentLength();
Log.i(TAG, "onResponse: 总大小" + l);
seekBar.setMax((int) l);
InputStream inputStream = body.byteStream();
FileOutputStream fileOutputStream = new FileOutputStream("/sdcard/Movies/asd.mp4");
byte[] bytes = new byte[2048];
int len = 0;
zhi = 0;
while ((len = inputStream.read(bytes)) != -1) {
zhi += len;
handler.post(new Runnable() {
@Override
public void run() {
seekBar.setProgress(zhi);
}
});
fileOutputStream.write(bytes, 0, len);
Log.i(TAG, "onResponse: " + zhi);
}
}
});
}
private void post() {
OkHttpClient client = new OkHttpClient.Builder()
.callTimeout(1, TimeUnit.MINUTES)
.readTimeout(1, TimeUnit.MINUTES)
.build();
FormBody formBody = new FormBody.Builder()
.add("itemid", "2")
.add("act", "ad_app")
.build();
Request request = new Request.Builder()
.url(postURL)
.post(formBody)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i(TAG, "onFailure: " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
String json = body.string();
Log.i(TAG, "onResponse: " + json);
}
});
}
private void get() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.readTimeout(1, TimeUnit.MINUTES);
builder.callTimeout(1, TimeUnit.MINUTES);
OkHttpClient client = builder.build();
Request.Builder builder1 = new Request.Builder();
builder1.url(getURL);
builder1.get();
final Request request = builder1.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i(TAG, "onFailure: " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
String json = body.string();
Log.i(TAG, "onResponse: " + json);
}
});
}
}