ARN ARN - 3 years ago 72
Android Question

how can i run a code just on first launch?

I want to send SMS just when the app launch for first time and for that I want to make a file in first launch and send SMS and in the next launch ask for existing that file if exist do not send SMS
here is my code

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 {

}
}

Answer Source

On Android, consider using SharedPreferences instead. It allows you to store simple informations that will be persisted to a file managed by the system.

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();
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download