22 posts in this topic

Posted

hey guys! i am having such trouble getting my head around services for android and I do not know why :/ its just not going in..

 

thats it really lol I have looked at them and I understand how they are set up in code structure ... but I dont know how to integrate a service?

 

lets say for example I had a chat client on my phone, I want that chat client to receive messages even when the screen isnt open, how would I go about that? (I have already programmed a chat client)..

 

I dont understand how my program and the service I am writing for it integrate together I am willing to practice with smaller bits of code to get used to it but all the examples I find rather then giving good clear English examples give 2 million pages of code and only explain the service, how am i meant to know how the service works if I dont know about the rest of their code lol?

 

currently reading SAMS teach your self java in 24 hours, while looking at official documentation and tutorials, just need someone use plain english please 

Share this post


Link to post
Share on other sites

Posted

I just recently wrote a TCP Client into a service as I was having problems with it disconnecting whenever I rotated the display.   Essentially there are two ways to do the service.  1) Application based, or 2) System based.  I have only done application based.   But what you do is think of the service like an object,  which is created, then you join it.

http://developer.android.com/reference/android/app/Service.html
 

I followed this, and made the local service.  I did the tutorial 100% and then made modifications to match what I was doing.  I then implemented a handler

http://robotoworks.com/2012/11/exploring-android-handlers/

 

to communicated from the service to my Activity (I use it to pass TCP Data I receive) so that I can fill in forms, make toasts, etc.

Make sure to set the service to STICKY.

For the record, I am a decent programmer, but doign services and java, and android for that matter is 100% new to me, and I was able to get and understand it relatively quickly.  There were a few things that stopped me up.  For example, you must explicity start the service, before binding otherwise it doesn't create an instance that can be rebound to.

Share this post


Link to post
Share on other sites

Posted

I just recently wrote a TCP Client into a service as I was having problems with it disconnecting whenever I rotated the display.   Essentially there are two ways to do the service.  1) Application based, or 2) System based.  I have only done application based.   But what you do is think of the service like an object,  which is created, then you join it.

http://developer.android.com/reference/android/app/Service.html
 

I followed this, and made the local service.  I did the tutorial 100% and then made modifications to match what I was doing.  I then implemented a handler

http://robotoworks.com/2012/11/exploring-android-handlers/

 

to communicated from the service to my Activity (I use it to pass TCP Data I receive) so that I can fill in forms, make toasts, etc.

Make sure to set the service to STICKY.

For the record, I am a decent programmer, but doign services and java, and android for that matter is 100% new to me, and I was able to get and understand it relatively quickly.  There were a few things that stopped me up.  For example, you must explicity start the service, before binding otherwise it doesn't create an instance that can be rebound to.

 

thanks I will look into this :P, I am rather a good programmer my self but I think the problem is with something as deep as services it becomes a problem for me as it uses a lot of technical language, being self taught and learning off examples means I lose the advantage of know the technical terms and reading about services?! my sky daddy there are alot of terms that I have no idea what they mean I barely know about objects :P 

When someone says object Im still like eerrrrrmm... oh yea I know what you mean lol... I use them ALL the time in both PHP, JAVA and android but I never talk about programming really, so have never needed to know terms. anyway once again thanks :P if you do find even more simply explinations pass them here xD once I do it once I will be ok...just need that once though 

Share this post


Link to post
Share on other sites

Posted

thanks I will look into this :p, I am rather a good programmer my self but I think the problem is with something as deep as services it becomes a problem for me as it uses a lot of technical language, being self taught and learning off examples means I lose the advantage of know the technical terms and reading about services?! my sky daddy there are alot of terms that I have no idea what they mean I barely know about objects :p 

When someone says object Im still like eerrrrrmm... oh yea I know what you mean lol... I use them ALL the time in both PHP, JAVA and android but I never talk about programming really, so have never needed to know terms. anyway once again thanks :p if you do find even more simply explinations pass them here xD once I do it once I will be ok...just need that once though 

I try and think of the technical terms in a real-world sense.   

