Are your ready??
1. Bikin project baru
2. Siapkan dulu strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">ServiceSederhana!</string>
<string name="app_name">Service Background Sederhana</string>
<string name="startBtn">Start</string>
<string name="stopBtn">Stop</string>
</resources>
3. Kita bikin layoutnya di main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:textSize="24dip" />
<Button
android:id="@+id/startBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/startBtn" >
</Button>
<Button
android:id="@+id/stopBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/stopBtn" >
</Button>
</LinearLayout>
4. Buat folder raw didalam folder res. Taruh saja file mp3nya di folder raw.
5. Membuat class MyService.java
package com.serv.bg;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
public class MyService extends Service{
MediaPlayer mp;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate(){
mp=MediaPlayer.create(this, R.raw.beraksi);
mp.setLooping(false);
}
public void onStart(Intent intent,int startId){
mp.start();
}
@Override
public void onDestroy(){
mp.stop();
}
}
6. Membuat activity ServiceSederhana.java
package com.serv.bg;
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 ServiceSederhana extends Activity implements OnClickListener {
Button startBtn,stopBtn;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startBtn=(Button)findViewById(R.id.startBtn);
stopBtn=(Button)findViewById(R.id.stopBtn);
startBtn.setOnClickListener(this);
stopBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.startBtn:
startService(new Intent(this,MyService.class));
case R.id.stopBtn:
stopService(new Intent(this,MyService.class));
break;
}
// TODO Auto-generated method stub
}
}
7. Coba Run maka akan tampak seperti ini
0 comments:
Post a Comment