Check if there is network/aeroplane mode active? - java

I have an application which uses a Google PlacePicker and Google StreetView. I have to test the application with the device in aeroplane mode.
I want the application to check when it reaches this activity if aeroplane mode is active, if it is not active I would like a Toast displayed
Below is the code for an Activity an activity in which there are 2 buttons, one of the buttons loads the PlacePicker and the other loads another activity which contains the StreetView.
I have seen this How can one detect airplane mode on Android? answer and that is where I got the code I have attempted in my answer but it will not work
Can someone please tell me how to get this working
public class PlacePickerActivity extends AppCompatActivity {
int PLACE_PICKER_REQUEST = 1;
TextView tvPlace;
private Button buttonStepsActivity;
private Button buttonStreet;
private boolean isAirplaneModeOn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_picker);
tvPlace = (TextView)findViewById(R.id.tvPlace);
//StreetView
buttonStreet = (Button) findViewById(R.id.buttonStreet);
if(isAirplaneModeOn) {
Toast.makeText(this,"Aeroplane mode active",Toast.LENGTH_LONG).show();
}
}
private static boolean isAirplaneModeOn(Context context) {
return Settings.System.getInt(context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
public void goPlacePicker(View v) {
// Construct an intent for the place picker
try {
PlacePicker.IntentBuilder intentBuilder =
new PlacePicker.IntentBuilder();
Intent intent = intentBuilder.build(this);
// Start the intent by requesting a result,
// identified by a request code.
startActivityForResult(intentBuilder.build(this), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
String toastMsg = String.format("You have chosen: %s", place.getName());
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
}
}
}

Use this way
find network enable
public static boolean isNetworkAvailable(Context mContext) {
ConnectivityManager connectivity = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
find aeroplane mode enable
private static boolean isAirplaneModeOn(Context context) {
return Settings.System.getInt(context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
add this permission
<uses-permission android:name="android.permission.WRITE_SETTINGS" />

Related

Closing the app when user cancels immediate in app update

Currently i'm implementing the in app update feature from android. I'm using the immediate update method, the problem that I'm facing is that when the UI prompting the user to update shows and the user does not click the update button instead they click the cross button. The UI for the app update just closes and user can continue using the app.
What I want is that when user click the cross button the app immediately closes, until user updates the app then they can use the app as usual. I also uses the java code for the android development.
public class LoginActivity extends AppCompatActivity {
private LoginViewModel loginViewModel;
public static final String MyPREFERENCES = "LoginPrefs" ;
public static final String Name = "nameKey";
public static final String User = "userKey";
public static final String con = "closed";
public static String error = "";
public static int userFlag = 0;
SharedPreferences sharedpreferences;
SharedPreferences.Editor editor;
public TextInputEditText usernameEditText;
public TextInputEditText passwordEditText;
private AppUpdateManager mAppUpdateManager;
private int RC_APP_UPDATE = 999;
private int inAppUpdateType;
private com.google.android.play.core.tasks.Task<AppUpdateInfo> appUpdateInfoTask;
private InstallStateUpdatedListener installStateUpdatedListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginViewModel = ViewModelProviders.of(this, new LoginViewModelFactory())
.get(LoginViewModel.class);
usernameEditText = findViewById(R.id.user);
passwordEditText = findViewById(R.id.pass);
final Button loginButton = findViewById(R.id.submitBTN);
final TextInputLayout userL = findViewById(R.id.userL);
final TextInputLayout passL = findViewById(R.id.passL);
final JellyToggleButton jtb = findViewById(R.id.jtb);
// Creates instance of the manager.
mAppUpdateManager = AppUpdateManagerFactory.create(this);
// Returns an intent object that you use to check for an update.
appUpdateInfoTask = mAppUpdateManager.getAppUpdateInfo();
//lambda operation used for below listener
//For flexible update
installStateUpdatedListener = installState -> {
if (installState.installStatus() == InstallStatus.DOWNLOADED) {
popupSnackbarForCompleteUpdate();
}
};
mAppUpdateManager.registerListener(installStateUpdatedListener);
inAppUpdateType = AppUpdateType.IMMEDIATE; //1
inAppUpdate();
if(userFlag==1){
jtb.setChecked(true);
}
userL.setHint("Enter username");
sharedpreferences = getSharedPreferences(MyPREFERENCES, MODE_PRIVATE);
loginViewModel.getLoginFormState().observe(this, new Observer<LoginFormState>() {
#Override
public void onChanged(#Nullable LoginFormState loginFormState) {
if (loginFormState == null) {
return;
}
loginButton.setEnabled(loginFormState.isDataValid());
if (loginFormState.getUsernameError() != null) {
usernameEditText.setError(getString(loginFormState.getUsernameError()));
loginButton.startAnimation(AnimationUtils.loadAnimation(LoginActivity.this,R.anim.shake));
}
if (loginFormState.getPasswordError() != null) {
passwordEditText.setError(getString(loginFormState.getPasswordError()));
loginButton.startAnimation(AnimationUtils.loadAnimation(LoginActivity.this,R.anim.shake));
}
}
});
loginViewModel.getLoginResult().observe(this, new Observer<LoginResult>() {
#Override
public void onChanged(#Nullable LoginResult loginResult) {
if (loginResult == null) {
return;
}
if (loginResult.getError() != null) {
showLoginFailed(loginResult.getError());
}
if (loginResult.getSuccess() != null) {
updateUiWithUser(loginResult.getSuccess());
Intent i = new Intent(LoginActivity.this, user_dashboard.class);
startActivity(i);
}
setResult(Activity.RESULT_OK);
//Complete and destroy login activity once successful
}
});
TextWatcher afterTextChangedListener = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// ignore
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// ignore
}
#Override
public void afterTextChanged(Editable s) {
loginViewModel.loginDataChanged(usernameEditText.getText().toString(),
passwordEditText.getText().toString());
}
};
usernameEditText.addTextChangedListener(afterTextChangedListener);
passwordEditText.addTextChangedListener(afterTextChangedListener);
passwordEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
loginViewModel.login(usernameEditText.getText().toString(),
passwordEditText.getText().toString());
}
return false;
}
});
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(userFlag==0) {
loginViewModel.login(usernameEditText.getText().toString(),
passwordEditText.getText().toString());
getStaffData();
}
else if(userFlag==1){
loginWorker();
}
}
});
jtb.setOnStateChangeListener(new JellyToggleButton.OnStateChangeListener() {
#Override
public void onStateChange(float process, State state, JellyToggleButton jtb) {
if (state.equals(State.LEFT)) {
userL.setHint("Enter username");
error = "Username cannot be empty";
userFlag = 0;
}
if (state.equals(State.RIGHT)) {
userL.setHint("Enter badge ID");
error = "Badge ID cannot be empty";
userFlag = 1;
}
}
});
}
#Override
protected void onDestroy() {
mAppUpdateManager.unregisterListener(installStateUpdatedListener);
finishAndRemoveTask();
super.onDestroy();
}
#Override
protected void onResume() {
try {
mAppUpdateManager.getAppUpdateInfo().addOnSuccessListener(appUpdateInfo -> {
if (appUpdateInfo.updateAvailability() ==
UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS) {
// If an in-app update is already running, resume the update.
try {
mAppUpdateManager.startUpdateFlowForResult(
appUpdateInfo,
inAppUpdateType,
this,
RC_APP_UPDATE);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
}
});
mAppUpdateManager.getAppUpdateInfo().addOnSuccessListener(appUpdateInfo -> {
//For flexible update
if (appUpdateInfo.installStatus() == InstallStatus.DOWNLOADED) {
popupSnackbarForCompleteUpdate();
}
});
} catch (Exception e) {
e.printStackTrace();
}
super.onResume();
}
#Override //For flexible update
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_APP_UPDATE) {
//when user clicks update button
if (resultCode == RESULT_OK) {
Toast.makeText(LoginActivity.this, "App download starts...", Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
//if you want to request the update again just call checkUpdate()
Toast.makeText(LoginActivity.this, "App download canceled.", Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_IN_APP_UPDATE_FAILED) {
Toast.makeText(LoginActivity.this, "App download failed.", Toast.LENGTH_LONG).show();
}
}
}
private void updateUiWithUser(LoggedInUserView model) {
String welcome = getString(R.string.welcome);
// TODO : initiate successful logged in experience
Toast.makeText(getApplicationContext(), welcome, Toast.LENGTH_LONG).show();
}
private void showLoginFailed(#StringRes Integer errorString) {
Toast.makeText(getApplicationContext(), errorString, Toast.LENGTH_SHORT).show();
}
private void getStaffData() {
String username = usernameEditText.getText().toString();
APIInterface apiInterface3 = APIClient.getClient().create(APIInterface.class);
Call<loginList> call3 = apiInterface3.staffData(username);
call3.enqueue(new Callback<loginList>() {
#Override
public void onResponse(Call<loginList> call, Response<loginList> response) {
loginList list = response.body();
if (list!=null && list.getStatusCode()==1) { //response received.
if(list.getStaffList().size()>0){
Log.d("check-in", list.getStatusCode() + " " + list.getStaffList().get(0).getName());
Toast.makeText(LoginActivity.this,"Logged in",Toast.LENGTH_SHORT).show();
final String name = list.getStaffList().get(0).getName();
final String badge = list.getStaffList().get(0).getBadge();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name,name);
editor.putString(User,badge);
editor.putInt(con,1);
editor.apply();
}
else if(list.getStaffList().size()==0){
}
}
}
#Override
public void onFailure(Call<loginList> call, Throwable t) {
Log.d("fail",t.toString());
}
});
}
private void loginWorker(){
String username = usernameEditText.getText().toString();
String password = passwordEditText.getText().toString();
APIInterface apiInterface3 = APIClient.getClient().create(APIInterface.class);
Call<loginList> call3 = apiInterface3.loginWorker(username,password);
call3.enqueue(new Callback<loginList>() {
#Override
public void onResponse(Call<loginList> call, Response<loginList> response) {
loginList list = response.body();
Log.d("response", response.body().toString());
if (list!=null && list.getStatusCode()==1) { //response received.
if(list.getLoginList().size()>0){
Log.d("check-in", list.getStatusCode() + " " + list.getLoginList().get(0).getName());
Toast.makeText(LoginActivity.this,"Logged in",Toast.LENGTH_SHORT).show();
List<login> item = response.body().getLoginList();
final String name = list.getLoginList().get(0).getName();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name,name);
editor.putInt(con,1);
editor.apply();
}
String welcome = getString(R.string.welcome);
Toast.makeText(getApplicationContext(), welcome, Toast.LENGTH_SHORT).show();
Intent i = new Intent(LoginActivity.this, user_dashboard.class);
startActivity(i);
}
else
Toast.makeText(LoginActivity.this, "wrong ID or password",Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<loginList> call, Throwable t) {
Log.d("fail",t.toString());
}
});
editor = sharedpreferences.edit();
editor.putString(User, username);
editor.commit();
}
#Override
public void onBackPressed() {
new MaterialAlertDialogBuilder(LoginActivity.this,R.style.MyDialogTheme)
.setTitle("Exit")
.setMessage("Confirm to exit?")
.setBackground(getDrawable(R.drawable.alert_dialog))
// Specifying a listener allows you to take an action before dismissing the dialog.
// The dialog is automatically dismissed when a dialog button is clicked.
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Continue with delete
finishAffinity();
}
})
.setNegativeButton(android.R.string.no, null)
.show();
}
private void inAppUpdate() {
try {
// Checks that the platform will allow the specified type of update.
appUpdateInfoTask.addOnSuccessListener(new OnSuccessListener<AppUpdateInfo>() {
#Override
public void onSuccess(AppUpdateInfo appUpdateInfo) {
if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE
// For a flexible update, use AppUpdateType.FLEXIBLE
&& appUpdateInfo.isUpdateTypeAllowed(inAppUpdateType)) {
// Request the update.
try {
mAppUpdateManager.startUpdateFlowForResult(
// Pass the intent that is returned by 'getAppUpdateInfo()'.
appUpdateInfo,
// Or 'AppUpdateType.FLEXIBLE' for flexible updates.
inAppUpdateType,
// The current activity making the update request.
LoginActivity.this,
// Include a request code to later monitor this update request.
RC_APP_UPDATE);
} catch (IntentSender.SendIntentException ignored) {
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void popupSnackbarForCompleteUpdate() {
try {
Snackbar snackbar =
Snackbar.make(
findViewById(R.id.coordinatorL),
"An update has just been downloaded.\nRestart to update",
Snackbar.LENGTH_INDEFINITE);
snackbar.setAction("INSTALL", view -> {
if (mAppUpdateManager != null){
mAppUpdateManager.completeUpdate();
}
});
snackbar.setActionTextColor(getResources().getColor(R.color.orange));
snackbar.show();
} catch (Resources.NotFoundException e) {
e.printStackTrace();
}
}
}
The image I borrowed from google, on the left image as can be seen there is a cross button on top right user can click to close the update process
The most important point I will emphasize is that you should not force users to update the app until it is absolutely necessary (like some security issues etc). Forcing updates to users is considered a very bad user experience.
To the question you asked, you have the answer in your question itself. If you check the code you have something like this in your onActivityResult method-
if (requestCode == RC_APP_UPDATE) {
//when user clicks update button
if (resultCode == RESULT_OK) {
Toast.makeText(LoginActivity.this, "App download starts...", Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
//if you want to request the update again just call checkUpdate()
Toast.makeText(LoginActivity.this, "App download canceled.", Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_IN_APP_UPDATE_FAILED) {
Toast.makeText(LoginActivity.this, "App download failed.", Toast.LENGTH_LONG).show();
}
}
In case when the user cancels resultCode == RESULT_CANCELED or the update fails resultCode == RESULT_IN_APP_UPDATE_FAILED, you can take whatever action you want. You can finish the activity or whatever is suitable in your situation.

How can I check if a telephone number exist programmatically?

I want to do an Android App that check if a number exist or not. In particular I was thinking of calling the number to check and if it ring it means that exist, otherwise it does not.
At the moment I can read the state "IDLE" and "OFFHOOK" but not the state "CALL_STATE_RINGING" that as far as I understood trigger only for received call.
How can I understand when it is ringing and when the number is not valid?
Note: The calling approach is just an idea but I could accept others solutions if they are effective.
My code at the moment:
Listener:
public class EndCallListener extends PhoneStateListener {
private String TAG = "CALL_AUTOMATICALLY_LISTENER";
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if(TelephonyManager.CALL_STATE_RINGING == state) {
// TODO
Log.i(TAG, "RINGING, number: " + incomingNumber);
}
if(TelephonyManager.CALL_STATE_OFFHOOK == state) {
Log.i(TAG, "OFFHOOK");
}
if(TelephonyManager.CALL_STATE_IDLE == state) {
Log.i(TAG, "IDLE");
}
}
}
public class MainActivity extends AppCompatActivity {
private String TAG = "CALL_AUTOMATICALLY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
askPermission();
}
private void askPermission() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE},0);
}
public void startCall(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
String number = "+39555555555"; // fake number
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + number));
// Activate listener
EndCallListener callListener = new EndCallListener();
TelephonyManager mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
if (mTM != null) mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);
else Log.d(TAG, "TelephonyManager null");
// start call
startActivity(intent);
} else {
askPermission();
}
}
}
public void startCallNotExisting(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
String number = "+39456464564545555565656565";
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + number));
// Activate listener
EndCallListener callListener = new EndCallListener();
TelephonyManager mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
if (mTM != null) mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);
else Log.d(TAG, "TelephonyManager null");
// start call
startActivity(intent);
} else {
askPermission();
}
}
}
}
I suggest you check phone number regex instead of calling them.place this method in your helper or activity or fragment class
public static boolean validateMobile(String mobile) {
if (mobile.matches("^[+]?[0-9]{10,13}$")) {
return true;
} else {
return false;
}
}
And use it like
if(Helper.validateMobile(mobile){
//mobile is valid
}else{
//mobile is not valid}
also this regex can be different if you target one specific country.for example i use below regex for iran phone numbers
(\\+98|0)?9\\d{9}

Before intent is changing spinner also change its value

After I press the button "ΕΙΣΟΔΟΣ" a new intent is called and the spinner change its value, to first item. Although it does not effect my app, it is disturbing. I cannot find where the issue is...
the code of this activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_login);
//region find views by their IDs
spinnerNames = findViewById(R.id.spin);
startButton = findViewById(R.id.btn_start_log_in);
etNameLogIn = findViewById(R.id.et_name_log_in);
bodyHuman = findViewById(R.id.ll_body_human);
bodyWiFi = findViewById(R.id.ll_body_wifi);
imageHuman = findViewById(R.id.rl_image_human);
imageWiFi = findViewById(R.id.rl_image_wifi);
//endregion
checkConnection();
//region set on item selected listener and set also editText name log in when select from spinner
spinnerNames.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
firstTime += 1;
SpinnerItem clickedItem = (SpinnerItem) parent.getItemAtPosition(position);
String clickedName = clickedItem.getName();
if (firstTime > 1) {
etNameLogIn.setText(clickedName);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//endregion
etNameLogIn.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN || actionId == EditorInfo.IME_ACTION_DONE ) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
getWindow().getDecorView().clearFocus();
}
return false;
}
});
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (startButton.getText().equals("ΑΝΑΝΕΩΣΗ")) {
checkConnection();
} else if (startButton.getText().equals("ΕΙΣΟΔΟΣ")) {
checkConnection();
// region check whether editText log in name exists in spinner if not add it to database and spinner
for (int z = 0; z < mspinnerList.size(); z++) {
if (etNameLogIn.getText().toString().equals(mspinnerList.get(z).getName())) {
yes += 1;
}
}
if (yes == 0) {
mspinnerList.add(new SpinnerItem(etNameLogIn.getText().toString(), R.drawable.next_48));
try {
ConnectionHelper connectionHelper = new ConnectionHelper();
connect = connectionHelper.connections();
if (connect == null) {
Toast.makeText(getApplicationContext(), "Δεν υπάρχει σύνδεση με τη βάση δεδομένων.",
Toast.LENGTH_LONG).show();
} else {
String sqlQuery = myQuery;
Statement stmt = connect.createStatement();
stmt.executeUpdate(sqlQuery);
isSuccess = true;
connect.close();
}
} catch (Exception ex) {
isSuccess = false;
}
}
//endregion
if (startButton.getText().equals("ΕΙΣΟΔΟΣ")) {
Intent myIntent = new Intent(MainLoginActivity.this, MainActivity.class);
myIntent.putExtra("NAME", etNameLogIn.getText().toString()); //Optional parameters
MainLoginActivity.this.startActivity(myIntent);
}
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if(grantResults[0] == PackageManager.PERMISSION_GRANTED && requestCode == LOCATION){
//User allowed the location and you can read it now
checkConnection();
}
}
private void checkConnection() {
//If requested permission isn't Granted yet
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//Request permission from user
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION);
}else{//Permission already granted
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if(wifiInfo.getSupplicantState() == SupplicantState.COMPLETED){
String ssid = wifiInfo.getSSID();//Here you can access your SSID
if (ssid.equals("\"private-Pda\"") || ssid.equals("\"AndroidWifi\"") ) {
initList();
imageHuman.setVisibility(View.VISIBLE);
bodyHuman.setVisibility(View.VISIBLE);
imageWiFi.setVisibility(View.GONE);
bodyWiFi.setVisibility(View.GONE);
startButton.setText("ΕΙΣΟΔΟΣ");
} else {
imageWiFi.setVisibility(View.VISIBLE);
bodyWiFi.setVisibility(View.VISIBLE);
imageHuman.setVisibility(View.GONE);
bodyHuman.setVisibility(View.GONE);
startButton.setText("ΑΝΑΝΕΩΣΗ");
}
} else {
imageWiFi.setVisibility(View.VISIBLE);
bodyWiFi.setVisibility(View.VISIBLE);
imageHuman.setVisibility(View.GONE);
bodyHuman.setVisibility(View.GONE);
startButton.setText("ΑΝΑΝΕΩΣΗ");
}
}
}
private void initList() {
mspinnerList = new ArrayList<>();
try {
ConnectionHelper connectionHelper = new ConnectionHelper();
connect = connectionHelper.connections();
if (connect == null) {
Toast.makeText(getApplicationContext(), "Δεν υπάρχει σύνδεση με τη βάση δεδομένων.",
Toast.LENGTH_LONG).show();
} else {
String sqlQuery = "SELECT ONOMA FROM [KOMBOS].[dbo].[CCCAPOGRAFI]";
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery(sqlQuery);
while (rs.next()) {
mspinnerList.add(new SpinnerItem(rs.getString("ONOMA"), R.drawable.next_48));
}
mAdapter = new SpinnerAdapter(this, mspinnerList);
spinnerNames.setAdapter(mAdapter);
isSuccess = true;
connect.close();
}
} catch (Exception ex) {
isSuccess = false;
}
}
}
Video that represents how my app is behaving. I have searched but couldn't find anything.
I think (but not 100% sure) it may be due to activity live cycle: onStop() method is invoked, which erase local data from your spinner and jumps to begenning of the array linked to AdapterView.
Overload onSaveInstanceState:
onSaveInstanceState(Bundle outState){
outState.putInt("position", [variable with chosen position])
}
And add to onCreate:
if(savedInstanceState!=null){
[variable with chosen position] = savedInstanceState.getInt("position");
// with that variable set position in your spinner here
}
Although I don't know if adding in onCreate() will do.
You can also try overloading OnStop() and setting spinner value.
Hope that helps

