android学习笔记(10)service初步

来源:互联网 发布:淘宝店长和运营的区别 编辑:程序博客网 时间:2024/06/04 20:08

前面学习了activity,service与它不同的地方是service可以后台运行,而activity不能.

一,service与thread
当后台运行不需要用户交互时用service如后台下载;当后台老板运行的程序需要用户至上交互时用thread如音乐播放.
二,启动方式
可以通过activity来启动
1,startService() 调用者和服务之间没有联系,即使调用 者退出了,服务仍运行.
(1)创建一个服务类.
点New Java Class图标创建一个类,在Superclass栏点Browse搜索service-android.app确定.
(2)复写方法:onStartCommand()  onBind()  onCreate()  onDestroy()
在代码中右键-->Source-->Override Implemet Methods然后勾选要复写的方法
(3)在manifest文件中声明服务:

<service android:name=".Service"/>

(4)过程:onCreate()-->startService()-->onDestory()

2,bindService() 调用者和服务绑在一起,调用者一旦退出,服务也就终止.
过程:onCreate-->onBind()-->onUnbind()-->onDestory()
三,源码:
activity_main.xml:
    <Button        android:id="@+id/btnservicestart"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="startservice" />        <Button        android:id="@+id/btnservicestop"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="stopservice" />
MainActivity.java:
package com.example1.servicedemo;import org.apache.commons.logging.Log;import android.net.sip.SipAudioCall.Listener;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;public class MainActivity extends Activity {private Button btnButton;private Button btnButton2;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        btnButton = (Button)findViewById(R.id.btnservicestart);        btnButton2 = (Button)findViewById(R.id.btnservicestop);        btnButton.setOnClickListener(listener);        btnButton2.setOnClickListener(listener);    }private OnClickListener listener = new OnClickListener() {@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.btnservicestart:Intent intent = new Intent(MainActivity.this,ExamppleService.class);startService(intent);break;case R.id.btnservicestop:Intent intent2 = new Intent(MainActivity.this,ExamppleService.class);startService(intent2);break;default:break;}}};    }
ExamppleService.java:
package com.example1.servicedemo;import org.apache.commons.logging.Log;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.LogPrinter;public class ExamppleService extends Service {private static final String tag = "ExamppleService";@Overridepublic IBinder onBind(Intent arg0) {return null;}@Overridepublic void onCreate() {Log.i(tag,"ExamppleService-->onCreate");super.onCreate();}@Overridepublic void onDestroy() {Log.i(tag,"ExamppleService-->onDestroy");super.onDestroy();}}

在manifest文件中声明服务:
<service android:name=".Service"/>
运行后可以看到相应的日志输出,在我这个版本中Log.i();显示有错,建议是rename但没用,求教.
4 0
原创粉丝点击