JavaH
JavaH

Reputation: 427

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";
    }
}

Upvotes: 3

Views: 5994

Answers (4)

Avijit Acharjee
Avijit Acharjee

Reputation: 31

Write your Activity and Service class Like this:

MyActivity.java

package com.rdc;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class MyActivity extends Activity {

    static MyActivity instance;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        instance = this;
        Intent myIntent = new Intent(getBaseContext(), MyService.class);
        startService(myIntent);
    }

    public void showToast() {
        Toast.makeText(getBaseContext(), "called from ervice", 1).show();

    }
}

MyService.java

package com.rdc;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {

    @Override
    public IBinder onBind(Intent i) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        Log.v("Debug", "Service has been Created..");
        // code to execute when the service is first created
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.v("Debug", "Service has been Started..");
        Toast.makeText(getBaseContext(), "Service has been Started..",
                Toast.LENGTH_SHORT).show();

        // getting the static instance of activity
        MyActivity activity = MyActivity.instance;

        if (activity != null) {
            // we are calling here activity's method
            activity.showToast();
        }

        return START_STICKY;
    }

}

Upvotes: 0

Zar E Ahmer
Zar E Ahmer

Reputation: 34360

There are three ways to handle service from Activity.

  • IBinder Implementation
  • Using Messanger
  • Using AIDL

Easiest way IMHO is to use bind service

public class Server extends Service{

 IBinder mBinder = new LocalBinder();

 @Override
 public IBinder onBind(Intent intent) {
  return mBinder;
 }

 public class LocalBinder extends Binder {
  public Server getServerInstance() {
   return Server.this;
  }
 }

 public String getTime() {
  SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  return mDateFormat.format(new Date());
 }
}



package com.example.bindservice.binder;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.bindservice.binder.Server.LocalBinder;

public class Client extends Activity {

 boolean mBounded;
 Server mServer;
 TextView text;
 Button button;

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        text = (TextView)findViewById(R.id.text);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new OnClickListener() {

   public void onClick(View v) {
    text.setText(mServer.getTime());
   }
  });
    }

 @Override
 protected void onStart() {
  super.onStart();
  Intent mIntent = new Intent(this, Server.class);
        bindService(mIntent, mConnection, BIND_AUTO_CREATE);
 };

 ServiceConnection mConnection = new ServiceConnection() {

  public void onServiceDisconnected(ComponentName name) {
   Toast.makeText(Client.this, "Service is disconnected", 1000).show();
   mBounded = false;
   mServer = null;
  }

  public void onServiceConnected(ComponentName name, IBinder service) {
   Toast.makeText(Client.this, "Service is connected", 1000).show();
   mBounded = true;
   LocalBinder mLocalBinder = (LocalBinder)service;
   mServer = mLocalBinder.getServerInstance();
  }
 };

 @Override
 protected void onStop() {
  super.onStop();
  if(mBounded) {
   unbindService(mConnection);
   mBounded = false;
  }
 };
}

Upvotes: 0

user468311
user468311

Reputation:

I guess you're on the wrong way. If you don't want to start Activity, but only want to call its method, you better push this method out of Activity. Class, which has many responsibilities is considered a bad design. Consider using Application class as well.

Upvotes: 0

Ian Warwick
Ian Warwick

Reputation: 4784

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.

Upvotes: 1

Related Questions