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
Related
I've implemented something similar to Android notification of screen off/on, but it's not working the way it should. All I want to do is stop music when the screen is turned off. I created a screen action class like this
public class ScreenAction extends BroadcastReceiver {
public static boolean wasScreenOn = true;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// DO WHATEVER YOU NEED TO DO HERE
wasScreenOn = false;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// AND DO WHATEVER YOU NEED TO DO HERE
wasScreenOn = true;
}
}
}
Then, in my main activities on create I have this
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenAction();
registerReceiver(mReceiver, filter);
In my main activities onPause, I have something like this:
public void onPause() {
super.onPause();
if (ScreenAction.wasScreenOn) {
final MediaPlayer mp = MediaPlayer.create(this, R.raw.pcmouseclick1);
mp.setVolume(.1f, .1f);
mp.start();
if (buttonState) {
mServ.reduceVolume();
}
}
}
I found this from an online source, but I am having issues. It seems that the screen state is always set as true, and I'm not sure how to change this.
How do I utilize this ScreenAction class to turn off music in on Pause ONLY when the user has locked the screen? I feel like I am missing something in the onPause because in onCreate I link to the class.
#Override
protected void onPause() {
// when the screen is about to turn off
// or when user is switching to another application
super.onPause();
}
#Override
protected void onResume() {
// only when screen turns on
// or when user returns to application
super.onResume();
}
Here you can see the entire lifecycle of an Activity in android:
Activity Lifecycle
Maybe you could also start and stop your music directly from the receiver:
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// Pause music player
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// Resume music player
}
}
You're checking ScreenAction.wasScreenOn in onPause, but that's happening before the BroadcastReceiver is called to notify you that the screen is being turned off. So at that point, ScreenAction.wasScreenOn is still true, and then it's set to false, but onPause has already run, so your music never gets paused.
To solve this, you should take the action directly in response to the screen turning off in the BroadcastReceiver. If you need to interact with your UI, consider a solution like LiveData as an abstraction so that you're not reliant on your Activity being paused at the exact moment the screen is turned off (consider also that the onPause solution wouldn't work if your Activity weren't currently visible).
I need to complete three task in one button click. its look like on button click called SaveQuote
1) Hide Adview
2) Make Screenshot of Layout and Save it
3) Show Adview
Now I have implemented method for do above three task in my java as like below
else if(menuItem.getItemId() == R.id.save_image) {
adView.setVisibility(View.GONE);
saveQuote();
adView.setVisibility(View.VISIBLE);
But I am facing issue that ad always staying visible. If I use on ViewGone method and saveQuote method than its working fine, but if I add VISIBLE method than its not hiding my adview.
Note : I am not getting any error for same. I just need to know how can I achieve above three task via one button click
My saveQuote method is like below
private void saveQuote(){
String id=getQuote(mItemIndx).get(KEY_ID);
View v1=null;
List<Fragment> activeFragments=getSupportFragmentManager().getFragments();
for(Fragment fragment:activeFragments){
QuoteCard cardFrag=(QuoteCard)fragment;
if(cardFrag!=null&&cardFrag.mId.equals(id)){
v1=cardFrag.getCardView();
}
}
TextView textView = (TextView)v1.findViewById(R.id.textAuthorSign);
textView.setVisibility(TextView.VISIBLE);
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
ImageLoader.getInstance().saveQuoteImage(bitmap);
Snackbar.make(v1,"Quote Saved",Snackbar.LENGTH_SHORT).show();
adView.setVisibility(View.VISIBLE);
}
I am getting error like below if set VISIBLE method on end of saveQuote
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.ads.NativeExpressAdView.setVisibility(int)' on a null object reference
Thanks
You can do something like this.
adView.setVisibility(View.GONE);
saveQuote();
now in your saveQuote() method after all your logic is set.. add last line..
adView.setVisibility(View.VISIBLE); make note that your adView should be defined globally and you have initialized your adVIew.
You should review "Handle,Looper,Message"
adView.setVisibility(View.GONE);
saveQuote();
adView.post(runable)
Runnable runable=new Runnable(){
#Override
public void run(){
adView.setVisibility(View.VISIBLE);
}
}
Declare as global
final Handler handler = new Handler();
Change your code like this
else if(menuItem.getItemId() == R.id.save_image) {
adView.setVisibility(View.GONE);
saveQuote();
handler.postDelayed(new Runnable()
{ #Override public void run() {
adView.setVisibility(View.VISIBLE); } }, 5000);
}
Here the delay is 5 s reduce the delay if don't need that much.
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
I want to play an audio file in the background of my app. Easy enough. I want the music to persist and NOT stop or pause while switching between activities in my app. Also fairly easy and accomplished simply by doing this in the onCreate method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
mp = MediaPlayer.create(MainActivity.this, R.raw.lostmexicancity);
mp.setLooping(true);
mp.start();
}
The problem? Getting the music to stop when I press the HOME button.
Killing the sound when the user presses the back button seems easy. Here's what I have for that and works great:
public void onPause() {
if(this.isFinishing()){ //BACK was pressed from this activity
mp.stop();
}
super.onPause(); }
Not complicated, but this does not catch presses of the HOME button. If the Home button is pressed, the music keeps playing even while the user no longer sees my app.
I have seen answers that involve setting permission in the manifest to Get Tasks which I shouldn't have to do and appears dangerous to users. Besides that, the solution didn't even work. I've seen solutions that involve using a service, but none of those work either because the home button STILL plays the music just like before because there doesn't seem to be a way to catch it and it doesn't 'finish' the app (not to mention that every time someone suggest using a service for this task multiple people come in and state that this is not a proper use for services)
It seems the only way to kill the music when the Home button is pressed is to use a non-conditional stop() within onPause, but that's no good because that's called when I swap activities with intents, causing the music to end between activities which is no good.
I have trouble imagining that such a common function like background music is this hard, but I've seen post after post with the same issue as me and no proper answers other than ones that would kill the music between activities within the app.
How do all the other apps on the Google play store accomplish this and yet there appears to be no clear answer online? I could just stop and start the music with each onPause(), but that would cause unprofessional gaps in audio not to mention it would start the background audio from the beginning over and over again which is unacceptable.
I'm a bit new to Android Programming (few months) and today, I faced the same problem you did (maybe you still do?)
I made it work as the following :
Lets say I have MainActivity, and in MainActivity I have Btn2 which leads to SecondActivity, and Btn3 which leads to ThirdActivity.
I declared at the beginning of MainActivity :
public static boolean shouldPlay = false;
I then implemented my onStop() method :
public void onStop() {
super.onStop();
if (!shouldPlay) { // it won't pause music if shouldPlay is true
player.pause();
player = null;
}
}
If the boolean shouldPlay is set to true, then my onStop() won't be called entirely and my music won't turn off. I then have to decide when I set it to true. When I switch from MainActivity to SecondActivity, I do it through an Intent and that's when I'll set shouldPlay to true :
Button Btn2 = (Button) findViewById(R.id.Btn2);
Btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
shouldPlay = true;
startActivity(intent);
}
});
And the same is done for Btn3.
Now, the last thing we want to be looking for is that if I was to go back to MainActivity after visiting SecondActivity or ThirdActivity, shouldPlay would then have been set to true. The first thing I tried was to set it to false as soon as Second and ThirdActivity are called (in their onCreate()) but it want to work, maybe because the onStop() from Main and onCreate() from others are called simultaneously (frankly I don't really get life cycle for now).
What worked is simply to set shouldPlay to false every time we launch onCreate() of Main :
shouldPlay = false;
This works properly for me.
Let me know if it does for you,
Cheers,
bRo.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_HOME){
Log.d("Jorgesys", "Home button pressed!!!");
}
return super.onKeyDown(keyCode, event);
}
but hey! This no longer works as of 4.0 + , Read this: Capture Home Key Event
Try with Back button:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK ) {
Log.d("Jorgesys", "Back button pressed!!!");
}
return super.onKeyDown(keyCode, event);
}
To stop the media player, you are using the method:
isFinishing(): if the activity is finishing, returns true; else
returns false, but you are only pausing the activity not finishing the
activity.
public void onPause() {
if(this.isFinishing()){ //INCORRECT, Here you are pausing you activity not finishing.
mp.stop();
}
super.onPause();
}
so change to:
public void onPause() {
if(mp.isPlaying())
{
mp.stop();
}
super.onPause();
}
When your activity is on pause, evaluates if your MediaPlayer is playing, if this is true then stops the audio.
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