android学习之unbindservice一

来源:互联网 发布:java招生简章 编辑:程序博客网 时间:2024/05/15 07:34

今天谈谈android四大组件之一的service,今天我只简单的介绍service,以及需要注意的一些事项,后面会有补充的关于service的一些内容:

先贴一张service的生命周期图


当然,因为 这里介绍的是unbindservice,首先是启动,然后就是启动了service以后,oncreate只启动一次,以后点击以后只启动onStartConmmand,所以一般来说耗时的操作都在方法里面,然后就是运行,然后就是onDestory了,还有就是我不知道为什么那么多人喜欢把线程和service联系在一起(sorry,我也把他们联系在一起的了),我想说这两个有关系吗?如果真的有关系也就是可能会在service里面开辟线程来处理问题啊,对了,在启动线程的时候,注意配置权限。ok,贴代码

package com.jk.servicedemo;import android.app.Service;import android.content.Intent;import android.os.IBinder;public class MyService extends Service {@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn null;}@Overridepublic void onCreate() {System.out.println("onCreate");}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {System.out.println("onStartCommand");new Thread() {public void run() {for (int i = 0; i < 5; i++) {System.out.println(i);try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}.start();return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {System.out.println("onDestory");super.onDestroy();}}

package com.jk.servicedemo;import android.os.Bundle;import android.app.Activity;import android.content.Intent;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;public class MainActivity extends Activity implements OnClickListener {Button btn_start, btn_stop;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);init();}private void init() {// Initialize the componentbtn_start = (Button) findViewById(R.id.btn_start);btn_stop = (Button) findViewById(R.id.btn_stop);btn_start.setOnClickListener(this);btn_stop.setOnClickListener(this);}@Overridepublic void onClick(View v) {// get the id of the click eventint id = v.getId();switch (id) {case R.id.btn_start:startService();break;case R.id.btn_stop:stopService();break;}}private void startService() {Intent intent = new Intent();// set the flag of the startserviceintent.setAction("www.jk.com");startService(intent);}private void stopService() {Intent intent = new Intent();// set the flag of the endserviceintent.setAction("www.jk.com");stopService(intent);}}

service android:name="com.jk.servicedemo.MyService" >            <intent-filter  >                <action android:name="www.jk.com"/>            </intent-filter>        </service>


0 0
原创粉丝点击