Trying to keep an xmpp connection alive using a service in android
public class XMPPService extends Service {
XMPPTCPConnection connection;
String USERNAME;
String PASSWORD;
public XMPPService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
onHandleIntent();
return START_STICKY;
}
private void onHandleIntent() {
connection = XMPPClient.getConnection();
connection.addConnectionListener(
new AbstractConnectionListener() {
public void connectionClosed() {
Log.i("connection", "closed");
}
public void connectionClosedOnError(Exception e) {
Log.i("connection", "closed on error");
}
public void reconnectionFailed(Exception e) {
Log.i("reconnection", "failed");
}
public void reconnectionSuccessful() {
if (connection.isAuthenticated()) {
Log.i("isauthenticauted : ", String.valueOf(connection.isAuthenticated()));
Log.i("reconnection", "succesful");
} else {
try {
connection.login(USERNAME, PASSWORD);
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.i("reconnection", "succesful");
}
}
public void reconnectingIn(int seconds) {
Log.i("reconnectingIn", String.valueOf(seconds));
}
}
);
}
#Override
public void onCreate() {
Log.i("service", "created");
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
My service restarts when I kill my app. Why is this happening? When I restart it gives me an exception NetworkOnMainThreadException at connection = XMPPClient.getConnection();
I don't want my service to restart when I kill my app.
The START_STICKY flag causes your service to auto-restart when it's destroyed. Your onstartCommand should return START_NOT_STICKY instead of START_STICKY.
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
onHandleIntent();
return START_NOT_STICKY;
}
Make use of START_NOT_STICKY in the onStartCommand(Intent, int, int) function of your service.
example:
public static final int START_NOT_STICKY http://developer.android.com/reference/android/app/Service.html
Related
i have a problem in my service, the service is runnig from MainActivity (i am doing test) and extends of service.
i want to use the service from foreground and background (when the app is closed) and i already have my first problem:
my service(have a counter that is displayed by LOG) is restarting when i close the app.
also i want to be able to use the service with the open app and close app, in other words to use both the Service Started and Link Service
public class MyService extends Service {
private Thread backgroundThread;
private boolean isRunning;
public MyService() {
Log.e("MyService","constructor");
}
#Override
public void onCreate() {
super.onCreate();
isRunning = false;
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
Log.e("onStartCommand","Servicio Llamado");
if (!this.isRunning) {
Log.e("onStartCommand","hilo iniciandose");
this.backgroundThread = new Thread(myTask);
runTask();
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("onDestroy","servicio destuido");
}
private void runTask(){
this.isRunning = true;
this.backgroundThread.start();
}
private Runnable myTask = new Runnable() {
public void run() {
Log.e("myTask","hilo iniciado");
int i = 0;
do{
pauseService();
Log.e("myTask","hilo contador: "+i);
//Toast.makeText(getApplicationContext(),"CONTADOR = "+j, Toast.LENGTH_SHORT).show(); //no working :(
i++;
}while (i<10);
/*
//linea de detencion del servicio
//stopSelf();
isRunning=false;
backgroundThread.interrupt();
//backgroundThread = new Thread(myTask);
*/
Log.e("myTask","hilo cerrado");
}
};
private void pauseService(){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
In main Activity
Intent intent = new Intent(MainActivity.this,MyService.class);
intent.putExtra("iteraciones",10);
startService(intent);
why because the service restarts when I close the application and how can I avoid it?
I tried to start socket connection and maintain it in a service. The service work well, but i cant connect to the my socket. Is it my code wrong or there some other way to do it?
This is my code
public class SocketService extends Service {
private Socket mSocket;
{
try {
mSocket = IO.socket("http://192.91.25.99:3000");
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mSocket.connect();
mSocket.on("message", handleIncomingMessages);
Toast.makeText(getApplicationContext(),"Start Service",Toast.LENGTH_LONG).show();
return Service.START_STICKY;
}
private Emitter.Listener handleIncomingMessages = new Emitter.Listener(){
#Override
public void call(final Object... args){
System.out.println(args[0].toString());
Toast.makeText(getApplicationContext(),"LALALALA",Toast.LENGTH_LONG).show();
}
};
}
Thanks in advance
I am working on a Chat messenger.I have used socket.io-client library.I have created a service that will instantiate Socket class.
SocketService.java
public class SocketService extends Service {
public static Socket mSocket;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
String data = intent.getStringExtra("Socket");
Log.e("intent data", data);
Log.e("Service", "Called");
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onCreate() {
super.onCreate();
Log.e("Service", "created");
try {
mSocket = IO.socket(Constants.CHAT_SERVER_URL);
Log.e("ValueSocket", String.valueOf(mSocket));
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
I am starting the service in SplashActivity.java.I have to pass Socket instance i.e. mSocket to Activity SplashActivity.java .How can i achieve this in android?Please help .
I am creating bound service for socket connection.Which means it is creating a long polling connection and listens my server.If user closes the app in task manager my service is killing i have no problem with this.But when user presses the back button I am calling activity.finish() method for close app.But with this method my service doesn't kill,it is still connected to socket server.
Is this normal ? And Could be this drain the battery ?
My service:
public class SocketService extends Service {
//you need constants to tell servise and activity what you are sending a message for
public static final int REGISTER_CHAT_ACTIVITY = 1;
public static final int MESSAGE_RECEIVED = 2;
final Messenger mMessenger = new Messenger(new IncomingHandler());
Messenger chat;
private Socket socket;
#Override
public void onCreate() {
try {
socket = IO.socket("ip");
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
}
}).on("connected", new Emitter.Listener() {
#Override
public void call(Object... args) {
}
}).on("message", new Emitter.Listener() {
#Override
public void call(Object... args) {
try {
chat.send(android.os.Message.obtain(null, MESSAGE_RECEIVED, args[0]));
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
//and add all the other on listeners here
socket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (socket != null) {
socket.disconnect();
socket.connect();
} else {
try {
socket = IO.socket("ip");
socket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
class IncomingHandler extends Handler {
#Override
public void handleMessage(android.os.Message msg) {
switch(msg.what){
case REGISTER_CHAT_ACTIVITY:
chat = msg.replyTo;
break;
}
}
}
public class LocalBinder extends Binder {
SocketService getService() {
return SocketService.this;
}
}
}
I had something similar a while ago i solved the issue by using shared preferences.(Note: I dont think it's the best answer but it solved my problem)
I saved in preferences a boolean to register when i dont need the service anymore but lost reference of it.
public class YourService extends Service {
private YourService serv;
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
serv = this;
Then Somehwere on your code that the service does frequently.
if(!sharedPref.getBoolean("TurnOffService", false)){
serv.stopSelf();
}
Hope it helps.
I started my service properly, its working well. I write condition that if service is already running then it don't start service again. condition returns true values which shows that service is running. But whenever I force stop my application, or if any exception occurred, my service stops loading data at background and till showing that service is running. That's why service is not re-started.
Intent that I used to start service from activity :
this.startService(new Intent(MainMenu1.this, MovieService.class));
And My service class is :
public class MovieService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TBD
Log.i("Movie Service : "," Created2");
new MovieDownloaderTask().execute();
return Service.START_FLAG_REDELIVERY;
//return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
Log.i("Movie Service : "," Created");
}
#Override
public void onDestroy() {
Log.d("Movie Service","onDestroy was Called!");
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startid) {
Log.i("Movie Service : "," Started");
}
public class MovieDownloaderTask extends AsyncTask<Void, Void, Integer>
{
#Override
protected Integer doInBackground(Void... params) {
Log.i("Movie Service"," : Started2");
//Moviejson.createDB();
try
{
Moviejson.insert_Movie_Data();
}
catch(Exception e)
{
Log.e("Exception > ", "i m in doInBackground. Trying to stop Movie service.");
MovieService.this.stopSelf();
e.printStackTrace();
}
return 1;
}
#Override
protected void onPostExecute(Integer result) {
if (result == 1) {
if(MainMenu1.Movies_new_time==null)
{
MainMenu1.Movies_new_time=MainMenu1.sp.getMovies_Old_Date();
}
else
{
MainMenu1.sp.setMovies_Current_Date(MainMenu1.Movies_new_time);
}
MainMenu1.sp.setMovies_Current_Date(MainMenu1.Movies_new_time);
Log.i("Movie Date:", " : "+MainMenu1.Movies_new_time);
MovieService.this.stopSelf();
Log.i("Movie Service"," : Stoped");
super.onPostExecute(result);
}
}
}
}
In your onStartCommand(), replace
return Service.START_FLAG_REDELIVERY;
with
return Service.START_REDELIVER_INTENT