Get a link to work from the service

I need to get a link to the main activity from the service.

This is my design:

MainActivity.java

public class MainActivity extends Activity{
private Intent myIntent;
onCreate(){
 myIntent=new Intent(MainActivity.this, MyService.class);

 btnStart.setOnClickListener(new OnClickListener(){
  public void onClick(View V){
   startService(myIntent);
   });
}}

MyService.java

class MyService extends Service{

 public IBinder onBind(Intent intent) {
  return null;
 }

 onCreate(){
 //Here I need to have a MainActivity reference
 //to pass it to another object
 }
}

How can i do this?

[EDIT]

Thanks everyone for the answers! This application is a web server that currently only works with streams, and I want to use the service instead so that it also works in the background. The problem is that I have a class that is responsible for getting the page from resources, and for this operation I need to use this method:

InputStream iS =myActivity.getAssets().open("www/"+filename); 

At the moment, my project has only one Activity and no services, so I can transfer the main link to the Activity directly from myself:

WebServer ws= new DroidWebServer(8080,this);

So, to make this application work with the service, what should I change in my design?

+7
4

, . . Activity - , . , , Activity onDestroy(). , (, ). , , onDestroy(), , , .

. , . , .


UPDATE

, Activity. ( ApplicationContext, Activity , ).

, , WebService:

class WebService 
{   
     private final Context mContext;
     public WebService(Context ctx) 
     {
        //The only context that is safe to keep without tracking its lifetime
        //is application context. Activity context and Service context can expire
        //and we do not want to keep reference to them and prevent 
        //GC from recycling the memory.
        mContext = ctx.getApplicationContext(); 
     }

     public void someFunc(String filename) throws IOException 
     {
         InputStream iS = mContext.getAssets().open("www/"+filename); 
     }
}

WebService Service ( ) Activity ( , , - ).

Service:

class MyService extends Service
{
    WebService mWs;
    @Override
    public void onCreate()
    {
        super.onCreate();
        mWs = new WebService(this);

       //you now can call mWs.someFunc() in separate thread to load data from assets.
    }

    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }
}
+8

AIDL , apks.

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

public class LocalBinder extends Binder {
        LocalService getService() {
            return LocalService.this;
        }
    }
+2

inazaruk. Activity : AIDL ( ), Messenger, BroadcastReicever .. Messenger AIDL, . :

http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/MessengerService.html

0

All Articles