How to execute method only when location of the device change? - java

I have method "NetAsync(view)" in my app which execute on button click event and send data to my database, what i want is that this method "NetAsync(view)" only execute when location of device change, let say after 5KM. Kindly help me out how to do this, i tried a lot of methods by googling but they are confusing.
At the moment method "NetAsync(view)" executes on buttonClick event.
move = (Button)findViewById(R.id.movebutton);
move.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
NetAsync(view);
}
}

This link maybe the answer:
Android - GPS Listener
you can add your NetAsync(View) in the listener:
#Override
onLocationChanged(...)
and more api docs, please find
Android LocationManager

Related

How can I change onClick to always active ? (Android Studio)

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

Having trouble understanding this line of code

If anyone wants to break down this code and explain it to me. I'd be thankful.
I run into an error on view(cannot resolve symbol), not sure if I'm supposed to replace that with a specific view ?
Btw, this is an onClick method.
"else if(view.getId()==R.id.Button9){}"
What I understand from this code is it says when "if" "view" whatever the viewid is goes in here ()?? == <--is related to R.id.button9
then run this block of code. Am i even close? Thanks.
A little backstory, I have created an ImageButton and when it's clicked, I'd like to to clear the screen. I've built on onclicklistener and implemented view.OnClickListener on my user public class.
CLEARCANVAS = (ImageButton) findViewById(R.id.button9);
CLEARCANVAS.setOnClickListener(this);
#Override
public void onClick(View v) {
if (view.getId()==R.id.button9);
}
Your View parameter is v, not view.
Change it to v and it will compile:
#Override
public void onClick(View v) {
//if (view.getId()==R.id.button9){
if (v.getId() == R.id.button9){
//handle button9 click
}
}
Another common way to do it is to define a separate click listener for each clickable element, for example:
clearCanvas = (ImageButton) findViewById(R.id.button9);
clearCanvas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Handle button9 click
}
});
If the error is related with class R, then you need to rebuild the project or else if its still not working for you, you will have to restart the IDE you are using. Basically if you are using Eclipse, I suggest to change to Android Studio as google has deprecated android support to eclipse. Cannot resolve symbol error basically means that the project does not have particular class reference or whatever you are trying to use.
It is like this.
You have 10 buttons from button1 to button10. Everything has an id stored in R.java file to uniquely identify it.
Suppose you want to perform a onClick event for button9. You create a generic onClick event for all the buttons.
#Override
public void onClick(View v) {
//now all the 10 buttons have the same onclick event.
}
Now to differentiate between which button was clicked, you need to use it's id.
#Override
public void onClick(View v) {
if (v.getId()==R.id.button9){
Toast.makeText(context, "Button 9 Clicked!", Toast.LENGTH_SHORT).show();
}
if (v.getId()==R.id.button8){
Toast.makeText(context, "Button 8 Clicked!", Toast.LENGTH_SHORT).show();
}
...
}
So, R.java is a link between your UI objects in the XML and the java code.
You'll need the R.java to identify each object from the UI.
This is automatically done. If you get an error saying cannot resolve R. You might want to re-build or clean your project.
you just need to change your view.getId() with the v.getId().
The view which is passed in the OnClick method is the view which is clicked, so It will check which Id is clicked.

Android working in background

this is my first question I got stucked in an app development..
I have developed an app. This app has a registration activity in the first stage, here the user's name, password and mobile number is collected and saved in the server. after that, the user's registration process is completed.
once this is done, the app will work to give daily horoscope predictions. This means the app will have to notify, or predict, daily. So after once the registrtion process is over the app should continue to run in the background. Also, when the user re-opens the app, it should not display the registration page, but the prediction page. I would also like a button that closes the app, but keeps it running in background.
How would I go about doing this?
Here is the code to my mainActivity,
public class MainActivity extends Activity
{
Button btn1,btn2;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
btn2 = (Button) findViewById (R.id.button2);
btn1 = (Button) findViewById (R.id.button1);
if(loginDataBaseAdapter.getUsercount() >= 50)
{
btn2.setVisibility(View.INVISIBLE);
}
else
{
btn2.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this,SignUpActivity.class);
startActivity(i);
}
});
}
btn1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Intent inte = new Intent(MainActivity.this,SignInActivity.class);
startActivity(inte);
}
});
}
#Override
protected void onDestroy()
{
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
finish();
}
}
1.Use Shared preference to set a flag once user has done a successful login. NEVER STORE USERNAME OR PASSWORD.
2.Create a Service which will run in Background for getting horoscope details.
3.Next time when user opens app, check the flag value from the Shared Preferences and display appropriate activity
Create a Service class which runs in the background. Access the horoscope details in the service class in a daily manner, which is up to your requirements. Don't forget to register your service in your Activity.
Also once the registration is successful save username and password in Sharedpreferences and each time application starts you can check if the data is available or not and skip the login page. If it's online you can further validate the username and password with the server.
Since you are writing a Service class you can close the application by clicking a button or something. But once you login makesure you finish() the login activity and start the prediction activity.
You will have to inherit from Thread Object. This will allow You to overwrite the run method where You can, for example, run an infinite loop depending on some passed arguments to the inherited thread class.
NOT UI threads ( and this is going to become one, as i understood) must not create and/or modify any ui elements. Therefore You must also create an interface, which will be implemented by the inherited thread class. You also will have to pass the thread's callback object as listener to Your thread class in order to invoke a method call in it, where itself You then can marshall thread execution back to ui thread. Basically this means, the thread runs in background and if some conditions occurr, it announces the main thread like an event, where You for Yourself can Do whatever You like.
But read You must, first: ( especially, how variable access among n threads should be ensured ):
Here for example:
Threading Example in Android

