Sunday, 15 September 2013

BindService Demo activity

package com.demo;

public class BindServiceDemoact extends Activity
{
    boolean mBounded;
    Myser  mServer;
  
    TextView text;
    Button Bon;
  
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        text=(TextView) findViewById(R.id.textView1);       
        Bon =(Button) findViewById(R.id.button1);
       
    Intent mIntent=new Intent(BindServiceDemoact.this,Myser.class);
    bindService(mIntent,mConnection,BIND_AUTO_CREATE);
       
        Bon.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                text.setText(mServer.getTime());
            }
        });
    }
    ServiceConnection mConnection=new ServiceConnection()
    {
        public void onServiceConnected(ComponentName name, IBinder service)
        {
            // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), "My Service is Connected",1000);
            mBounded=true;
            LocalBinder mLB=(LocalBinder)service;
            mServer=mLB.getServerRequest();
        }

        public void onServiceDisconnected(ComponentName name)
        {
            // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), "My Service is Connected",1000);
            mBounded=false;
            mServer=null;
        }
    };
   
    protected void onStop()
    {
        super.onStop();
        if(mBounded)
        {
            unbindService(mConnection);
            mBounded=false;
        }
    }
}




package com.demo;

public class Myser extends Service
{
    public class LocalBinder extends Binder
    {
        public Myser getServerRequest()
        {
            return Myser.this;
        }
    }
  
    @Override
    public IBinder onBind(Intent intent)
    {
        // TODO Auto-generated method stub
        return new LocalBinder();
    }
  
    public String getTime()
    {
        // TODO Auto-generated method stub
        SimpleDateFormat mdate=new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
        return mdate.format(new Date());
    }

}

No comments:

Post a Comment