Exercise : 9
Create a background application that will open
activity on specific time.
Screen Shot:
XML :
main.xml :
main.xml :
JAVA :
MyService.java
package kmn.Nine;
import kmn.servicedemo.R;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service
{
/** @author Y@@D */
private static final String TAG = "MyService";
MediaPlayer player;
public IBinder onBind(Intent intent)
{
return null;
}
public void onCreate()
{
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
player = MediaPlayer.create(this, R.raw.braincandy);
player.setLooping(false); // Set looping
}
public void onDestroy()
{
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
public void onStart(Intent intent, int startid)
{
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player.start();
}
}
Nine.java :package kmn.Nine;
import kmn.servicedemo.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Nine extends Activity implements OnClickListener
{
/** @author Y@@D */
private static final String TAG = "ServicesDemo";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button start = (Button)findViewById(R.id.button1);
Button stop = (Button)findViewById(R.id.button2);
start.setOnClickListener(this);
stop.setOnClickListener(this);
}
public void onClick(View v)
{
if(v.getId()==R.id.button1)
{
Log.d(TAG, "onClick: starting srvice");
startService(new Intent(this, MyService.class));
//break;
}
if(v.getId()==R.id.button2)
{
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, MyService.class));
//break;
}
}
}