Mediation and CustomEventBanner java

I would like to create a CustomEventBanner but have some questions. Im not sure if I do the right things at the right place. Where should I add the Banner to my layout? Do I have to call every method of the CustomEventBannerListener? Which are those which are absolutly necessary? How do I know if there is no Ad to display (no anouncer)??
I actually can display Ad with admob but not using my CustomAd :(
Here is my code:
public class CustomAd implements CustomEventBanner, AdResponseHandler {
private CustomEventBannerListener bannerListener;
protected SASBannerView mBannerView;
#Override
public void requestBannerAd(final CustomEventBannerListener listener,
final Activity activity, String label, String serverParameter,
AdSize adSize, MediationAdRequest mediationAdRequest, Object extra) {
// Keep the custom event listener for use later.
this.bannerListener = listener;
// Determine the best ad format to use given the adSize. If the adSize
// isn't appropriate for any format, an ad will not fill.
// Create banner instance
mBannerView = new SASBannerView(activity);
// Set the listener to register for events.
this.mBannerView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
listener.onClick();
} catch (Throwable t) {
}
}
});
// Load the ad with the ad request giving an AdResponseHandler
mBannerView.loadAd(42295, "286177", 18008, true, "", this);
}
#Override
public void destroy() { // The destroy method gets called when the mediation
// framework refreshes
// and removes the custom event. Perform any necessary cleanup here.
if (this.mBannerView != null) {
this.mBannerView.onDestroy();
}
}
#Override
public void adLoadingCompleted(SASAdElement arg0) {
this.bannerListener.onReceivedAd(this.mBannerView);
}
#Override
public void adLoadingFailed(Exception arg0) {
this.bannerListener.onFailedToReceiveAd();
}
}
The code looks pretty good. Though your banner doesn't seem to be doing anything on click other than notifying onClick(). If you're banner ends up hitting an external web browser or the play store, you can also call onPresentScreen() and onLeaveApplication() in the onClickListener.
Note that this is just the Custom Event component of your app to implement the SAS network. Your main activity still needs to create an AdView (with a mediation ID set up to target your custom event) and load an ad into it.
Only the onReceivedAd and onFailedToReceiveAd are absolutely necessary for mediation to run. The others are useful so that your main AdView's AdListener can listen for these events.

Stopping and Play button for Audio (Android)

I have this problem, I have some audio I wish to play...
And I have two buttons for it, 'Play' and 'Stop'...
Problem is, after I press the stop button, and then press the Play button, nothing happens. -The stop button stops the song, but I want the Play button to play the song again (from the start) Here is my code:
final MediaPlayer mp = MediaPlayer.create(this, R.raw.megadeth);
And then the two public onclicks:
(For playing...)
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
button.setText("Playing!");
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
//
}
});
And for stopping the track...
final Button button2 = (Button) findViewById(R.id.cancel);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp.stop();
mp.reset();
}
});
Can anyone see the problem with this? If so could you please fix it... (For suggest)
Thanks alot...
James
You need to call prepare() or preparAsync() before start().
See the API for details (look at the state diagram).
There is a bug in the Android documentation, in this page it is said that you could stop() a "raw resource" mediaplayer, and then replay it just by calling reset() and prepare() before calling start() again. This doesn't work, as you have noticed.
The problem is that reset() clears the audio source and returns to the initial state, so you must set again the data source. Unfortunatelly you can't set a "raw resource" data source, because there is no API for this besides create().
I don't know a clean way of solving this issue. stealthcopter's way works great, but is a pain for your design, as you need the context for each start() call :( And involves destroying and creating a complex object, which has a price for realtime apps like games...
Another way that ensures that context will only be needed for the create() call, is to stop the media player this way:
stop()
prepare()
but if you call start() now, it won't restart from the beginning. You could call seekTo(0), but the sound will have a bit of noise from the previous play position.
I keep investigating on this. There must be a clean and efficient way of stopping and restarting the mediaplayer when created on a raw resource...
This is what I have working in my program. It releases the media player each time as I use different sounds each time it is called, however it should work as a work-around for your usage.
Creation:
public MediaPlayer mp=null;
Starting:
if (mp!=null){
mp.reset();
mp.release();
}
mp = MediaPlayer.create(test.this, soundResource);
mp.start();
Stopping:
mp.stop();
Also note that you do not require to use prepare because the create method already calls prepare for you (API REF).

Categories