In my application I decided to make a server and client through Sockets (just testing my idea for now).
So I made two AsyncTasks (for the server and client) an on my onCreate (depending on user action - as I said I'm just testing, for now just with buttons):
new createServer().execute();
or
new connectClient().execute();
Question is, everything works good, but the app where I want to implement my idea has many activities, so the app that is serving the data, when leave the activity where the createServer Async Task is, the client (obviously) loses the connection.
Is there a way to maintain the server running "all time", and allow the user (with the "server app") to navigate through the app without affecting the connected clients? Because even if everytime I leave an activity I create the Server, the clients will lose connection anyway.
Really appreciate any suggestion.
EDIT: For the purposes of my test application, I need the system to be working only in foreground, no background, so no need of service creation.
Your problem is with correctly managing the lifetime of your server. First you'll have to decide what you want that lifetime to be. Clearly you've figured out that you want it to be broader than just the activity level, but do you want it to run in the background or only when your app is in the foreground? If it is only when in the foreground, you can get away with not creating a service, but instead keeping a reference to a component from your application object. However, if you want to keep your server running even when your app is in the background you do need a Service.
Update:
Here's an example of what I meant by "keeping a reference to a component from your application object":
Create a custom Application class.
Add a field to hold a reference to your server AsyncTask
private AsyncTask mServerTask;
Add a method to it to start your server AsyncTask
public void startServer() {
mServerTask = new createServer();
mServerTask.execute();
}
Probably add another method to stop your server
To start your server from an activity you can now do something like:
CustomApplication app = (CustomApplication) getApplication();
app.startServer();
Of course you'll want to do more to properly manage the server like making sure you don't start it twice, etc. and you might decide to use threads instead of AsyncTasks but this should give you an idea of how you can have an object with a lifetime beyond that of an activity.
Related
Hey guys:) I'm currently working on an android project, where I want to realize a chat function. I know there are several tutorials which describe a chat app but I want to do it myself with my own Server.
In my MainActivity I start a self written updater in a new thread (bc. of network-operations can only be done outside the UI thread), which permanently checks, if the chat-protocol, which is stored on my server (RaspberryPi), has new messages from other users. If there are new messages, the Updater downloads it and stores it in a string. This works fine!
Now, when the updater receives a new message, I want to update the ListView in my Chat-Activity with the new message. This process should work at any time and update my ListView permanently (not with a refresh button or sth. like that).
My question is: how do i realize this the smoothest way - a strategy, not necessarily code. One idea, which works but feels a bit random, is to write the received messages in a shared preferences-file and load it in the chat-acivity via an infinite loop in the chat activity.
Is there a possibility to write the received messages directly in the ListView at any time from the thread with the updater which was startet in the MainActivity.
If needed i could upload the current code but i want to do it directly and not with an infinite loop.
Thanks for reading and maybe even for the help :)
You may want to save the received messages in SQLite database, and inside the activity, you can poll the database (suppose for every 5 seconds) and stop polling after the activity is destroyed.
Another way would be to use the static references of the views and update them from a different class. Even you are trying to update them from inside a background thread, you can update the UI using view.post()
SomeActivity.textView.post(new Runnable(){
#Override
public void run(){
SomeActivity.textView.setText("sth");
}
});
Ive run into a problem with Android not letting you pass objects around Activities with intent' putExtra. So, if my application needs to make any number of network requests, it would make sense to keep futures in an object and get results as they become needed and block background threads if necessary.
How can you pass an object from one Activity to another without it being static or serialization?
I am developing a testing application on an Architecture which is based on Producer-Consumer structure. I have an producer-consumer* problem, especially if an producer callback mechanism is utilized in android service i.e. consumer. Consumers are not supposed to hold the call for more than the minimum necessary time to have the info handed over. Since the producer’s callbacks are supposed to run in a different thread than the consumer’s one.
In my specific case within the callback of Producer only a reference moving of the passed object should be done and release the control right away. The object has to be consumed in the consumer thread. Currently I have been calling a method which only gets data coming within callback and processes that data and return it via Intent baack to the Android Activity.
Now, Android intents are well known to be resource consuming entities which are not meant (and not supposed) to be used to transfer data streams.
Within the Test app, one intent per callback is generated. Those overflow the whole system. For example, at 25% of load a traffic of about a thousand Android intents per seconds are triggered.
I want a way which doesn't include Android Intents(without any Thrid party jar) using which I can send data back to my android activity or route on host machine at super high rate so that my producer call back doesn't get crashed.
Use a socket connection between the Service and the Activity for streaming data. Intent is the wrong technique.
I have a startingActivity on Google-glass
I want to run it sometimes silently,
meaning it will run, communicate with the server,
get and send data - but the user won't see the app.
The user will see a static card from time to time,
but basically can be in a context of another app.
my tries:
I have thought to create a service instead of my
startingActivity,but there are too many things that relays on the main UI views
If I comment out the setContentView(), all my code that refers
view.findViewById() will fail. no? and besides the user will see a
black screen instead of silent run which i desire.
any other solution for silent run, but yet running the
startingActivity fully?
I have a small Android app that I have been working on that logs GPS data to my SD card in a GPX file. I currently have a main Activity that starts a Service to do all the background work. The service is kept in the foreground in the notification bar to make it the least likely thing to be killed by the OS. Currently I am requesting location updates from the service at the maximum frequency to get the most accurate route. The problem I am having is my User Interface is acting slow/strange. Correct me if I am wrong, but what I have concluded is that I have too much going on in the main thread of the app. My next thought is to try and move the service performing the acquiring and logging of data to a separate thread. I am new to Java/Android so the whole topic of interacting with separate threads is hard for me to wrap my head around. Initially in research I came across IntentServices, which are supposed to make threading easier, but from what I read these don’t seem to mix well with the Android location package because they don’t run long enough. I feel like I am running in circles with internet searches on this topic. I desperately need some guidance on how to achieve the following features for my programs service:
Separate thread from Main Thread
Fetching and storing of data must be the least likely thing to be killed by the OS and run indefinitely once started (don’t worry about battery I will have the device plugged in to power while running the app)
Eventually I will need the ability to interact with the User Interface
Thanks for any help you can offer!
this is a common problem that i have accomplished a lot on
in the launcher or main() ( what Android is calling an Activity ) you do as little as possible ( which amounts to saving the the refs they give you and maybe setting a few other things as long as you are there ) and do ^not^ drop in to a long-running activity
A Service is exactly what you need but instead of trying to pump it into a "hold on to it" state what you do is implement checks for nulls and handle as needed -- trying to "fix" a machine to make it run the way you want here actually involves rescinding you hold on the main thread and letting it go as fast as consistent with the Applicaton's general constraints.
To do this you can simply write a Service - reading everything available - then extend that service and implement Runnable then you run the constructor on that code from the Activity Constructor and do new Thead(yourClass).start(); in the onCreate() checking for Thread.isRunning() before starting it again ...
Service will have an onCompletion() call in it somewhere - it will go through an interface
All this is done in Android in something like start activity for result then you just to the UI stuff in that call or sorta figure out a way for the GUI to get called somehow at some time then check to see if Service is done an so report in the gui