Search code examples
androidservice

how to cal the activity method from the service


How to call a method at the time From the service to activity. I want to cal only particular method From the service .am using timer function and handler.

In my Activity the method name is savedata(), i want to cal this function

service

public class MyService extends Service 
{
    @Override
    public IBinder onBind(Intent intent) 
    {
        return null;
    }

    @Override
    public void onCreate() 
    {
        Log.d(TAG, "onCreate");
    }

    @Override
    public void onDestroy() 
    {
        Log.d(TAG, "onDestroy");
    }

    public void onStart(Intent intent, int startid) 
    {
        Timer mTimer = new Timer(user);
        mTimer.scheduleAtFixedRate(new mainTask(), 5000,60000);//1 hour=3600 s

    }

    private class mainTask extends TimerTask 
    { 
        public void run() 
        {
            toastHandler.sendEmptyMessage(0);
        }
    }  


    private final Handler toastHandler = new Handler() 
    {
        public void handleMessage(Message msg) 
        {
                Intent myIntent = new Intent(getBaseContext(),StorageHelper.class);
                myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(myIntent);//here i start the activity but i need to acces the particular method only.

        }
    };    

 }

update

Activity

public class StorageHelper extends Activity
{
    final DBAdapter1 database=new DBAdapter1(this);

MessageCount objmsgCount=new MessageCount();
String msgCount;
int count;
String []tokens=null;
String notify=null;
int userid=71; 


 public  String savedata()
    {
        msgCount=objmsgCount.getMessageCount();
        {
            try {
                database.open();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            }
                    long id=database.insert(71,4,"yes"); 
                    database.close();

        return "success";
    }
}

Solution

  • Its a good question, probably been asked many times before but one that stumped me to begin with.

    You have several options, the easiest of which is to register a listener with your activity, but this would require you to implement onBind(Intent) so you can connect from the activity to the service so you can register the listener.

    The following example shows you how to do this, once you have registered the activity as a listener with setServiceClient(ExampleServiceClient) the service can then invoke the method exampleServiceClientMethod() on the activity.

    You will notice I use a WeakReference when registering the client, always make sure you check to see you still have the reference when invoking any methods you add to ExampleServiceClient.

    public class ExampleService extends Service {
    
        public interface ExampleServiceClient {
            void exampleServiceClientMethod();
        }
    
        private WeakReference<ExampleServiceClient> mClient;
    
        public void setServiceClient(ExampleServiceClient client) {
            if(client == null) {
                mClient = null;
                return;
            }
    
            mClient = new WeakReference<ExampleServiceClient>(client);
        }
    
        public class ExampleBinder extends Binder {
            ExampleService getService() {
                return ExampleService.this;
            }
        }
    
        private IBinder mBinder = new ExampleBinder();
    
        @Override
        public IBinder onBind(Intent intent) {
            return mBinder;
        }
    }
    

    Your activity:

    public class ExampleServiceActivity extends Activity implements ExampleServiceClient {
    
        private ExampleServiceConnection mServiceConnection = new ExampleServiceConnection();
        private ExampleService mService = null;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            bindService(new Intent(this, ExampleService.class), mServiceConnection, BIND_AUTO_CREATE);
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
    
            unbindService(mServiceConnection);
        }
    
    
        class ExampleServiceConnection implements ServiceConnection {
    
            public void onServiceConnected(ComponentName name, IBinder service) {
                mService = ((ExampleBinder)service).getService();
    
                mService.setServiceClient(ExampleServiceActivity.this);
            }
    
            public void onServiceDisconnected(ComponentName name) {
                mService.setServiceClient(null);
                mService = null;
    
            }
        }
    
    
        public void exampleServiceClientMethod() {
            // TODO Auto-generated method stub
        }
    }
    

    Hope that helps.