Prevent Reload Activity / Webview when go Back to app and when press the turn off button - android-activity

I have a fragment inside of an Activity and then, inside of this fragment I also have a webview.
Problem: After lock my screen and unlock pressing the turn off button, my Activity is recreated or my webview is reloaded (not sure what happens).
The same problem occurs when I switch apps in my device.
I tried to change my configChanges and my launchMode. Here is part of my activity in android manifest file:
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:windowSoftInputMode="adjustResize"
android:launchMode="singleTop"
>
</activity>
Also I tried to check my savedInstanceState on myCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
if (savedInstanceState == null) {
this.init(); // Initialize my webview
}
...
EDIT:
#Override
protected void onResume() {
super.onResume();
//Check if the user is authenticated onResume
String message = getIntent().getStringExtra(MainActivity.FragmentIdentifier);
if(message == null || message.compareTo(MainActivity.showWebViewFragment) == 0){
changeFragment(new WebViewFragment());
}else if (message.compareTo(MainActivity.showLoginFragment) == 0){
changeFragment(new LoginFragment());
}
}
Any ideas or code samples will be appreciated, thanks!

I figured out that I should handle the Instance and check if already saved or not, otherwise my onResume could always reload my webview. Here my new code:
#Override
protected void onResume() {
super.onResume();
//Check if the user is authenticated onResume
String message = getIntent().getStringExtra(MainActivity.FragmentIdentifier);
if (message == null || message.compareTo(MainActivity.showWebViewFragment) == 0) {
/*
Check if the instance is saved. If yes, is not necessary to create a new instance of the webview,
otherwise will always reload.
*/
if (!getSavedInstance()){
changeFragment(new WebViewFragment());
}
} else if (message.compareTo(MainActivity.showLoginFragment) == 0) {
changeFragment(new LoginFragment());
}
}
I declared a new global variable
private Boolean savedInstance = false;
And here my get and set
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
setSavedInstance(true);
}
public Boolean getSavedInstance() {
return savedInstance;
}
public void setSavedInstance(Boolean instance_saved) {
this.savedInstance = instance_saved;
}

Related

Android - Top Back Button not working

I have this button on the topmost left part. And for some reason it is not going back to it's previous page when I click it. I've checked the other links already but it is not working.
The activity code on that one
public class CardListActivity extends Activity {
private static final String LOG_TAG = CardListActivity.class.getSimpleName();
private EventBus eventBus;
private Activity activity;
private CardListRequest cardListRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
}
public void init() {
Log.e(LOG_TAG, "XXXX Start : init XXXX");
setUpActionBar();
activity = this;
setContentView(R.layout.activity_card_list);
Log.e(LOG_TAG, "XXXX Finish : init XXXX");
}
private void setUpActionBar() {
getActionBar().setTitle(CardListActivity.class.getSimpleName());
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
AndroidManifest.xml
...
<activity
android:name=".CardListActivity"
android:label="#string/title_activity_card_list"
android:parentActivityName=".HomeActivity2">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.pw.mccdealsapp.HomeActivity2" />
</activity>
...
This page contains all the information to create an Up button that works correctly.
You need to add, in your activity, something like:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
first on your onCreate method put this
//action bar back icon
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
then override this method and make back opetion go to its parent
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home){
finish();
}
return super.onOptionsItemSelected(item);
}

Android WebView in a ViewSwitcher loadUrl loads once

