Android 如何在非活动类中发送短信?
我有一个服务类和一个util类。 在util类中,我向手机发送短信。但是在util类中,有许多函数使用参数,例如context,但是util没有扩展任何内容,只是一个简单的类。怎么做?试着这样做:Android 如何在非活动类中发送短信?,android,android-layout,android-widget,Android,Android Layout,Android Widget,我有一个服务类和一个util类。 在util类中,我向手机发送短信。但是在util类中,有许多函数使用参数,例如context,但是util没有扩展任何内容,只是一个简单的类。怎么做?试着这样做: public class ABCD extends Service{ Util util = new Util(this); } public class Util{ private Context context = null;
public class ABCD extends Service{
Util util = new Util(this);
}
public class Util{
private Context context = null;
public Util(Context context){
this.context = context;
}
}
如果我理解正确,那么在使用util类创建任何对象时,都必须将上下文作为参数传递 所以,我假设在您的服务类中,您正在创建一个发送sms的Util类。。。我将只是编一些代码,可能适合你正在做的 在您的服务类中,执行此操作
Util util = new Util(this)
这样做将创建一个具有服务上下文的Util对象,只需确保Util类具有适当的构造函数来保留上下文(供以后使用)。在您的Util类中使用
public class Util {
private Context c //storage for the Context
public Util (Context context){ //constructor for Util
this.c = context;
}
}
希望有帮助。就像这样。将所有PendingEvent设置为空
public static boolean smsSender(String to, String msg) {
SmsManager smsManager = SmsManager.getDefault();
try {
List<String> contents = smsManager.divideMessage(msg);
for (String content : contents){
smsManager.sendTextMessage(to, null, content, null, null);
}
return true;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return false;
}
}
公共静态布尔smsSender(字符串到,字符串消息){
SmsManager SmsManager=smsmsmanager.getDefault();
试一试{
列表内容=smsManager.divideMessage(msg);
for(字符串内容:contents){
sendTextMessage(to,null,content,null,null);
}
返回true;
}捕获(例外e){
//TODO:处理异常
e、 printStackTrace();
返回false;
}
}
使用活动上下文的引用从非活动类发送Sms注意,这样存储上下文
对象是个坏主意。您将保留对它的引用,一旦它被销毁,它将不会被垃圾收集(除非ABCD也被垃圾收集)。相反,请立即使用上下文
访问SMS服务。