Service structure
package app.test;
import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
class SimpleServiceService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Log.v("SIMPLESERVICE", "onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v("SIMPLESERVICE", "onStartCommand");
return START_STICKY;
}
@Override
public void onStart(Intent intent, int startid) {
Log.v("SIMPLESERVICE", "onStart");
}
public void onDestroy() {
Log.v("SIMPLESERVICE", "onDestroy");
}
}
public class Test extends Activity implements OnClickListener {
Button startServiceButton;
Button stopServiceButton;
Intent serviceIntent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startServiceButton = (Button) this
.findViewById(R.id.StartServiceButton);
stopServiceButton = (Button) this.findViewById(R.id.StopServiceButton);
startServiceButton.setOnClickListener(this);
stopServiceButton.setOnClickListener(this);
serviceIntent = new Intent(this, SimpleServiceService.class);
}
public void onClick(View v) {
if (v == startServiceButton) {
startService(serviceIntent);
} else if (v == stopServiceButton) {
stopService(serviceIntent);
}
}
}
//main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Simple Service"
/>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/StartServiceButton" android:text="Start Service"></Button>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Stop Service" android:id="@+id/StopServiceButton"></Button>
</LinearLayout>
Related examples in the same category