android中的Service基礎知識

Service即服務,沒有UI,在手機中常見的運用是音樂播放器,音樂播放器能夠在後臺播放音樂,用的就是Service來實現的。

參考網上的資料,做了一個玩玩。(偷笑也可以說是照搬了一個。)

請結合Service的生命週期來理解。

使用service需要在AndroidManifest.xml的application標籤中加入 <service android:enabled="true" android:name="com.ccav.Service"/>(name後面的參數請根據實際情況修改)


首先是XML佈局文件

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" android:id="@+id/layout">

	<Button android:id="@+id/button1" android:layout_width="fill_parent"
		android:layout_height="wrap_content" android:text="StartServer"
		android:onClick="onClick" />
	<Button android:text="Stop Server" android:id="@+id/button2"
		android:layout_width="match_parent" android:layout_height="wrap_content"></Button>

</LinearLayout>  

java文件:

Hello_worldActivity.java

package com.ccav;

import com.fjep.R;

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 Hello_worldActivity extends Activity implements OnClickListener {

	private Intent intent;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// 發現控件並設置監聽事件
		Button startServer = (Button) findViewById(R.id.button1);
		Button stopServer = (Button) findViewById(R.id.button2);
		startServer.setOnClickListener(this);
		stopServer.setOnClickListener(this);
		// intent設置需要啓動的class,這裏指定的是service這個class
		intent = new Intent(Hello_worldActivity.this, Service.class);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.button1:
			// 啓動服務的方法
			startService(intent);
			break;
		case R.id.button2:
			// 停止服務的方法
			stopService(intent);
			break;
		default:
			break;
		}
	}

}

Service.java

package com.ccav;

import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class Service extends android.app.Service {

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onCreate() {
		Log.i("Fover", "Service onCreate");
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		Log.i("Fover", "Service onDestroy");
		super.onDestroy();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		Log.i("Fover", "Service onStart");
		super.onStart(intent, startId);
	}

	
	}



運行結果:

主界面:

後臺:

查看調試信息:



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章