//服务创建的额时候被调用 @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.javapackage 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); } }
新闻热点
疑难解答