Other way for getActivity() use in service Android java

10,112

A Service is a separate component from an Activity and thus you cannot get a reference to it using getActivity(). Services are designed for doing work not visible to the user, including (but not limited to) background work on a separate thread from the UI thread. Services are more robust and offer more control over what work is being performed that is not visible to the user. They do not require an Activity to run.

An AsyncTask is a simple way of doing work from inside an Activity on a separate Thread from the UI thread.

Basically, you dont want or need an AsyncTask in a Service.

Instead, in your Service you should either spawn a Thread, or use IntentService which will handle creating a worker Thread for you. Then when you are finished, send an intent back to the Activity either by starting it or using a LocalBroadcast

Alternatively, you can tie a Service to an Activity and provide methods that the Service and Activity can call directly on each other through an IBinder interface. These are called bound services and will only be alive as long as the Activity is alive.

Try an IntentService

I think your best bet is to try learning how to use an IntentService

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

Share:
10,112
cchua
Author by

cchua

Updated on June 04, 2022

Comments

  • cchua
    cchua almost 2 years

    In my PollFragment.java that able to call new PollTask((MainActivity)getActivity()).execute((Void)null);

    And in my PollTask.java

    public PollTask(MainActivity activity){
            super(activity);
            TerminalCfg terminalCfg = Global.getTerminalCfg();
            terminalId = terminalCfg.getTerminalId();
            retailerAcc = terminalCfg.getRetailerAcc();
            internalId = APIUtil.getInternalId(activity);
            username = APIUtil.getUsername(activity);
        }
    

    And now I want to call the new PollTask((MainActivity)getActivity()).execute((Void)null); in MyBackgroundService with extends Service like below :

    public int onStartCommand(Intent intent, int flags, int startId) {
            Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
            new PollTask((MainActivity)getActivity()).execute((Void)null);
            // For each start request, send a message to start a job and deliver the
            // start ID so we know which request we're stopping when we finish the job
            Message msg = mServiceHandler.obtainMessage();
            msg.arg1 = startId;
            mServiceHandler.sendMessage(msg);
    
            // If we get killed, after returning from here, restart
            return START_STICKY;
        }
    

    Is there any other way to replace the getActivity() to call the method?

  • cchua
    cchua over 10 years
    Do you mind to have source code for me to more understand of it.