We provide complete mobile and web apps development solutions

Saturday, October 20, 2012

Service in Android




 MainActivity.java
package com.example.serviceexample;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {
            Button b1;
            Button b2;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
         b1=(Button)findViewById(R.id.button1);
         b2=(Button)findViewById(R.id.button2);
        b1.setOnClickListener(this);
        b2.setOnClickListener(this);   
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

     public void onClick(View v) {
                        // TODO Auto-generated method stub
                        switch(v.getId())
                        {
                        case R.id.button1:
                                    startService(new Intent(this,ServiceDemo.class));
                                    break;
                        case R.id.button2:
                                    startService(new Intent(this,ServiceDemo.class));
                                   
                        }
            }
}


 ServiceDemo.java
package com.example.serviceexample;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

public class ServiceDemo extends Service{
     
      MediaPlayer mediaplayer;

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

      @Override
      public void onCreate() {
            // TODO Auto-generated method stub
            super.onCreate();
           
            mediaplayer=MediaPlayer.create(this, R.raw.newsong);
      }

      @Override
      public void onDestroy() {
            // TODO Auto-generated method stub
            super.onDestroy();
            mediaplayer.stop();
      }
      @Override
      public void onStart(Intent intent, int startId) {
            // TODO Auto-generated method stub
            super.onStart(intent, startId);
            mediaplayer.start();
      }
}

Declare manifest permission for service

 <service android:name="ServiceDemo"></service>



you can download source code here

http://www.4shared.com/rar/O39SukJ_/ServiceExample.html?



0 coment�rios:

Post a Comment

Online Training

Your Name :
Your Email: (required)
Your Message: (required)

Powered by Blogger.

Recent Posts

Find Us On Facebook

Popular Posts