首页 > 系统 > Android > 正文

44.android服务service-启动和关闭

2019-11-09 13:50:24
字体:
来源:转载
供稿:网友
Service运行于后台的一个组件,用来运行适合运行在后台的代码,可以视为没有界面的activity进程的优先级:1.Foreground PRocess:前台进程,拥有一个正在与用户交互的activity的进程onResume方法被调用2.visible process:可见进程,拥有可见没有焦点的activy,onPause方法被调用。3.Service process:服务进程,通过startService启动的服务4.background process:后台进程,拥有一个不可见的activity(onStop方法被调用)的进程5.Empty process:空进程,没有任何活动的应用组件的进程(activity已经退出了)服务的生命周期
	//服务创建的额时候被调用	@Override	public void onCreate(){		super.onCreate();		System.out.println("onCreate方法被调用");	}		//可见没有焦点的时候调用,因为服务本身没有焦点,这个方法过时了,现在都用下面的onStartCommand方法	@Override	public void onStart(Intent intent, int startId){		super.onStart(intent, startId);		System.out.println("onStart方法被调用");	}			@Override	public int onStartCommand(Intent intent, int flags, int startId){		System.out.println("onStartCommand方法被调用");		return super.onStartCommand(intent, flags, startId);	}		//服务销毁的时候调用	@Override	public void onDestroy(){		super.onDestroy();		System.out.println("onDestroy方法被调用");	}开启一个服务和关闭一个服务配置文件:
<service android:name="com.ldw.startService.MyService"></service>activity_main.xml
<LinearLayout 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"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".MainActivity"    android:orientation="vertical"    >    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="开启服务"         android:onClick="click"        />    <Button         android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="关闭服务"         android:onClick="click2"        /></LinearLayout>MyService.java
package com.ldw.startService;import android.app.Service;import android.content.Intent;import android.os.IBinder;public class MyService extends Service {	@Override	public IBinder onBind(Intent intent) {		// TODO Auto-generated method stub		return null;	}}

MainActivity.java

package com.ldw.startService;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }    public void click(View v){    	//显示启动服务    	Intent intent = new Intent(this, MyService.class);    	startService(intent);    }        public void click2(View v){    	//关闭鼓舞    	Intent intent = new Intent(this, MyService.class);    	stopService(intent);    }    }


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表