【问题标题】:how can i run a code just on first launch?我怎样才能在第一次启动时运行代码?
【发布时间】:2018-03-11 15:52:18
【问题描述】:

我想在应用程序第一次启动时发送短信,为此我想在第一次启动时制作一个文件并发送短信,并在下一次启动时询问现有该文件(如果存在)不发送短信 这是我的代码

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 {

    }
}

【问题讨论】:

标签: java android


【解决方案1】:

在 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();
}

【讨论】:

    【解决方案2】:

    myFile.exsist() 应该可以工作,你有什么样的错误? 另一种方法是,如果您想创建此文件只是为了检查是否必须发送短信,请使用应用程序 SharedPreferences。

    https://developer.android.com/reference/android/content/SharedPreferences.html

    【讨论】:

      猜你喜欢
      • 2017-12-05
      • 1970-01-01
      • 2017-07-29
      • 2018-07-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多