測試service的生命週期的程序,運行效果如下:
首先,對頁面進行佈局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="157dp"
android:text="@string/start" />
<Button
android:id="@+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/start"
android:layout_centerHorizontal="true"
android:layout_marginTop="36dp"
android:text="@string/stop" />
</RelativeLayout>
其次,編寫service類:
package com.bzu.servicelifecycle;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class LifeCycleService extends Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
System.out.println("onCreate()....");
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
System.out.println("onStart()...."+""+startId);
}
@Override
public void onDestroy() {
super.onDestroy();
System.out.println("onDestroy()....");
}
}
最後,主要的Activity類:
package com.bzu.servicelifecycle;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.support.v4.app.NavUtils;
public class ServiceLifeCycleActivity extends Activity {
private Button start;
private Button stop;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service_life_cycle);
start=(Button) this.findViewById(R.id.start);
stop=(Button) this.findViewById(R.id.stop);
start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setClass(ServiceLifeCycleActivity.this, LifeCycleService.class);
startService(intent);
}
});
stop.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setClass(ServiceLifeCycleActivity.this, LifeCycleService.class);
stopService(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_service_life_cycle, menu);
return true;
}
}
注意:在AndroidManifest.xml文件中註冊service:
<service android:name="LifeCycleService"></service>
否則會出下如下異常:
Unable to start service Intent { cmp=com.bzu.servicelifecycle/.LifeCycleService }: not found