安卓位置邮件发送服务的设计与实现
服务概述
核心功能实现
1. 服务生命周期管理
java
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "EmailService created");
createNotificationChannel();
startForeground(NOTIFICATION_ID, createNotification());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 处理启动参数并执行邮件发送逻辑
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "EmailService destroyed");
networkExecutor.shutdown();
}
2. 邮件发送功能
java
private void sendEmailWithAddress(String recipientEmail, String senderEmail, String emailPassword,
double latitude, double longitude, String address) {
try {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.qq.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props, null);
Message message = new MimeMessage(session);
// 设置邮件基本信息
message.setFrom(new InternetAddress(senderEmail));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail));
message.setSubject("位置更新(含详细地址)");
// 构建包含位置信息的邮件内容
String gaodeMapUrl = "https://uri.amap.com/marker?position=" + longitude + "," + latitude + "&name=当前位置";
String msg = "当前位置信息:\n" +
"纬度:" + latitude + "\n" +
"经度:" + longitude + "\n" +
"详细地址:" + address + "\n\n" +
"查看高德地图:" + gaodeMapUrl;
message.setText(msg);
// 执行邮件发送
Transport transport = session.getTransport("smtp");
transport.connect(senderEmail, emailPassword);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
Log.d(TAG, "邮件发送成功(含详细地址)");
showToast("位置邮件发送成功");
} catch (MessagingException e) {
Log.e(TAG, "发送邮件失败:" + e.getMessage());
showToast("邮件发送失败:" + e.getMessage());
} finally {
stopSelf();
}
}
3. 位置信息处理
java
// 使用 LocationUtils 获取详细地址
LocationUtils locationUtils = LocationUtils.getInstance();
ArrayList<String> locationDetails = locationUtils.getLocations(this);
// 解析得到的地址
String address = "";
if (!locationDetails.isEmpty()) {
address = locationDetails.get(0); // 获取地址信息
} else {
address = "未能获取地址";
}