ie) a Pointer... something that points to something else, and draws attention to that thing.
  an Object.... something.  ie) A ball is a physical object, it has properties, it is something
 a Service...  something that is done for me, that I don't have to worry about but something else is preforming it.

I am mostly self-taught the same way, and I know exactly what you mean by the technical side of things terminology wise.  Until recently I didn't know what it meant to "Serialize" something, but I knew the process of it.

Share this post


Link to post
Share on other sites

Posted

I try and think of the technical terms in a real-world sense.   

ie) a Pointer... something that points to something else, and draws attention to that thing.
  an Object.... something.  ie) A ball is a physical object, it has properties, it is something
 a Service...  something that is done for me, that I don't have to worry about but something else is preforming it.

I am mostly self-taught the same way, and I know exactly what you mean by the technical side of things terminology wise.  Until recently I didn't know what it meant to "Serialize" something, but I knew the process of it.

 

 

ha serialize people always telling me its the way? dont even know lol! ... out of the two methods you have shown me, what do you personally think would be best for a chat program ? possibly multi-threaded? 

Share this post


Link to post
Share on other sites

Posted

You could multi-thread, but the way activities work, if orientation changes or the activity is suspended the threads are suspended too.  By using a serice, they can remain active even if the activity is paused/closed/disconnected/etc.

The things I showed you work hand in hand and is how I implemented it into my project.

 

As for serializing, I've heard it's the way to go, especially for saving objects / sending objects.

Share this post


Link to post
Share on other sites

Posted

You could multi-thread, but the way activities work, if orientation changes or the activity is suspended the threads are suspended too.  By using a serice, they can remain active even if the activity is paused/closed/disconnected/etc.

The things I showed you work hand in hand and is how I implemented it into my project.

 

As for serializing, I've heard it's the way to go, especially for saving objects / sending objects.

 

havent got any samples have you? seeing as you have done what I need all i need to see is the interaction between them ?? :) ??

Share this post


Link to post
Share on other sites

Posted

havent got any samples have you? seeing as you have done what I need all i need to see is the interaction between them ?? :) ??


Not sure what you are after but here is my basic setup/connect code in the MainActivity file

 

    @Override
    protected void onStart() {
    	super.onStart();
    	
    	//Bind to the service
    	Intent intent = new Intent(curContext,TCPService.class);
    	startService(intent);
    	bindService(intent,mConnection,Context.BIND_AUTO_CREATE);
    	
    }
    
    @Override
    protected void onStop() {
    	super.onStop();
    	
    	//Unbind from the service
    	if (mBound) {
    		unbindService(mConnection);
    		
    		mBound = false;
    	}
    }
    
   
    
    //Defines callback for service binding, passed to bindService()
    private ServiceConnection mConnection = new ServiceConnection() {
    	    @Override
    	    public void onServiceConnected(ComponentName className, IBinder service){
    	    	//We are bound, so cast the binder to get the instance
    	    	LocalBinder binder = (LocalBinder) service;
    	    	mService = binder.getService();
    	    	mService.Setup(handler);
    	    	mBound = true;
    	    	
    	    	if (!mService.Connected) {
	    	        if (chkAutoConnect != null && chkAutoConnect.isChecked())
	    	        {
	    	        	btnConnect_Click();
	    	        }
    	    	}
    	    }
    	    
    	    @Override
    	    public void onServiceDisconnected(ComponentName arg0) {
    	    	mBound = false;
    	    }
    };
    

    
    private final Handler handler = new Handler() {
	    public void handleMessage(Message msg) {
	             
	    		parseData(msg.getData().getCharArray("data"));
	            //Log.e("Service",Integer.toString(aResponse)); 
	        }
    };

