-
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>
android开发之来电、短信、广播综合练习
原文:http://blog.chinaunix.net/uid-29270124-id-4647304.html