点击(此处)折叠或打开
- package com.example.incoming_number;
-
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.ServerSocket;
- import java.net.Socket;
-
- import android.os.Bundle;
- import android.app.Activity;
- import android.content.ContentResolver;
- import android.content.Intent;
- import android.view.Menu;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.TextView;
-
- /*
- * APP_name: incoming_number
- * AURHOR: DDDDD
- * DATE: 2014-11-17
- * MODIFY: 2014-11-23 20:43
- * FUCTION: get incoming number or message number and then send num and name to http server
- *
- *
- * DESCRIPTION:
- * 按下“开启服务”按钮,创建service,在service中创建一个broadcast
- * 通过broadcast接收来电号码或者短信号码, 访问通讯录数据库,通过号码得到name
- * 通过post方法向http server 发送 num name
- * 按下“关闭服务”按钮, service关闭,同时销毁broadcast
- * 要访问网络、message、phoneState、通讯录数据库 需要添加一起权限
- *
- *
- *
- *
- */
- public class MainActivity extends Activity
- {
- public static String IP = null;
- private Button startbtn = null;
- private Button stopbtn = null;
- private Button okbtn = null;
- private Button canclebtn = null;
- private static TextView info_text = null;
- private static EditText info_edit = null;
- private static ContentResolver contentResolver = null;
- @Override
- protected void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- //启动服务按钮
- startbtn = (Button)findViewById(R.id.startbtn);
- //为按钮添加动作
- startbtn.setOnClickListener(new ServiceListener());
- //关闭服务按钮
- startbtn = (Button)findViewById(R.id.stopbtn);
- //为按钮添加动作
- startbtn.setOnClickListener(new ServiceListener());
- //确定按钮
- okbtn = (Button)findViewById(R.id.ok);
- okbtn.setOnClickListener(new ServiceListener());
- //确定按钮
- canclebtn = (Button)findViewById(R.id.modify);
- canclebtn.setOnClickListener(new ServiceListener());
- //获取textview
- info_text = (TextView)findViewById(R.id.infoText);
- info_edit = (EditText)findViewById(R.id.infoEdit);
- info_text.setText("welcome!\n");
- //获取contex
- contentResolver = this.getContentResolver();
- }
- class ServiceListener implements OnClickListener
- {
-
- @Override
- public void onClick(View v)
- {
- //启动tcp服务器
- Intent intent = new Intent(MainActivity.this, listenerService.class);
- switch(v.getId())
- {
- //启动服务
- case R.id.startbtn:
- System.out.println("start service ");
- startService(intent);
- break;
- //关闭服务
- case R.id.stopbtn:
- System.out.println("stop service ");
- stopService(intent);
- break;
- case R.id.ok:
- //从editText获取IP
- IP = info_edit.getText().toString();
- break;
- case R.id.modify:
- //清空editText,清空ip
- info_edit.setText("");
- IP = null;
- break;
- default:
- break;
- }
-
- }
-
- }
- public static ContentResolver sendContentResolver()
- {
- return contentResolver;
- }
-
- @Override
- public boolean onCreateOptionsMenu(Menu menu)
- {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.main, menu);
- return true;
- }
-
- public static void setTextView(String string)
- {
- // TODO Auto-generated method stub
- info_text.setText(string);
- }
-
-
- /*
- class ServerThread extends Thread
- {
- ServerSocket serverSocket = null;
- @Override
-
- public void run()
- {
-
- // TODO Auto-generated method stub
- super.run();
- //申明一个SeverSocket对象
- ServerSocket serverSocket = null;
- try{
- //创建一个SeverSocket对象,监听80端口
- serverSocket = new ServerSocket(8080);
- //调用ServerSockrt的accept方法接受客户端发送的请求
- //如果客户端没有发送请求,accep函数会一直等待
- Socket socket = serverSocket.accept();
- //从socket中得到一个输入流
- InputStream inputStream = socket.getInputStream();
- byte buffer[] = new byte[1024*4];
- int temp = 0;
- //从inputstream中读取客户端发送的数据
- while((temp = inputStream.read(buffer)) != -1)
- {
- System.out.println(new String(buffer, 0, temp));
- }
- }catch(IOException e){
- e.printStackTrace();
- }
- finally{
- try{
- serverSocket.close();
- }catch(IOException e){
- e.printStackTrace();
- }
- }
- }
- } */
-
- }
点击(此处)折叠或打开
- package com.example.incoming_number;
-
- import java.io.IOException;
- import java.io.OutputStream;
- import java.net.HttpURLConnection;
- import java.net.Socket;
- import java.net.URL;
-
- import com.example.incoming_number.inComingReceiver;
- import com.example.incoming_number.inComingReceiver.CustomPhoneStateListener;
- import com.example.incoming_number.inComingReceiver.HttpRequestThread;
-
- import android.app.Service;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.os.Bundle;
- import android.os.IBinder;
- import android.telephony.PhoneStateListener;
- import android.telephony.SmsMessage;
- import android.telephony.TelephonyManager;
- import android.util.Log;
-
- public class listenerService extends Service
- {
- //接收短信广播
- IntentFilter filter_Message = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
- //创建短信广播接收器
- inComingReceiver iReceiver_Message = new inComingReceiver();
- //接收短信广播
- IntentFilter filter_Phone = new IntentFilter("android.intent.action.PHONE_STATE");
- //创建来电广播接收器
- inComingReceiver iReceiver_Phone = new inComingReceiver();
- @Override
- public IBinder onBind(Intent arg0)
- {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public void onCreate()
- {
- // TODO Auto-generated method stub
- System.out.println("create service ");
- super.onCreate();
- }
-
-
- @Override
- public int onStartCommand(Intent intent, int flags, int startId)
- {
- // TODO Auto-generated method stub
- System.out.println("service is running");
- //注册来电和短信广播接收器
- registerReceiver(iReceiver_Message, filter_Message);
- registerReceiver(iReceiver_Phone, filter_Phone);
-
- return super.onStartCommand(intent, flags, startId);
-
- }
-
- @Override
- public void onDestroy()
- {
- // TODO Auto-generated method stub
- super.onDestroy();
- //注销广播接收器
- unregisterReceiver(iReceiver_Message);
- unregisterReceiver(iReceiver_Phone);
- System.out.println("service is stop");
- }
- }
- /*
- * receiver android:name="com.example.incoming_number.listenerService$iReceiver" >
- intent-filter>
- action android:name="android.provider.Telephony.SMS_RECEIVED" />
- /intent-filter>
- intent-filter>
- action android:name="android.intent.action.PHONE_STATE" />
- /intent-filter>
- /receiver>
- * */
点击(此处)折叠或打开
- package com.example.incoming_number;
-
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.io.UnsupportedEncodingException;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.net.URL;
-
-
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.os.Bundle;
- import android.telephony.PhoneStateListener;
- import android.telephony.SmsMessage;
- import android.telephony.TelephonyManager;
- import android.util.Log;
- import android.widget.TextView;
-
- /*当有电话进入时,系统会铜鼓哦广播的方式通知应用程序
- * BroadcastReceiver会自动接收系统广播,每次接收到广播就会调用
- * onReceive方法
- */
- public class inComingReceiver extends BroadcastReceiver
- {
-
- private static final String TAG = null;
- private static String phoneNr = null;
- private static String smsNr = null;
- private static String contact_num = null;
- private static String contact_name = null;
- private static String info = null;
- private static String http_info = null;
-
- public inComingReceiver()
- {
-
- }
- @Override
- public void onReceive(Context context, Intent intent)
- {
- // TODO Auto-generated method stub
-
- toPhoneNum toPhoneNr = new toPhoneNum();
- getPhonePeopleActivity getpeople = new getPhonePeopleActivity();
-
- System.out.println("Recieve Message");
- Log.i(TAG, "WE ARE INSIDE!!!!!!!!!!!");
-
-
- //监听电话服务
- TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
- CustomPhoneStateListener customPhoneListener = new CustomPhoneStateListener();
- telephony.listen(customPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
-
-
- //接收intent对象
- Bundle bundle = intent.getExtras();
- //获取来电号码
- phoneNr= bundle.getString("incoming_number");
- //将18810867651转换为1-881-086-7651
- // phoneNr = toPhoneNr.makePhoneNum(phoneNr);
- //通过号码得到联系人名字
- // System.out.println("-------" +phoneNr+ "------");
- info = "主人,来电话啦!";
- contact_num = phoneNr;
- contact_name = getpeople.getPeople(phoneNr);
- // System.out.println(contact_num);
- // System.out.println(contact_name);
-
-
- //如果不是来电,那就是短信
- if(phoneNr == null)
- {
- //得到object类型数组
- Object myOBJpdus[] = (Object[])bundle.get("pdus");
- //得到smsmessage数组
- SmsMessage smsMessage[] = new SmsMessage[myOBJpdus.length];
- System.out.println(smsMessage.length);
- //创建smsmessage对象
- smsMessage[0] = SmsMessage.createFromPdu((byte[]) myOBJpdus[0]);
- //得到消息的号码
- smsNr = smsMessage[0].getDisplayOriginatingAddress();
-
-
- //将18810867651转换为1-881-086-7651
- //smsNr = toPhoneNr.makePhoneNum(smsNr);
- //通过号码得到联系人名字
- contact_num = smsNr;
- contact_name = getpeople.getPeople(smsNr);
- // System.out.println(contact_num);
- // System.out.println(contact_name);
- info = "主人,来短信啦";
- }
-
- //启动http发送
- new HttpRequestThread().start();
- //更新TextView
- MainActivity.setTextView("注意:\t" + info + "\n" + "姓名:\t" + contact_name + "\n" + "号码:\t" + contact_num + "\n" + "http:\t" + http_info);
-
- /* for(int i = 0; i myOBJpdus.length; i++)
- {
- //创建smsmessage对象
- smsMessage[i] = SmsMessage.createFromPdu((byte[]) myOBJpdus[i]);
- //得到消息的内容
- System.out.println(smsMessage[i].getDisplayMessageBody());
- //得到消息的号码
- System.out.println(smsMessage[i].getDisplayOriginatingAddress());
- }
- //启动socket发送
- new ClientThread().start(); */
- }
-
-
- public class CustomPhoneStateListener extends PhoneStateListener {
-
- private static final String TAG = "CustomPhoneStateListener";
-
- @Override
- public void onCallStateChanged(int state, String incomingNumber){
-
- Log.v(TAG, "WE ARE INSIDE!!!!!!!!!!!");
- Log.v(TAG, incomingNumber);
- //检测来电的状态
- switch(state){
- case TelephonyManager.CALL_STATE_RINGING:
- Log.d(TAG, "RINGING");
- break;
- case TelephonyManager.CALL_STATE_IDLE:
- Log.d(TAG, "IDLE");
- break;
- case TelephonyManager.CALL_STATE_OFFHOOK:
- Log.d(TAG, "OFFHOOK");
- break;
- }
- }
- }
-
-
- //启动新的线程, 创建一个http链接,post数据
- public class HttpRequestThread extends Thread
- {
- public void run()
- {
- // TODO Auto-generated method stub
- super.run();
- String path = MainActivity.IP;
- System.out.println("IP is:" + path);
- System.out.println("http server is running");
- try
- {
- sendString(path, info);
- } catch (Exception e1)
- {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- try
- {
- //发送号码
- sendString(path, "contact_num is :" + contact_num);
- } catch (Exception e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- try
- {
- //发送名字
- sendString(path, "contact_name is:" + contact_name);
- } catch (Exception e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- System.out.println("------- "+ info + "------");
- System.out.println("------- "+ contact_num + "------");
- System.out.println("------- "+ contact_name + "------");
- System.out.println("http server is over");
- }
- }
-
- //通过post方法向http发送数据
- public boolean sendString(String path, String str) throws Exception
- {
- byte[] data = str.getBytes();
- URL url = new URL(path);
- HttpURLConnection conn = (HttpURLConnection)url.openConnection();
- conn.setRequestMethod("POST");
- conn.setConnectTimeout(5 * 1000);
- //如果通过post提交数据,必须设置允许对外输出数据
- conn.setDoOutput(true);
- conn.setRequestProperty("Content-Type", "String; charset=UTF-8");
- conn.setRequestProperty("Content-Length", String.valueOf(data.length));
- OutputStream outStream = conn.getOutputStream();
- outStream.write(data);
- outStream.flush();
- outStream.close();
- if(conn.getResponseCode()==200)
- {
- System.out.println("http is running over");
- http_info = "Data is send!";
- return true;
- }
- System.out.println("http is running wrong");
- http_info = "http post is wrong";
- return false;
- }
-
-
- /*
- //创建TCP客户端
- class ClientThread extends Thread
- {
- //InputStream is = new ByteArrayInputStream(string.getBytes());
- @Override
- public void run()
- {
- // TODO Auto-generated method stub
- super.run();
- System.out.println("tcp cleint is running");
- try{
- //创建一个socket,指定服务器端的ip地址和端口,
- Socket socket = new Socket("192.168.1.116", 7654);
- //从sicket获取一个outputstream
- OutputStream outputStream = socket.getOutputStream();
- byte buffer[] = smsNr.getBytes();
- int temp = buffer.length;
- //将buffer的内容写入outputstream
- outputStream.write(buffer, 0, temp);
- outputStream.flush();
- }catch (IOException e){
- e.printStackTrace();
-
- System.out.println("tcp cleint is running over");
- }
- }
- }
- */
- }
点击(此处)折叠或打开
- package com.example.incoming_number;
-
- import android.app.Activity;
- import android.content.ContentResolver;
- import android.database.Cursor;
- import android.provider.ContactsContract;
- import android.util.Log;
-
- //通过电话号码获取姓名
- public class getPhonePeopleActivity
- {
- private static final String TAG = null;
- String str = "未知号码";
- String name = null;
- public String getPeople(String phoneNr) {
- /* String[] projection = { android.provider.ContactsContract.Contacts.DISPLAY_NAME,
- };
-
- Log.d(TAG, "getPeople ---------");
-
- ContentResolver contentResolver = MainActivity.sendContentResolver();
- Cursor cursor = contentResolver.query(android.provider.ContactsContract.Contacts.CONTENT_URI,
- projection,
- android.provider.ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '" + phoneNr + "'",
- null, null);
- cursor.getCount();
- while(cursor.moveToNext()) {
- System.out.println("NUM:"+cursor.getString(cursor.getColumnIndex(android.provider.ContactsContract.Contacts._ID)));
- System.out.println("NAME:"+cursor.getString(cursor.getColumnIndex(android.provider.ContactsContract.Contacts.DISPLAY_NAME)));
- }
- // cursor.close(); */
-
- String[] projection = { ContactsContract.PhoneLookup.DISPLAY_NAME,
- ContactsContract.CommonDataKinds.Phone.NUMBER};
-
- Log.d(TAG, "getPeople ---------");
- ContentResolver contentResolver = MainActivity.sendContentResolver();
- // 将自己添加到 msPeers 中
- Cursor cursor = contentResolver.query(
- ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
- projection, // Which columns to return.
- ContactsContract.CommonDataKinds.Phone.NUMBER + " = '" + phoneNr + "'", // WHERE clause.
- null, // WHERE clause value substitution
- null); // Sort order
-
- if( cursor == null ) {
- Log.d(TAG, "getPeople null");
- return str;
- }
- Log.d(TAG, "getPeople cursor.getCount() = " + cursor.getCount());
- //未找到匹配的联系人,那么就是未知号码
- if(cursor.getCount() == 0)
- {
- return str;
- }
- //System.out.println("phoneNum is:" + phoneNr);
- for( int i = 0; i cursor.getCount(); i++ )
- {
- cursor.moveToPosition(i);
-
- // 取得联系人名字
- int nameFieldColumnIndex = cursor.getColumnIndex(android.provider.ContactsContract.Contacts.DISPLAY_NAME);
- name = cursor.getString(nameFieldColumnIndex);
- Log.i("Contacts", "" + name + " .... " + nameFieldColumnIndex); // 这里提示 force close
- System.out.println("name is:" + name);
- }
- return name;
- }
- }
- //ContactsContract.CommonDataKinds.Phone.NUMBER + " = '" + phoneNr + "'", // WHERE clause.
- //android.provider.ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '" + phoneNr + "'"
点击(此处)折叠或打开
- package com.example.incoming_number;
-
- import java.io.UnsupportedEncodingException;
-
- /*
- * 将号码18810867651转变成模拟器的格式1-881-086-7651
- * 这个类将依据手机的内号码的存放格式而定
- * */
- public class toPhoneNum
- {
-
- private byte b[] = null;
- private byte c[] = new byte[14];
- private String phoneNr = null;;
- public String makePhoneNum(String str)
- {
- try
- {
- b = str.getBytes("ISO-8859-1");
- } catch (UnsupportedEncodingException e1)
- {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- c[0] = b[0];
- c[1] = '-';
- c[2] = b[1];
- c[3] = b[2];
- c[4] = b[3];
- c[5] = '-';
- c[6] = b[4];
- c[7] = b[5];
- c[8] = b[6];
- c[9] = '-';
- c[10] = b[7];
- c[11] = b[8];
- c[12] = b[9];
- c[13] = b[10];
- try
- {
- phoneNr = new String(c,"ISO-8859-1");
- } catch (UnsupportedEncodingException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return phoneNr;
- }
- }
点击(此处)折叠或打开
- RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:paddingBottom="@dimen/activity_vertical_margin"
- android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- tools:context=".MainActivity" >
-
- Button
- android:id = "@+id/startbtn"
- android:layout_height="wrap_content"
- android:layout_width="fill_parent"
- android:text="开启监听服务"
- />
- Button
- android:id = "@+id/stopbtn"
- android:layout_below="@+id/startbtn"
- android:layout_height="wrap_content"
- android:layout_width="fill_parent"
- android:text="关闭监听服务"
- />
- EditText
- android:id="@+id/infoEdit"
- android:hint="请输入http服务器的IP地址"
- android:layout_width="fill_parent"
- android:layout_height="50dp"
- android:textSize="20sp"
- android:textColor="#00ff00"
- android:inputType="none"
- android:layout_below="@+id/stopbtn" />
-
- TextView
- android:id="@+id/infoText"
- android:layout_width="fill_parent"
- android:layout_height="100dp"
- android:layout_alignRight="@+id/infoEdit"
- android:layout_below="@+id/ok"
- android:textColor="#00ff00"
- android:textSize="20sp" />
-
- Button
- android:id="@+id/ok"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignLeft="@+id/infoText"
- android:layout_below="@+id/infoEdit"
- android:text="确定" />
-
- Button
- android:id="@+id/modify"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignLeft="@+id/infoEdit"
- android:layout_below="@+id/infoEdit"
- android:layout_marginLeft="68dp"
- android:text="修改" />
-
- /RelativeLayout>
点击(此处)折叠或打开
- ?xml version="1.0" encoding="utf-8"?>
- manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.incoming_number"
- android:versionCode="1"
- android:versionName="1.0" >
-
- uses-sdk
- android:minSdkVersion="8"
- android:targetSdkVersion="18" />
-
- application
- android:allowBackup="true"
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name"
- android:debuggable="true"
- android:theme="@style/AppTheme" >
- activity
- android:name="com.example.incoming_number.MainActivity"
- android:label="@string/app_name" >
- intent-filter>
- action android:name="android.intent.action.MAIN" />
-
- category android:name="android.intent.category.LAUNCHER" />
- /intent-filter>
- /activity>
- service android:name = "com.example.incoming_number.listenerService"/>
-
- /application>
- uses-permission android:name="android.permission.READ_PHONE_STATE" />
- uses-permission android:name="android.permission.RECEIVE_SMS" />
- uses-permission android:name="android.permission.INTERNET"/>
- uses-permission android:name="android.permission.READ_CONTACTS"/>
- /manifest>