And this is my setup/TCP Connection in the Service

 

	public void Setup(Handler messageHandler)
	{
		handler = messageHandler;
	}


    public class TCPConnect extends AsyncTask<String,String,TCPClient> {


    	@Override 
    	protected TCPClient doInBackground(String... message)
    	{
    		mTCPClient = new TCPClient(new TCPClient.OnMessageReceived() {
    			
    			@Override
    			public void MessageReceived(String message) {	
    				publishProgress(message);
    			}
    		});
    		

    		mTCPClient.Connect(serverIP,serverPort);
    		  			
    		return null;
    	}

    	@Override
    	protected void onProgressUpdate(String... values) {
    	    super.onProgressUpdate(values);

    	    Message msgObj = handler.obtainMessage();
    		Bundle b = new Bundle();
    		b.putCharArray("data",values[0].toCharArray());
    		msgObj.setData(b);
    		handler.sendMessage(msgObj);
    		
    	}
    }

Setup() takes the handler so it knows where to send messages too.  The TCP data received shows making and sending the message.    As I say most of this is new so it is a mish-mash of tutorials modified to suit what I needed it to do.

Share this post


Link to post
Share on other sites

Posted

Not sure what you are after but here is my basic setup/connect code in the MainActivity file

 

And this is my setup/TCP Connection in the Service
 

 

 

ah ok, so does the service start on the start of the class? or are you manually starting the service within the thread? do not think i can see it actually being called, ALSO is this all in main activity ? and thn you are just calling the TCP service on start?

Share this post


Link to post
Share on other sites

Posted

ah ok, so does the service start on the start of the class? or are you manually starting the service within the thread? do not think i can see it actually being called, ALSO is this all in main activity ? and thn you are just calling the TCP service on start?

My TCP Thread/Class is inside my service.  In my MainActivity I tell it to start the service (runs the services Constructor, which I have as empty).  I then Bind to it, which allows me to directly interact with the instance of the service.  By having the service start as STICKY, then it will automatically return an instance of a pre-existing service and does not start it again.

I then call a function I wrote that is inside the service.  That function creates a new instance of the TCP Server class which has it's own threading.

So essentially it's like this

MainActivity -> Start Service -> Service Runs Constructor -> Starts as STICKY (So not to dispose itself)
MainActivity -> Bind to Service -> Service Runs OnBind (Returns instance of itself back to MainActivity)
MainActivity -> Runs Connect Function inside Instance of Service -> Service Starts TCP Class which has it's thread

That way my main activity can be doing whatever (stopped, paused, etc), but the service is still running, and able to pass messages back, make toasts, etc.

The Connect function is called in a different function (when user clicks connect).  And is done by doing mService.Connect(ip,port);   mService = my local instance of the service.

Share this post


Link to post
Share on other sites

Posted

My TCP Thread/Class is inside my service.  In my MainActivity I tell it to start the service (runs the services Constructor, which I have as empty).  I then Bind to it, which allows me to directly interact with the instance of the service.  By having the service start as STICKY, then it will automatically return an instance of a pre-existing service and does not start it again.

I then call a function I wrote that is inside the service.  That function creates a new instance of the TCP Server class which has it's own threading.

So essentially it's like this

MainActivity -> Start Service -> Service Runs Constructor -> Starts as STICKY (So not to dispose itself)
MainActivity -> Bind to Service -> Service Runs OnBind (Returns instance of itself back to MainActivity)
MainActivity -> Runs Connect Function inside Instance of Service -> Service Starts TCP Class which has it's thread

That way my main activity can be doing whatever (stopped, paused, etc), but the service is still running, and able to pass messages back, make toasts, etc.

The Connect function is called in a different function (when user clicks connect).  And is done by doing mService.Connect(ip,port);   mService = my local instance of the service.