Where exactly to insert onPause() in Android?

Sorry for this question, I'm a beginner.
My first app has been rejected due to violating the Device and Network Abuse policy.
Edit: Main reason is that Youtube video doesn't stop playing when the display is turned off...
some info here:
Volating the Device and Network Abuse policy
I should add
#Override
public void onPause(){
super.onPause();
mWebView.onPause();
}
But where exactly I should insert this code?
Please help.
My Java code is here:
WebView asw_view;
ProgressBar asw_progress;
TextView asw_loading_text;
NotificationManager asw_notification;
Notification asw_notification_new;
private String asw_cam_message;
private ValueCallback<Uri> asw_file_message;
private ValueCallback<Uri[]> asw_file_path;
private final static int asw_file_req = 1;
private final static int loc_perm = 1;
private final static int file_perm = 2;
private SecureRandom random = new SecureRandom();
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (Build.VERSION.SDK_INT >= 21) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimary));
Uri[] results = null;
if (resultCode == Activity.RESULT_OK) {
if (requestCode == asw_file_req) {
if (null == asw_file_path) {
return;
}
if (intent == null || intent.getData() == null) {
if (asw_cam_message != null) {
results = new Uri[]{Uri.parse(asw_cam_message)};
}
} else {
String dataString = intent.getDataString();
if (dataString != null) {
results = new Uri[]{ Uri.parse(dataString) };
} else {
if(ASWP_MULFILE) {
if (intent.getClipData() != null) {
final int numSelectedFiles = intent.getClipData().getItemCount();
results = new Uri[numSelectedFiles];
for (int i = 0; i < numSelectedFiles; i++) {
results[i] = intent.getClipData().getItemAt(i).getUri();
}
}
}
}
}
}
}
asw_file_path.onReceiveValue(results);
asw_file_path = null;
} else {
if (requestCode == asw_file_req) {
if (null == asw_file_message) return;
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
asw_file_message.onReceiveValue(result);
asw_file_message = null;
}
}
}
#SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.w("READ_PERM = ",Manifest.permission.READ_EXTERNAL_STORAGE);
Log.w("WRITE_PERM = ",Manifest.permission.WRITE_EXTERNAL_STORAGE);
//Prevent the app from being started again when it is still alive in the background
if (!isTaskRoot()) {
finish();
return;
}
setContentView(R.layout.activity_main);
if (ASWP_PBAR) {
asw_progress = findViewById(R.id.msw_progress);
} else {
findViewById(R.id.msw_progress).setVisibility(View.GONE);
}
asw_loading_text = findViewById(R.id.msw_loading_text);
Handler handler = new Handler();
//Launching app rating request
if (ASWP_RATINGS) {
handler.postDelayed(new Runnable() { public void run() { get_rating(); }}, 1000 * 60); //running request after few moments
}
//Getting basic device information
get_info();
//Getting GPS location of device if given permission
if(!check_permission(1)){
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, loc_perm);
}
get_location();
asw_view = findViewById(R.id.msw_view);
//Webview settings; defaults are customized for best performance
WebSettings webSettings = asw_view.getSettings();
if(!ASWP_OFFLINE){
webSettings.setJavaScriptEnabled(ASWP_JSCRIPT);
}
webSettings.setSaveFormData(ASWP_SFORM);
webSettings.setSupportZoom(ASWP_ZOOM);
webSettings.setGeolocationEnabled(ASWP_LOCATION);
webSettings.setAllowFileAccess(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
webSettings.setUseWideViewPort(true);
webSettings.setDomStorageEnabled(true);
asw_view.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
request.addRequestHeader("User-Agent", userAgent);
request.setDescription(getString(R.string.dl_downloading));
request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimeType));
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
assert dm != null;
dm.enqueue(request);
Toast.makeText(getApplicationContext(), getString(R.string.dl_downloading2), Toast.LENGTH_LONG).show();
}
});
if (Build.VERSION.SDK_INT >= 21) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
asw_view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
} else if (Build.VERSION.SDK_INT >= 19) {
asw_view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}
asw_view.setVerticalScrollBarEnabled(false);
asw_view.setWebViewClient(new Callback());
asw_view.getSettings().setLoadWithOverviewMode(true);
asw_view.getSettings().setUseWideViewPort(true);
asw_view.setInitialScale(1);
asw_view.getSettings().setJavaScriptEnabled(true);
//Rendering the default URL
aswm_view(ASWV_URL, false);
asw_view.setWebChromeClient(new WebChromeClient() {
//Handling input[type="file"] requests for android API 16+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
if(ASWP_FUPLOAD) {
asw_file_message = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType(ASWV_F_TYPE);
if(ASWP_MULFILE) {
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
startActivityForResult(Intent.createChooser(i, getString(R.string.fl_chooser)), asw_file_req);
}
}
//Handling input[type="file"] requests for android API 21+
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams){
get_file();
if(ASWP_FUPLOAD) {
if (asw_file_path != null) {
asw_file_path.onReceiveValue(null);
}
asw_file_path = filePathCallback;
Intent takePictureIntent = null;
if (ASWP_CAMUPLOAD) {
takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = create_image();
takePictureIntent.putExtra("PhotoPath", asw_cam_message);
} catch (IOException ex) {
Log.e(TAG, "Image file creation failed", ex);
}
if (photoFile != null) {
asw_cam_message = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
if(!ASWP_ONLYCAM) {
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType(ASWV_F_TYPE);
if (ASWP_MULFILE) {
contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
}
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.fl_chooser));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, asw_file_req);
}
return true;
}
//Getting webview rendering progress
#Override
public void onProgressChanged(WebView view, int p) {
if (ASWP_PBAR) {
asw_progress.setProgress(p);
if (p == 100) {
asw_progress.setProgress(0);
}
}
}
// overload the geoLocations permissions prompt to always allow instantly as app permission was granted previously
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
if(Build.VERSION.SDK_INT < 23 || (Build.VERSION.SDK_INT >= 23 && check_permission(1))){
// location permissions were granted previously so auto-approve
callback.invoke(origin, true, false);
} else {
// location permissions not granted so request them
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, loc_perm);
}
}
});
if (getIntent().getData() != null) {
String path = getIntent().getDataString();
/*
If you want to check or use specific directories or schemes or hosts
Uri data = getIntent().getData();
String scheme = data.getScheme();
String host = data.getHost();
List<String> pr = data.getPathSegments();
String param1 = pr.get(0);
*/
aswm_view(path, false);
}
}
#Override
public void onResume() {
super.onResume();
//Coloring the "recent apps" tab header; doing it onResume, as an insurance
if (Build.VERSION.SDK_INT >= 23) {
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
ActivityManager.TaskDescription taskDesc;
taskDesc = new ActivityManager.TaskDescription(getString(R.string.app_name), bm, getColor(R.color.colorPrimary));
MainActivity.this.setTaskDescription(taskDesc);
}
get_location();
}
//Setting activity layout visibility
private class Callback extends WebViewClient {
public void onPageStarted(WebView view, String url, Bitmap favicon) {
get_location();
}
public void onPageFinished(WebView view, String url) {
findViewById(R.id.msw_welcome).setVisibility(View.GONE);
findViewById(R.id.msw_view).setVisibility(View.VISIBLE);
}
//For android below API 23
#SuppressWarnings("deprecation")
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getApplicationContext(), getString(R.string.went_wrong), Toast.LENGTH_SHORT).show();
aswm_view("file:///android_res/raw/error.html", false);
}
//Overriding webview URLs
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return url_actions(view, url);
}
//Overriding webview URLs for API 23+ [suggested by github.com/JakePou]
#TargetApi(Build.VERSION_CODES.N)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return url_actions(view, request.getUrl().toString());
}
}
//Random ID creation function to help get fresh cache every-time webview reloaded
public String random_id() {
return new BigInteger(130, random).toString(32);
}
//Opening URLs inside webview with request
void aswm_view(String url, Boolean tab) {
if (tab) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
} else {
if(url.contains("?")){ // check to see whether the url already has query parameters and handle appropriately.
url += "&";
} else {
url += "?";
}
url += "rid="+random_id();
asw_view.loadUrl(url);
}
}
//Actions based on shouldOverrideUrlLoading
public boolean url_actions(WebView view, String url){
boolean a = true;
//Show toast error if not connected to the network
if (!ASWP_OFFLINE && !DetectConnection.isInternetAvailable(MainActivity.this)) {
Toast.makeText(getApplicationContext(), getString(R.string.check_connection), Toast.LENGTH_SHORT).show();
//Use this in a hyperlink to redirect back to default URL :: href="refresh:android"
} else if (url.startsWith("refresh:")) {
aswm_view(ASWV_URL, false);
//Use this in a hyperlink to launch default phone dialer for specific number :: href="tel:+919876543210"
} else if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
//Use this to open your apps page on google play store app :: href="rate:android"
} else if (url.startsWith("rate:")) {
final String app_package = getPackageName(); //requesting app package name from Context or Activity object
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + app_package)));
} catch (ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + app_package)));
}
//Sharing content from your webview to external apps :: href="share:URL" and remember to place the URL you want to share after share:___
} else if (url.startsWith("share:")) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, view.getTitle());
intent.putExtra(Intent.EXTRA_TEXT, view.getTitle()+"\nVisit: "+(Uri.parse(url).toString()).replace("share:",""));
startActivity(Intent.createChooser(intent, getString(R.string.share_w_friends)));
//Use this in a hyperlink to exit your app :: href="exit:android"
} else if (url.startsWith("exit:")) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
//Opening external URLs in android default web browser
} else if (ASWP_EXTURL && !aswm_host(url).equals(ASWV_HOST)) {
aswm_view(url,true);
} else {
a = false;
}
return a;
}
//Getting host name
public static String aswm_host(String url){
if (url == null || url.length() == 0) {
return "";
}
int dslash = url.indexOf("//");
if (dslash == -1) {
dslash = 0;
} else {
dslash += 2;
}
int end = url.indexOf('/', dslash);
end = end >= 0 ? end : url.length();
int port = url.indexOf(':', dslash);
end = (port > 0 && port < end) ? port : end;
Log.w("URL Host: ",url.substring(dslash, end));
return url.substring(dslash, end);
}
//Getting device basic information
public void get_info(){
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.setCookie(ASWV_URL, "DEVICE=android");
cookieManager.setCookie(ASWV_URL, "DEV_API=" + Build.VERSION.SDK_INT);
}
//Checking permission for storage and camera for writing and uploading images
public void get_file(){
String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
//Checking for storage permission to write images for upload
if (ASWP_FUPLOAD && ASWP_CAMUPLOAD && !check_permission(2) && !check_permission(3)) {
ActivityCompat.requestPermissions(MainActivity.this, perms, file_perm);
//Checking for WRITE_EXTERNAL_STORAGE permission
} else if (ASWP_FUPLOAD && !check_permission(2)) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, file_perm);
//Checking for CAMERA permissions
} else if (ASWP_CAMUPLOAD && !check_permission(3)) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, file_perm);
}
}
//Using cookies to update user locations
public void get_location(){
//Checking for location permissions
if (ASWP_LOCATION && ((Build.VERSION.SDK_INT >= 23 && check_permission(1)) || Build.VERSION.SDK_INT < 23)) {
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
GPSTrack gps;
gps = new GPSTrack(MainActivity.this);
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
if (gps.canGetLocation()) {
if (latitude != 0 || longitude != 0) {
cookieManager.setCookie(ASWV_URL, "lat=" + latitude);
cookieManager.setCookie(ASWV_URL, "long=" + longitude);
//Log.w("New Updated Location:", latitude + "," + longitude); //enable to test dummy latitude and longitude
} else {
Log.w("New Updated Location:", "NULL");
}
} else {
show_notification(1, 1);
Log.w("New Updated Location:", "FAIL");
}
}
}
//Checking if particular permission is given or not
public boolean check_permission(int permission){
switch(permission){
case 1:
return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
case 2:
return ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
case 3:
return ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
}
return false;
}
//Creating image file for upload
private File create_image() throws IOException {
#SuppressLint("SimpleDateFormat")
String file_name = new SimpleDateFormat("yyyy_mm_ss").format(new Date());
String new_name = "file_"+file_name+"_";
File sd_directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return File.createTempFile(new_name, ".jpg", sd_directory);
}
//Launching app rating dialoge [developed by github.com/hotchemi]
public void get_rating() {
if (DetectConnection.isInternetAvailable(MainActivity.this)) {
AppRate.with(this)
.setStoreType(StoreType.GOOGLEPLAY) //default is Google Play, other option is Amazon App Store
.setInstallDays(SmartWebView.ASWR_DAYS)
.setLaunchTimes(SmartWebView.ASWR_TIMES)
.setRemindInterval(SmartWebView.ASWR_INTERVAL)
.setTitle(R.string.rate_dialog_title)
.setMessage(R.string.rate_dialog_message)
.setTextLater(R.string.rate_dialog_cancel)
.setTextNever(R.string.rate_dialog_no)
.setTextRateNow(R.string.rate_dialog_ok)
.monitor();
AppRate.showRateDialogIfMeetsConditions(this);
}
//for more customizations, look for AppRate and DialogManager
}
//Creating custom notifications with IDs
public void show_notification(int type, int id) {
long when = System.currentTimeMillis();
asw_notification = (NotificationManager) MainActivity.this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent i = new Intent();
if (type == 1) {
i.setClass(MainActivity.this, MainActivity.class);
} else if (type == 2) {
i.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
} else {
i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.setData(Uri.parse("package:" + MainActivity.this.getPackageName()));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
}
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this, "");
switch(type){
case 1:
builder.setTicker(getString(R.string.app_name));
builder.setContentTitle(getString(R.string.loc_fail));
builder.setContentText(getString(R.string.loc_fail_text));
builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getString(R.string.loc_fail_more)));
builder.setVibrate(new long[]{350,350,350,350,350});
builder.setSmallIcon(R.mipmap.ic_launcher);
break;
case 2:
builder.setTicker(getString(R.string.app_name));
builder.setContentTitle(getString(R.string.loc_perm));
builder.setContentText(getString(R.string.loc_perm_text));
builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getString(R.string.loc_perm_more)));
builder.setVibrate(new long[]{350, 700, 350, 700, 350});
builder.setSound(alarmSound);
builder.setSmallIcon(R.mipmap.ic_launcher);
break;
}
builder.setOngoing(false);
builder.setAutoCancel(true);
builder.setContentIntent(pendingIntent);
builder.setWhen(when);
builder.setContentIntent(pendingIntent);
asw_notification_new = builder.build();
asw_notification.notify(id, asw_notification_new);
}
//Checking if users allowed the requested permissions or not
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults){
switch (requestCode){
case 1: {
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
get_location();
}
}
}
}
//Action on back key tap/click
#Override
public boolean onKeyDown(int keyCode, #NonNull KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (asw_view.canGoBack()) {
asw_view.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
protected void onSaveInstanceState(Bundle outState ){
super.onSaveInstanceState(outState);
asw_view.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
asw_view.restoreState(savedInstanceState);
}
}
Anywhere you want inside your Activity class (the one you pasted in your question).
I usually try to order my lifecycle methods in the order Android executes them, so I'd put it after onResume()
#Override
public void onResume() {
super.onResume();
asm_view.onResume(); //remember to add this so your WebView can resume
//Coloring the "recent apps" tab header; doing it onResume, as an insurance
if (Build.VERSION.SDK_INT >= 23) {
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
ActivityManager.TaskDescription taskDesc;
taskDesc = new ActivityManager.TaskDescription(getString(R.string.app_name), bm, getColor(R.color.colorPrimary));
MainActivity.this.setTaskDescription(taskDesc);
}
get_location();
}
#Ovveride
public void onPause() {
super.onPause();
asw_view.onPause(); //your WebView variable is asm_view, not mWebView, which is just example code
}
onPause is a lifecycle method of Activity (and Fragments) and can be placed anywhere in the Activity class but putting your lifecycle methods in the order they are executed will help making your code more readable.

