我有一个任务,我必须每天发送E-Mail
一次。 我使用Service
触发AlarmManager
来实现这一点。它工作正常。但问题是,只有移动数据可用,邮件才会发送。所以我试图打开数据连接并发送邮件。移动数据已启用,但Mail不发送。我在这里发布了我试过的东西。有人请提出一种方法,等待用户打开移动数据并发送邮件。谢谢。如何等待用户启用移动数据并发送邮件?
cm=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
ni=cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
isConnected=ni!=null&&ni.isConnected();
Mail m=new Mail("[email protected]","xxxxxxx");
String[] strTo={"[email protected]"};
m.setTo(strTo);
m.setFrom("[email protected]");
m.setSubject("Subject");
m.setBody("Please find the attachment");
try{
m.addAttachment(Environment.getExternalStorageDirectory() + "/xxxxx/xxxxxx.xx");
if (isConnected){
m.send();
}else {
ConnectivityManager dataManager;
dataManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
Method dataMtd = null;
try {
dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
dataMtd.setAccessible(true);
try {
dataMtd.invoke(dataManager, true);
} catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
NetworkInfo netInfo=dataManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isOnline=netInfo!=null&&netInfo.isConnected();
if(isOnline){
if (m.send()){
ConnectivityManager dataManager1;
dataManager1 = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
Method dataMtd1 = null;
try {
dataMtd1 = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
dataMtd1.setAccessible(false);
try {
dataMtd1.invoke(dataManager1, false);
} catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}catch (final Exception e){
e.printStackTrace();
Log.v("My_Service",e.toString());
}
您是否试过广播接收器发送电子邮件 –
我无法在'BroadcastReceiver'中执行'Asynctask'。 –
从**广播接收器**开始**服务**并在服务中运行**异步** –