package com.sogouchat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.sogouchat.bean.ContactNode;
import com.sogouchat.bean.DownNode;
import com.sogouchat.bean.MsgNode;
import com.sogouchat.bean.TelNode;
import com.sogouchat.os.ChatAppConstant;
import com.sogouchat.os.IMsgService;
import com.sogouchat.os.MsgSrvReceiver;
import com.sogouchat.smsmms.ContactsMgr;
import com.sogouchat.smsmms.SmsMgr;
import com.sogouchat.ui.ChatListActivity;
import com.sogouchat.ui.ContactListActivity2;
import com.sogouchat.ui.CreateActivity;
import com.sogouchat.ui.NewsListActivity;
import com.sogouchat.ui.SlidingActivity;
import com.sogouchat.util.HanZiToPinYin;
import android.app.Activity;
import android.app.Application;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.telephony.SmsManager;
import android.text.format.Time;
import android.util.Log;
import android.widget.Toast;
public class SogouChatApp extends Application {
private static final String TAG = "SogouChatApp";
public SplashActivity mSplash;
public CreateActivity mCreate;
public ChatListActivity mChatList;
public NewsListActivity mNewsList;
public SlidingActivity mSliding;
public ContactListActivity2 mContactsList = null;
public long mBackRecord;
public final class OftenContactVal {
public TelNode mTelNode;
public int mValue;// 权重值
}
public List<TelNode> mTelList;
public List<MsgNode> mMsgList;
public ArrayList<TelNode> mOftenContacts = new ArrayList<TelNode>(9);//常用联系人列表
public ArrayList<OftenContactVal> mTelNodeWeight = new ArrayList<OftenContactVal>();
public ArrayList<DownNode> mDownList = new ArrayList<DownNode>();
public ArrayList<TelNode> mSelectList= new ArrayList<TelNode>();
public IMsgService mRemoteService;
private Bundle mBundle;
private MsgSrvReceiver mMsgRecv;
private SmsSendReceiver mSendRecv = new SmsSendReceiver();
private SmsDeliverReceiver mDeliverRecv = new SmsDeliverReceiver();
private SmsManager mSmsMgr = SmsManager.getDefault();
private boolean mPinyinOk;
public void onCreate() {
super.onCreate();
ContactsMgr.GetI().Init(getApplicationContext());
ContactsMgr.GetI().Load();
SmsMgr.GetI().Init(getApplicationContext());
SmsMgr.GetI().LoadAll();
mMsgRecv = new MsgSrvReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.sogouchat.action.CONTENT_CHANGED_ACTION");
registerReceiver(mMsgRecv, filter);
bindService(new Intent("com.sogouchat.os.IMsgService"),
mRemoteConn, Context.BIND_AUTO_CREATE);
}
public void onTerminate() {
super.onTerminate();
unregisterReceiver(mMsgRecv);
unbindService(mRemoteConn);
}
public void handleSrvBackMsg(int msg, Bundle bundle){
Log.i(TAG, "handleSrvBackMsg") ;
mBundle = bundle;
if (mSplash == null) return;
switch (msg) {
case ChatAppConstant.SRV_BackMsg_FetchDb_Ok: {
try {
mTelList = mRemoteService.getTelList();
setupPinyin();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (mSplash != null)
mSplash.directTo();
}
break;
case ChatAppConstant.SRV_BackMsg_New_Sms: {
if (mChatList != null) {
try {
mMsgList = mRemoteService.getNewMsgList();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
appendMsgList();
Toast.makeText(getBaseContext(), "SMS new",
Toast.LENGTH_SHORT).show();
// mNewsListFrag.updateListView();
if (mChatList.isShown())
{
mChatList.handleSrvMsg(msg, mBundle);
}
}
}
break;
case ChatAppConstant.SRV_BackMsg_File_Down_Ok: {
if (mChatList != null)
mChatList.handleSrvMsg(msg, mBundle);
}
break;
case ChatAppConstant.SRV_BackMsg_Fetch_All_Msg_Ok: {
Log.i(TAG, "handleSrvBackMsg SRV_BackMsg_Fetch_All_Msg_Ok") ;
try {
mTelList = mRemoteService.getTelList();
setupPinyin();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
break;
case ChatAppConstant.SRV_BackMsg_Fetch_Contacts_Msg_Ok: {
if (mContactsList == null) return;
try {
mTelList = mRemoteService.getTelList();
setupPinyin();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (mContactsList != null)
mContactsList.refresh();
}
break;
default:
break;
}
}
public void sendSrvForeMsg(int msg, String arg1, String arg2){
if (mRemoteService != null) {
try {
Log.i(TAG, "sendSrvForeMsg") ;
mRemoteService.handleSrvForeMsg(msg, arg1, arg2);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void syncDownList(){
if (mDownList.size() >0){
if (mRemoteService != null) {
try {
mRemoteService.downMediaList(mDownList);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public void fetchDb() {
Log.i(TAG, "fetchDb");
try {
if (mRemoteService != null) {
mRemoteService.fetchContactDb();
}
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void fetchContactList(){
if (mRemoteService != null) {
try {
mRemoteService.getTelList();
setupPinyin();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class MsgSrvReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
int castType = bundle.getInt("CastType");
handleSrvBackMsg(castType, bundle);
}
}
public class SmsSendReceiver extends BroadcastReceiver {
@Override
public void onReceive(android.content.Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}
public class SmsDeliverReceiver extends BroadcastReceiver {
@Override
public void onReceive(android.content.Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}
private ServiceConnection mRemoteConn = new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
mRemoteService = IMsgService.Stub.asInterface(service);
Log.i(TAG, "onServiceConnected") ;
}
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
mRemoteService = null;
}
};
public void sendSms(String tel, String body, long date){
String SENT = "SENT_SMS_ACTION";
String DELIVERED = "DELIVERED_SMS_ACTION";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED), 0);
registerReceiver(this.mSendRecv, new IntentFilter(SENT));
registerReceiver(this.mDeliverRecv, new IntentFilter(DELIVERED));
ArrayList<String> list = mSmsMgr.divideMessage(body);
if (isPhoneNumberValid(tel) == true) {
try {
mSmsMgr.sendTextMessage(tel, null, body, sentPI, deliveredPI);
saveSms(tel, body, date);
} catch (Exception e) {
// TODO: handle exception
}
Toast.makeText(this, "发送成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "***不符合",Toast.LENGTH_SHORT ).show();
}
}
public void saveSms(String tel, String body, long date) {
ContentValues values = new ContentValues();
// 发送时间
values.put("date", System.currentTimeMillis());
// 阅读状态
values.put("read", 0);
// 1为收 2为发
values.put("type", 2);
// 送达号码
values.put("address", tel);
// 送达内容
values.put("body", body);
// 插入短信库
getContentResolver().insert(Uri.parse("content://sms"), values);
addSendSms(tel, body, date);
}
public static boolean isPhoneNumberValid(String phoneNumber) {
boolean isValid = false;
String expression = "((^(13|15|18)[0-9]{9}$)|(^0[1,2]{1}\\d{1}-?\\d{8}$)|(^0[3-9] {1}\\d{2}-?\\d{7,8}$)|(^0[1,2]{1}\\d{1}-?\\d{8}-(\\d{1,4})$)|(^0[3-9]{1}\\d{2}-? \\d{7,8}-(\\d{1,4})$))";
CharSequence inputStr = phoneNumber;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
}
// return isValid;
return true;
}
private void appendNewMsg(){
Log.i(TAG, "mergeMsgList");
Iterator<MsgNode> msgIt = mMsgList.iterator();
while(msgIt.hasNext()){
MsgNode msgNode = msgIt.next();
TelNode telNode = getTelNumNode(msgNode.mAdress);
// Log.i(TAG, "mergeMsgList 2");
if (telNode != null){
// Log.i(TAG, "mergeMsgList find");
if (telNode.mMsgList == null){
telNode.mMsgList = new ArrayList<MsgNode>();
}
telNode.mMsgCnt++;
if (msgNode.mRead == 0) telNode.mUnMsgCnt++;
telNode.mMsgList.add(msgNode);
}
else
{
Log.i(TAG, "mergeMsgList NOT find");
telNode = new TelNode();
telNode.mTel = msgNode.mAdress;
telNode.mMsgCnt++;
if (msgNode.mRead == 0) telNode.mUnMsgCnt++;
telNode.mMsgList = new ArrayList<MsgNode>();
telNode.mMsgList.add(msgNode);
telNode.mContactId = 0;
telNode.mName = telNode.mTel;
mTelList.add(telNode);
}
}
}
TelNode getTelNumNode(String tel) {
Log.i(TAG, "getTelNumNode" + tel);
Iterator<TelNode> telIt = mTelList.iterator();
while (telIt.hasNext()) {
TelNode telNode = telIt.next();
if (telNode.mTel.equals(tel)) {
return telNode;
}
}
Log.i(TAG, "getTelNumNode Not" + tel);
return null;
}
void appendMsgList(){
Log.i(TAG, "mergeMsgList");
Iterator<MsgNode> msgIt = mMsgList.iterator();
while(msgIt.hasNext()){
MsgNode msgNode = msgIt.next();
TelNode telNode = getTelNumNode(msgNode.mAdress);
if (telNode == null){
Log.i(TAG, "mergeMsgList NOT find");
telNode = new TelNode();
telNode.mTel = msgNode.mAdress;
telNode.mName = telNode.mTel;
mTelList.add(telNode);
}
if (telNode.mMsgList == null){
telNode.mMsgList = new ArrayList<MsgNode>();
}
telNode.mMsgCnt++;
if (msgNode.mRead == 0) telNode.mUnMsgCnt++;
if (msgNode.mDate > telNode.mLastDate){
telNode.mLastDate = msgNode.mDate;
telNode.mLastBody = msgNode.mBody;
}
telNode.mMsgList.add(msgNode);
}
}
public void addSendSms(String tel, String body, long date){
// public int mMsgId;
// public int mThreadId;
// public int mProtocol;
// public int mRead;
// public int mStatus;
// public int mType;
// public long mDate;
// public String mAdress;
// public String mSubject;
// public String mBody;
MsgNode msgNode = new MsgNode();
msgNode.mThreadId = -1;
msgNode.mProtocol = 0;
msgNode.mRead = 1;
msgNode.mStatus = 0;
msgNode.mType = 2;
msgNode.mDate = date;
msgNode.mAdress = tel;
msgNode.mBody = body;
TelNode telNode = getTelNumNode(msgNode.mAdress);
if (telNode.mMsgList == null){
telNode.mMsgList = new ArrayList<MsgNode>();
}
telNode.mMsgCnt++;
if (msgNode.mRead == 0) telNode.mUnMsgCnt++;
if (msgNode.mDate > telNode.mLastDate){
telNode.mLastDate = msgNode.mDate;
telNode.mLastBody = msgNode.mBody;
}
telNode.mMsgList.add(msgNode);
// mNewsListFrag.updateListView();
}
protected void setupPinyin() {
Log.i(TAG, "setupPinyin");
mPinyinOk = false;
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
Log.i(TAG, "setupPinyin +++++ start");
doSetupPinyin();
mPinyinOk = true;
Log.i(TAG, "setupPinyin +++++ end");
}
});
thread.start();
}
public boolean isPinyinOk(){
return mPinyinOk;
}
public void doSetupPinyin(){
Iterator<TelNode> telIt = mTelList.iterator();
while (telIt.hasNext()) {
TelNode telNode = telIt.next();
if ( telNode.mPinyin == null || telNode.mContactId>0) {
HanZiToPinYin.TelToPinYin(telNode);
}
if (telNode.mPinyin == "")
telNode.mPinyin=telNode.mName;
}
}
// 7天之内返回1,7天以前返回2
private static int beforeToday(long date) {
int sIndex = 0;
int bDay;
Time nTime = new Time();
nTime.setToNow();
Time oTime = new Time();
oTime.set(date);
int dayNow = Time.getJulianDay(nTime.normalize(true), 0);
int day = Time.getJulianDay(date, 0);
// 天数差
bDay = dayNow - day;
int wDay = nTime.weekDay;
int nMon = nTime.month;
int oMon = oTime.month;
if (bDay == 0) {
sIndex = 1;
} else if (bDay == 1) {
sIndex = 1;
} else if (bDay == 2) {
sIndex = 1;
}
// 一周之内
else if (bDay > 2 && bDay <= wDay) {
sIndex = 1;
} else {
sIndex = 2;
}
return sIndex;
}
// 根据自定义算法产生常用联系人数据
public void setupOftenContactsData() {
// 权重:7天以下:sms(4)tel(3) 7天以上:sms(3)tel(2)
int down7sms = 4, up7sms = 3, down7tel = 3, up7tel = 2;
int oftencontactsconst = 9;
int contactsnum = 0;
mOftenContacts.clear();
if(mTelList == null )
{
Log.i("setupOftenContactsData ", "err:mTelList == null") ;
return;
}
for (int i = 0; i < mTelList.size(); i++) {
TelNode TelNodeItem = mTelList.get(i);
if (TelNodeItem.mContactId != 0)
contactsnum++;
}
if (contactsnum <= oftencontactsconst)
for (int i = 0; i < mTelList.size(); i++) {
TelNode TelNodeItem = mTelList.get(i);
if (TelNodeItem.mContactId != 0)
mOftenContacts.add(TelNodeItem);
}
else {
for (int i = 0; i < mTelList.size(); i++) {
OftenContactVal OftenItem = new OftenContactVal();
TelNode TelNodeItem = mTelList.get(i);
OftenItem.mTelNode = mTelList.get(i);
OftenItem.mValue = 0;
if (TelNodeItem.mContactId != 0) {
if (1 == beforeToday(TelNodeItem.mLastDate))// tel
{
OftenItem.mValue += down7tel;// 7天以内
} else {
OftenItem.mValue += up7tel;// 7天以前
}
for (int j = 0; (j < TelNodeItem.mMsgCnt && j < TelNodeItem.mMsgList
.size()); j++) {
if (1 == beforeToday(TelNodeItem.mMsgList.get(j).mDate))// sms
OftenItem.mValue += down7sms;// 7天以内
else {
OftenItem.mValue += up7sms;// 7天以前
}
}
mTelNodeWeight.add(OftenItem);
}
}
Collections.sort(mTelNodeWeight, new SortByValue());
for (int i = 0; i < oftencontactsconst; i++) {
TelNode item = mTelNodeWeight.get(i).mTelNode;
mOftenContacts.add(item);
}
}
}
class SortByValue implements Comparator<Object> {
public int compare(Object o1, Object o2) {
OftenContactVal item1 = (OftenContactVal) o2;
OftenContactVal item2 = (OftenContactVal) o1;
if (item1.mValue < item2.mValue) {
return -1;
} else if (item1.mValue > item2.mValue) {
return 1;
} else {
return 0;
}
}
}
}