android api分析21 Service

来源:互联网 发布:会计核算软件说明书 编辑:程序博客网 时间:2024/05/01 10:09

Service


dump()
getApplication()
onBind() //返回一个IBinder对象 应用程序通过该对象与Service组件通信
onConfigurationChanged()
onCreate() //第一次创建时回调
onDestroy() //关闭之前回调
onLowMemory()
onRebind()
onStart() //客户端调用startService(Intent)启动Service回调该方法
onStartCommand()
onTaskRemoved()
onTrimMemory()
onUnbind() //Service绑定的客户端都断开连接时回调该方法
startForeground()
stopForeground()
stopSelf()
stopSelfResult()


运行Service的两种方式
Context的startService()方法 该方法启用Service 访问者与Service没有关联 访问者退出了 Service依然运行
Context的bindService()方法 该方法启用Service 访问者与Service绑定在一起 访问者退出 Service也就
终止了

实例

public class MainActivity extends Activity{Button start , stop;@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);// 获取程序界面中的start、stop两个按钮start = (Button) findViewById(R.id.start);stop = (Button) findViewById(R.id.stop);//创建启动Service的Intentfinal Intent intent = new Intent();//为Intent设置Action属性intent.setAction("org.crazyit.service.FIRST_SERVICE");start.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View arg0){//启动指定SerivcestartService(intent);}});stop.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View arg0){//停止指定SerivcestopService(intent);}});}}

<?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:gravity="center_horizontal"    android:orientation="horizontal" >    <Button        android:id="@+id/start"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="start" />    <Button        android:id="@+id/stop"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="stop" /></LinearLayout>

public class FirstService extends Service{// 必须实现的方法@Overridepublic IBinder onBind(Intent arg0){Log.e("FirstService", "onBind");return null;}// Service被创建时回调该方法。@Overridepublic void onCreate(){super.onCreate();Log.e("FirstService", "onCreate");}// Service被启动时回调该方法@Overridepublic int onStartCommand(Intent intent, int flags, int startId){Log.e("FirstService", "onStartCommand");return START_STICKY;}// Service被关闭之前回调。@Overridepublic void onDestroy(){super.onDestroy();Log.e("FirstService", "onDestroy");}}
                <service android:name=".FirstService"><intent-filter><!-- 为该Service组件的intent-filter配置action --><action android:name="org.crazyit.service.FIRST_SERVICE" /></intent-filter></service>

运行结果

点击start按钮

onCreate
onStartCommand

再次点击start按钮

onStartCommand

点击stop按钮

onDestroy



0 0
原创粉丝点击