I have in my ViewSwitcher a ListView and a WebView. In my ListView's adapter, I have an onclick listener that writes the clicked url in the list to sharedpreferences. I'm trying to load that url into the WebView using an onSharedPreferencesChangedListener.
This is the code in my adapter:
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewSwitcher.showNext();
Settings.writeSettings(context, "webviewUrl",
urls.get(position));
}
});
return convertView;
And in the preference listener:
#Override
public void onSharedPreferenceChanged(SharedPreferences pref, String key) {
if (key.equals("webviewUrl")) {
Log.d("TAG", pref.getString(key, null));
WebView wv = (WebView) findViewById(R.id.rss_webview);
wv.getSettings().setJavaScriptEnabled(true);
wv.setWebViewClient(new MyWebViewClient());
wv.loadUrl("about:blank");
wv.loadUrl(pref.getString(key, null));
}
}
This works great except it only works once. The preference listener code logs the correct urls, and the code executes each time I want it to, but wv.loadUrl() method seems to do nothing after the first successful call. Can anyone explain to me why this is happening and perhaps offer a solution? Thanks.
I solved the problem by implementing a static ViewHolder on the WebView whose reference I needed to keep longer than its views' lifecycle.
private static final class WebViewHolder {
WebView wv;
}
#Override
public void onSharedPreferenceChanged(SharedPreferences pref, String key) {
WebViewHolder holder = new WebViewHolder();
if (key.equals("webviewUrl")) {
if (wv == null) {
wv = new WebView(this);
holder.wv = (WebView) findViewById(R.id.rss_webview);
holder.wv.getSettings().setJavaScriptEnabled(true);
holder.wv.setWebViewClient(new MyWebViewClient());
wv.setTag(holder);
} else {
holder = (WebViewHolder) wv.getTag();
}
holder.wv.loadUrl("about:blank");
holder.wv.loadUrl(pref.getString(key, null));
}
}

Multiple MediaPlayer background instead of 1

I'm trying to run an App that has only one background song that runs on all activities. But some how when I open another activity, (all the activities are extends of the main activity), the application opens another session of the song. I tried to fix it but with no success.
I don't understand why the "Music:IsPlaying" is always false despite that the song is playing, this is my code:
public class MainActivity extends ActionBarActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Music = MediaPlayer.create(MainActivity.this, R.raw.ad_matai);
if (!Music.isPlaying())
{
Music.start();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void OpenMyProfile(View view)
{
Intent open_my_profile = new Intent(this,MyProfile.class);
startActivity(open_my_profile);
}
public void OpenPeople(View view)
{
Intent open_people = new Intent(this,PazamPeople.class);
startActivity(open_pazam_people);
}
Why don't You use service for that? If You have task which should be active for longer than single activity lifecycle it should be service for that. Hit Google with 'music service android'

My Android App is crashed when I register SensorManager.registerListener

Below is my code. I am having a problem when I call SensorManager.registerListener, my app will crash. Can someone tell me what's going on?
I just follw the web guide to setup SensorManger, Sensor(Accelerometer) and then register the action lintener to detect the montion of accelerometer.
I used API 21 to develop this app.
public class MainActivity extends ActionBarActivity implements SensorEventListener{
private TextView tip;
private SensorManager mSensorManager;
private Sensor mSensor;
private float axisX = 0;
private float axisY = 0 ;
private float axisZ = 0;
#Override
protected void onResume() {
super.onResume();
setUpAcceleratorSensor();
mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpAcceleratorSensor();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void setUpAcceleratorSensor(){
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
if((mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)) != null);
else
Toast.makeText(this, "No Sensor Device Exist", Toast.LENGTH_LONG).show();
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
Sensor mySensor = event.sensor;
if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
if(event.values[0] != 0 || event.values[1] != 0 || event.values[2] != 0){
axisX = event.values[0];
axisY = event.values[1];
axisZ = event.values[2];
tip.setText("Detect your montion");
}
}
else
Toast.makeText(this, "Cannot Get Sensor Device", Toast.LENGTH_LONG).show();
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
}
Thanks.
First that I always check when something like this goes wrong, is to check that you have all the correct permissions in the Android Manifest; however, I don't believe that there are any permissions associated with using the position sensors. I would check on this first. That is what comes to mind first, after you post logcat, we will be able to give a more detailed answer.
Try getting the sensor this way
mSensor = mSensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0); instead in your setUpAccelerometer() method.

Back Button in webView

When the user clicks on back button, I've implemented the following code that works very well for links inside of my webview:
#Override
public void onBackPressed() {
if (this.webViewFragment != null && this.webViewFragment.canGoBack()) {
this.webViewFragment.goBack();
} else {
super.onBackPressed();
}
}
My problem is that I have native menu in Android, and when the user clicks on the menu Profile for example and then clicks on the menu Dashboard, the back button doesn't work. Nothing happens. As I said before, just works for links clicked inside of the webview.
Anyone knows a solution for that?
or try this
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
web.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}