android - Google places opens the map on closes after 1 sec

Im creating an intent to an activity by clicking on a button which should open google places, but it closes again really fast and says no location selected, and returns to the main activity, and then nothing happens if i click again.
My api should be fine, I have checked that it's the correct SHA1-fingerprint thats connected to the api key.
The result code is 2
It worked earlier in the activity before this one, but I needed it to open when i click on a button instead, and now when I try to open this new activity as an intent it wont work.
public class MapActivity extends AppCompatActivity {
int PLACE_PICKER_REQUEST = 1;
int status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_events);
status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (status != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(status)) {
GooglePlayServicesUtil.getErrorDialog(status, this,
100).show();
}
}
if (status == ConnectionResult.SUCCESS) {
int PLACE_PICKER_REQUEST = 199;
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
Context context = this;
try {
startActivityForResult(builder.build(context), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println("Result code: " + resultCode);
System.out.println("Request code: " + requestCode);
if (requestCode == 100) {
status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
}
if (requestCode == 199) {
//process Intent......
if (data != null) {
Place place = PlacePicker.getPlace(data, this);
String toastMsg = String.format("Place: %s", place.getName());
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
} else {
String toastMsg = ("No location selected.");
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
}
}
}
}
This is from the intent which create the new intent to maps
public void onClick(View view) {
Intent i = new Intent(this, MapActivity.class);
startActivity(i);
}
I think its happening because of you are using old method of getPlace
try to swap the arguments, by changing it from:
Place place = PlacePicker.getPlace(data, this);
to
Place place = PlacePicker.getPlace(getContext(), data);
Update #2
Enable Google places API in the developer console and add these lines to AndroidManifest
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="ADD_YOUR_API_KEY_HERE" />
Update #3
after some search, it looks like there is others having same issue. Look at these links:
https://github.com/zhangtaii/react-native-google-place-picker/issues/21
https://stackoverflow.com/a/32751164/
https://github.com/googlesamples/android-play-places/issues/13

Categories

Resources