i want to restart an activity when i make changes to wifi settings menu if connection is disabled.
this is my code (onCreate method):
boolean status = ConnectionManager.getConnectivityStatusString(this);
if(status){
networkStatus.setText("SEI CONNESSO AD INTERNET !");
}else{
networkStatus.setText("connection not present");
FragmentManager fragmentManager = getSupportFragmentManager();
MsgAlertConnection newAlertConnection = new MsgAlertConnection();
newAlertConnection.show(fragmentManager, "Fragment");
}
and this is the code that show a dialog :
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// 2. Chain together various setter methods to set the dialog characteristics
builder.setTitle("Connection Error !")
.setMessage("Please check your Internet Connection for start the application.")
.setPositiveButton("Back to Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent=new Intent();
intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.WirelessSettings"));
startActivity(intent);
}
});
// Create the AlertDialog object and return it
return builder.create();
}
when a user change the wifi network on "ON", how i restart or resume the application for check network connection ?
Thanks
I think that if you need to restart the activity - then something is wrong with your design - anyway
startActivity(getIntent());
finish();
this will do the trick
With onRestart method
protected void onRestart() {
super.onRestart();
}
Call recreate() from the activity
public void recreate ()
Cause this Activity to be recreated with a new instance. This results in essentially the same flow as when the Activity is created due to a configuration change -- the current instance will go through its lifecycle to onDestroy() and a new instance then created after it.
Try to put the first block of code in onResume() method.
When back from WirelessSettings to the activity, the onResume method was called and assign a new value to status var.
Try this one.
#Override
protected void onResume() {
super.onResume();
notify("onResume");
}
or
#Override
protected void onStart() {
super.onStart(); // Always call the superclass method first
// The activity is either being restarted or started for the first time
// so this is where we should make sure that GPS is enabled
LocationManager locationManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!gpsEnabled) {
// Create a dialog here that requests the user to enable GPS, and use an intent
// with the android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS action
// to take the user to the Settings screen to enable GPS when they click "OK"
}
}
#Override
protected void onRestart() {
super.onRestart(); // Always call the superclass method first
// Activity being restarted from stopped state
}
Please Visit this link.
http://developer.android.com/training/basics/activity-lifecycle/stopping.html
Related
I got this code and wanted to change it to always active.
At this moment I have to click on a Button to get the app started.
Is this even possible?
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
checkGps();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
return;
}
if (status == false)
bindService();
locate = new ProgressDialog(MainActivity.this);
locate.setIndeterminate(true);
locate.setCancelable(false);
locate.setMessage("Suche GPS-Signal");
locate.show();
start.setVisibility(View.GONE);
pause.setVisibility(View.VISIBLE);
pause.setText("Pause");
stop.setVisibility(View.VISIBLE);
}
});
Then you don’t need in any onClick listeners. Change it to method outside of onCreate { }
public void start () {
checkGps();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
return;
}
if (status == false)
bindService();
locate = new ProgressDialog(MainActivity.this);
locate.setIndeterminate(true);
locate.setCancelable(false);
locate.setMessage("Suche GPS-Signal");
locate.show();
start.setVisibility(View.GONE);
pause.setVisibility(View.VISIBLE);
pause.setText("Pause");
stop.setVisibility(View.VISIBLE);
}
});
And call this method in “onCreate” start();
you can put your code inside onCreate().
button listeners are triggers that fire upon button clicks. they have nothing to do with your program logic
Activity has life cycle methods that are called one after another you can override one of them. which one? (this depends on your needs)
see activity lifecycle.
mention your onClick method into onCreate, onResume, onStart, onPause methods it will active all time if you want to active after killing app then make Service for this may be it will help you. Thanks
I have a service that is, among other things, downloading images from internet. When this is done I want to show this image in a custom Activity that has a dialog theme. But I only want to use this pop up if the app is running, otherwise I just want to create a notification.
But I get an exception when I try to start an activity from my service and i feel that maybe this isn't the right way to do it?
It says:
android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
So my question is if this is the right way to do this by setting that flag or how should I get my downloaded image from my service to an activity. Can I in some way tell an activity to start a new activity from my service class?
I think using Broadcast Receiver is better option for you.
Add Below Method in Service and call this method when image Download Complete.
private void updateMyActivity(Context context) {
if(MainActivity.activityStatusFlag){
//update the activity if activityStatusFlag=true;
Intent intent = new Intent("mUpdateActivity");
context.sendBroadcast(intent);
}else{
//display notification if activityStatusFlag=false;
}
}
In Activity Add Following Code.
public class MainActivity extends Activity{
public static boolean activityStatusFlag= false;
//define this variable to check if activity is running or not.
#Override
protected void onResume() {
super.onResume();
activityStatusFlag = true;
this.getApplicationContext().
registerReceiver(mMessageReceiver,new IntentFilter("mUpdateActivity"));
}
#Override
protected void onPause() {
super.onPause();
activityStatusFlag = false;
this.getApplicationContext().unregisterReceiver(mMessageReceiver);
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Display Popup or update Activity
}
};
}
I am working on a To Do List Android application (it happens to be for a class assignment, but that's not what I'm asking about--I've tried to leave out as much code as I could). The main screen displays a list of ToDo items with a button at the bottom to open the Add New ToDo Item screen.
On the Add New ToDo Item screen, there is a Cancel button.
Relevant ToDoManagerActivity.java snippet:
public void onCreate(Bundle savedInstanceState) {
// Init and setup adapter, etc.
footerView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(ToDoManagerActivity.this, AddToDoActivity.class);
startActivityForResult(intent, ADD_TODO_ITEM_REQUEST);
}
});
// Attach the adapter to this ListActivity's ListView
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
log("Entered onActivityResult()");
// Check result code and request code.
// If user submitted a new ToDoItem
// Create a new ToDoItem from the data Intent
// and then add it to the adapter
}
Relevant AddToDoActivity.java snippet:
protected void onCreate(Bundle savedInstanceState) {
// Initialize default view, handle other events, etc.
final Button cancelButton = (Button) findViewById(R.id.cancelButton);
cancelButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
setResult(RESULT_CANCELED, new Intent());
finish();
}
});
}
The above code works. Previously, I was trying this in the onClick handler for cancelButton:
public void onClick(View v) {
finishActivity(RESULT_CANCELED);
}
When I clicked the Cancel button, I could see that the onActivityResult was being reached in the logs, but the screen was not reverting back to the main ToDo list screen.
Why does the above code not return me to the previous screen, but the following code does return me to the previous screen? What am I misunderstanding about the task backstack/activities?
public void onClick(View v) {
setResult(RESULT_CANCELED, new Intent());
finish();
}
According to the documentation:
public void finish ()
Call this when your activity is done and should be closed. The ActivityResult is propagated back to whoever launched you via
onActivityResult().
and
public void finishActivity (int requestCode)
Force finish another activity that you had previously started with startActivityForResult(Intent, int).
You should call finish() to close the current activity and finishActivity() to close another activity you started using startActivityForResult(Intent intent, int requestCode). Calling finishActivity() on the current activity will not close it.
Also, there's no point in creating a new Intent for setResult() as you are not passing back any data. Doing this would be sufficient:
setResult(RESULT_CANCELED);
finish();
From Android Docs:
public void finishActivity (int requestCode)
Force finish another activity that you had previously started with startActivityForResult(Intent, int).
finishActivity does not finish the current activity but calls finish for an activity called with requestCode
If you look at the documentation for finishActivity() it says that it will force finish an activity started with startActivityForResult(), but you have to pass in the request code that you used to start the other activity. In your case it would be ADD_TODO_ITEM_REQUEST.
This is probably not the API you want to use. Your 2nd method is cleaner in that you don't need to force close the child activity, but let it finish in the normal way.
I currently confused on how I can display my dialog only if the application is first time to load only with orientation change. I have only one activity composed of tabs.
Problem:
I tried using boolean variables and preferences but I can't figure out on where to place them in cases where the activity's view is being destroyed. Destroyed is either by exiting the app or orientation change. Secondly, during orientation changes the dialog should be showed again on first time, but the even if I dismiss dialog and do orientation change - the dialog is displayed again which should not happen. I prefer not using the onConfigurationChanged(Configuration).
boolean FirstTimeActivityOpened = true;
boolean dialogDismissed = false;
boolean orientationChanged = false;
++++++++++
if(FirstTimeActivityOpened && dialogDismissed && orientationChanged ){
loadDialog(this);
}
new OrientationEventListener(MainActivity.this,
SensorManager.SENSOR_DELAY_NORMAL){
#Override
public void onOrientationChanged(int orientation) {
// TODO Auto-generated method stub
orientationChanged = true;
//Toast.makeText(MainActivity.this, "onOrientationChanged"+ orientation, Toast.LENGTH_SHORT).show();
}};
loadDialog
dialog.setOnDismissListener(new OnDismissListener(){
#Override
public void onDismiss(DialogInterface arg0) {
// TODO Auto-generated method stub
dialogDismissed = true;
Toast.makeText(MainActivity.this, "Dialog Dismissed", Toast.LENGTH_SHORT).show();
}});
+++++++++++++
#Override
public void onDestroy() {
super.onDestroy();
if(dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
//or
if(dialog != null) {
dialog.dismiss();
}
}
I found out during my study:
FirstLoad:
onCreate()
onStart()
onResume()
Change or Orientation:
onPause()
onStop()
onDestroy()
onCreate()
onStart()
onRestoreInstantState()
onResume()
Activity not visible but not destroyed
onPause()
onStop()
Activity opened from Pause State:
onRestart()
onStart()
onResume()
Activity not visible and destroyed:
onPause()
onStop()
onDestroy()
Activity Destroyed and Re-opened
onCreate()
onStart()
I think you should store them in shared preferences so that you don't lose them when you restart your application or when the activity reloads.
Edit :
First of all, add this line to your manifest if it is not already done :
android:configChanges="orientation"
Adding this won't let your activity restart when the orientation changes.
In that case, you can set your FirstTimeActivityOpened to true at the beggining of the onCreate() method of your activity and you can set it to false in onDestroy().
Now, you already know when the orientation changes. So when it changes, you just have to prompt your dialog IF it is the first time your app is opened.
Hope this helps
I have a progress dialog I am trying to show when a user clicks a button to launch a new activity. The spinner should be displayed on the current page until the other activity appears. ( The activity can take sometimes up to 4-5 seconds to launch and without the spinner it just shows a pressed button that looks frozen )
This is what I have, it's only working if I remove hideProgressDialog();, but then the spinner will still be there when I back to the previous activity, obviously.
What am I doing wrong ?
Progress Dialog :
public void showProgressDialog(Context context) {
if(this.progressDialog != null) {
this.progressDialog.dismiss();
this.progressDialog = null;
}
this.progressDialog = ProgressDialog.show(context, "", "Chargement en cours, veuillez patienter");
}
public void hideProgressDialog() {
if(this.progressDialog != null) {
this.progressDialog.dismiss();
this.progressDialog = null;
}
}
Function :
public void startActivity(Context context, Class<? extends Activity> activityClass) {
try {
showProgressDialog(context);
Intent intent = new Intent(this, activityClass);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
hideProgressDialog();
}
catch(Throwable e) {
e.printStackTrace();
}
}
Example of a button click where this calls the function to show the spinner :
#Override
public void onClick(View view) {
if(view.getId() == R.id.changeBannerButton) {
getBaseApplication().startActivity(this, BannerListActivity.class);
}...
Call hideProgressDialog() in the onResume() method. This way, if the user presses the back button, the onResume() method gets called and immediately hides the progress dialog.
Well First off you should use the new DialogFragment class with FragmentManager. Because showdialog() is deprecated from API level 8
Next you should use showdialog and removedialog for adding and removing the dialog.
And you should use the onCreateDialog to handle the dialog and the operations. Like start a new thread to run do the job when you are displaying the progressdialog.
Try to load data in a seperate thread on start of activity. But before start of that process show the progress dialog. Now once the process is done use runOnUI to hide the progress dialog..
Indicate the user that data is being loading
http://www.helloandroid.com/tutorials/using-threads-and-progressdialog
and this:
Android - using runOnUiThread to do UI changes from a thread