lol im trying to play around with this at the moment, can you explain this line??  public class TCPConnect extends AsyncTask<String,String,TCPClient> {

thans for all your help btw!!! really appreciate it 

Share this post


Link to post
Share on other sites

Posted

My TCP Thread/Class is inside my service.  In my MainActivity I tell it to start the service (runs the services Constructor, which I have as empty).  I then Bind to it, which allows me to directly interact with the instance of the service.  By having the service start as STICKY, then it will automatically return an instance of a pre-existing service and does not start it again.

I then call a function I wrote that is inside the service.  That function creates a new instance of the TCP Server class which has it's own threading.

So essentially it's like this

MainActivity -> Start Service -> Service Runs Constructor -> Starts as STICKY (So not to dispose itself)
MainActivity -> Bind to Service -> Service Runs OnBind (Returns instance of itself back to MainActivity)
MainActivity -> Runs Connect Function inside Instance of Service -> Service Starts TCP Class which has it's thread

That way my main activity can be doing whatever (stopped, paused, etc), but the service is still running, and able to pass messages back, make toasts, etc.

The Connect function is called in a different function (when user clicks connect).  And is done by doing mService.Connect(ip,port);   mService = my local instance of the service.

lol im trying to play around with this at the moment, can you explain this line??  public class TCPConnect extends AsyncTask<String,String,TCPClient> {

thans for all your help btw!!! really appreciate it 

Share this post


Link to post
Share on other sites

Posted

My TCP Thread/Class is inside my service.  In my MainActivity I tell it to start the service (runs the services Constructor, which I have as empty).  I then Bind to it, which allows me to directly interact with the instance of the service.  By having the service start as STICKY, then it will automatically return an instance of a pre-existing service and does not start it again.

I then call a function I wrote that is inside the service.  That function creates a new instance of the TCP Server class which has it's own threading.

So essentially it's like this

MainActivity -> Start Service -> Service Runs Constructor -> Starts as STICKY (So not to dispose itself)
MainActivity -> Bind to Service -> Service Runs OnBind (Returns instance of itself back to MainActivity)
MainActivity -> Runs Connect Function inside Instance of Service -> Service Starts TCP Class which has it's thread

That way my main activity can be doing whatever (stopped, paused, etc), but the service is still running, and able to pass messages back, make toasts, etc.

The Connect function is called in a different function (when user clicks connect).  And is done by doing mService.Connect(ip,port);   mService = my local instance of the service.

lol im trying to play around with this at the moment, can you explain this line??  public class TCPConnect extends AsyncTask<String,String,TCPClient> {

thans for all your help btw!!! really appreciate it 


i am going crazy I am just staring at this code.

Share this post


Link to post
Share on other sites

Posted

I am going to pull an all nighter I will not let this crap defeat me ... once i understand it il kick my self for being a blind idiot, but i have to get this in there.

Share this post


Link to post
Share on other sites

Posted

I DID IT !!! well i kind of did it ... I made a service happen and I understand how it happened etc and why... now to play around with it and understand it more... 

package com.example.serviceexample;

import android.app.IntentService;
import android.content.Intent;
import android.widget.Toast;

public class MyIntentService extends IntentService {

	@Override
	protected void onHandleIntent(Intent arg0) {
		// TODO Auto-generated method stub
		Toast.makeText(this, "TESTING", Toast.LENGTH_LONG).show();
	}
	public MyIntentService() {
		super("MyIntentService");
	}

}

my service I know it is REALLY basic and cannot do anything! but its a foundation :) 

Share this post


Link to post
Share on other sites

Posted

lol im trying to play around with this at the moment, can you explain this line??  public class TCPConnect extends AsyncTask<String,String,TCPClient> {

It is a declaration of a class.  Basically my class is called TCPConnect which extends (uses) the AsynTask<> Class.  I am honestly not 100% sure what the stuff in the <>'s are for.  I assume they are parameters of some sort.  I just followed a tutorial online on how to make the Client.  I am sure when I wrote it (I never copy and paste tutorial code) that it made sense.

Basically my Service encases my TCPConnect class which runs an AsyncTask (a thread).  The service lets that task keep running even if my activity is closed.

Share this post


Link to post
Share on other sites

Posted

It is a declaration of a class.  Basically my class is called TCPConnect which extends (uses) the AsynTask<> Class.  I am honestly not 100% sure what the stuff in the <>'s are for.  I assume they are parameters of some sort.  I just followed a tutorial online on how to make the Client.  I am sure when I wrote it (I never copy and paste tutorial code) that it made sense.

Basically my Service encases my TCPConnect class which runs an AsyncTask (a thread).  The service lets that task keep running even if my activity is closed.

 




package com.example.serviceexample;


import com.example.serviceexample.MyIntentService.LocalBinder;

import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Toast;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;


public class MainActivity extends Activity {
	    MyIntentService mService;
	    boolean mBound = false;

	    @Override
	    protected void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.activity_main);
	      onStart();
	    }

	    @Override
	    protected void onStart() {
	        super.onStart();
	        // Bind to LocalService
	        Intent intent = new Intent(this, MyIntentService.class);
	        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
	    }

	    @Override
	    protected void onStop() {
	        super.onStop();
	        // Unbind from the service
	        if (mBound) {
	            unbindService(mConnection);
	            mBound = false;
	        }
	    }
	    private ServiceConnection mConnection = new ServiceConnection() {

	        @Override
	        public void onServiceConnected(ComponentName className,
	                IBinder service) {
	            
	            LocalBinder binder = (LocalBinder) service;
	            mService = binder.getService();
	            mBound = true;
	         
	        }

	        public void onServiceDisconnected(ComponentName arg0) {
	            mBound = false;
	        }
	    };
	
	    
	   
	    public void onServiceDisconnected(ComponentName arg0) {
	    	mBound = false;
	    }



}

above is mainActivity.class

 

this works and it turns my wifi on? but why is it not turning it back on when i turn it off... do i have to add a listener or ? what 

 

 

the below is MyIntentSerive.class file...

package com.example.serviceexample;


import java.util.Random;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;

public class MyIntentService extends Service {
	// Binder given to clients
    private final IBinder mBinder = new LocalBinder();
    // Random number generator
    
    WifiManager wifi;
    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */
    public class LocalBinder extends Binder {
        MyIntentService getService() {
            // Return this instance of LocalService so clients can call public methods
            return MyIntentService.this;
            
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
        Toast.makeText(this, "binding", Toast.LENGTH_SHORT).show();
    }

    /** method for clients */
    public void checkWi() {
    	wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
		boolean wion = wifi.isWifiEnabled();
		if (wion == false)
		{
			wifi.setWifiEnabled(true);
			Toast.makeText(this, "on......................", Toast.LENGTH_LONG).show();
		}
		
		
    }
}

Share this post


Link to post
Share on other sites

Posted


above is mainActivity.class

 

this works and it turns my wifi on? but why is it not turning it back on when i turn it off... do i have to add a listener or ? what 

 

 

the below is MyIntentSerive.class file..

 

 

not sure, however my assumption would be you need a timer, or some sort of thread that checks the wifi status every X seconds and re-enables it if it is off.

Share this post


Link to post
Share on other sites

Posted

not sure, however my assumption would be you need a timer, or some sort of thread that checks the wifi status every X seconds and re-enables it if it is off.

 

 

ok :) so does your TCP thread listen constantly to incoming messages? just wondering if it works the same :) trying to combine mine now (without objects lol) and its confusing me :P

Share this post


Link to post
Share on other sites

Posted

ok :) so does your TCP thread listen constantly to incoming messages? just wondering if it works the same :) trying to combine mine now (without objects lol) and its confusing me :p


I have the wifi set to never shut off.

Share this post


Link to post
Share on other sites

Posted

I have the wifi set to never shut off.

 

 

like i have said though I have started the service and got it working ... just need to now... combine it with my chat program some how :/ 

Share this post


Link to post
Share on other sites

Posted

like i have said though I have started the service and got it working ... just need to now... combine it with my chat program some how :/

Inside your service have your TCP Server/Client running.  It means making an object (a thread would work, though objects are easier), and starting its thread.

So like.. I have a TCP object that uses AsyncTask to run in it's own thread.  The service keeps the Async Task alive even when the activity isn't using it. 

 

 

Edit: I also misread your post, I thought you asked HOW I kept it running.  Yes, I have the listening loop happening in a thread so not to block the ui.  The thread runs inside the service.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0

  • Recently Browsing   0 members

    No registered users viewing this page.