Friday, 31 May 2013

EXAMPLE PROGRAMME ON SERVICE IN ANDROID

ExplicitServiceActivity.java

package com.service;

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

public class ExplicitServiceActivity extends Activity
implements OnClickListener {
    /** Called when the activity is first created. */
     Button bstart,bstop;
    @Override  
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        bstart=(Button)findViewById(R.id.button1);
        bstop=(Button)findViewById(R.id.button2);
        bstart.setOnClickListener(this);
        bstop.setOnClickListener(this);
       
    }
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if(v.getId()==R.id.button1){
            startService(new Intent(this,MyService.class));
        }else{
            stopService(new Intent(this,MyService.class));
        }
    }
   
}




Myservice.java



package com.service;

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

public class MyService extends Service{

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        Toast.makeText(this, "Service Created...",
                Toast.LENGTH_LONG).show();
    }
    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
        Toast.makeText(this, "Service Started...",
                Toast.LENGTH_LONG).show();
    }
    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        Toast.makeText(this, "Service Destroyed...",
                Toast.LENGTH_LONG).show();
    }


}







Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.service"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <service android:name=".MyService">           
        </service>
        <activity
            android:name=".ExplicitServiceActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>







No comments:

Post a Comment