我想在第一次启动应用程序时发送短信,为此我想在首次启动时发送文件并发送短信,并在下次启动时询问现有文件是否存在不发送短信 这是我的代码
public static String file_name = "save_setting";
public static String text_file = "1";
public void writefile(){
try {
FileOutputStream fos_setting = openFileOutput(file_name , MODE_PRIVATE);
fos_setting.write(text_file.getBytes());
fos_setting.close();
}catch (Exception e) {
e.printStackTrace();
}
}
public void sendSMS(){
String phoneNumber = "000000000";
String message = "text";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,new Intent("SENT_SMS"), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, null);
}
public void readfile() {
File directory = Environment.getDataDirectory();
File file = new File(directory + "/save_setting");
if (!file.exists()) {
writefile();
sendSMS();
} else {
}
}
答案 0 :(得分:0)
在Android上,请考虑使用SharedPreferences。它允许您存储将持久保存到系统管理的文件的简单信息。
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean isFirstLaunch = prefs.getBoolean("first_launch", true);
if (isFirstLaunch) {
// Do your stuff here...
sendSMS();
// Remember that you already have sent the SMS
prefs.edit().putBoolean("first_launch", false).apply();
}
答案 1 :(得分:0)
myFile.exsist()应该有效,你有什么样的错误? 另一种方法,如果你想创建这个文件只是为了检查你是否必须发送短信,请使用应用程序SharedPreferences。
https://developer.android.com/reference/android/content/SharedPreferences.html