public class MainActivity extends FragmentActivity { private TextView textView; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.text_view); } @Override protected void onStop() { super.onStop(); // Save the text in the TextView String text = textView.getText().toString(); SharedPreferences preferences = getPreferences(Context.MODE_PRIVATE); preferences.edit().putString("text", text).apply(); } }
public class MainActivity extends FragmentActivity { private Call call; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); OkHttpClient client = new OkHttpClient.Builder().build(); Request request = new Request.Builder() .url("http://example.com/data") .build(); call = client.newCall(request); } @Override protected void onStop() { super.onStop(); // Cancel any ongoing network requests if (call != null) { call.cancel(); } } }This example demonstrates how to cancel any ongoing network requests when the activity is stopped. Both examples use the android.support.v4.app.FragmentActivity class, which is part of the Android Support Library.