StartService总结

一、整体工程图

StartService总结_第1张图片


二、activity_start_service.xml

<?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:orientation="vertical">


<Button android:text="startService" 
    android:id="@+id/buttonStartService" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"></Button>
</LinearLayout>


三、AndroidManifest.xml,需要注册Service

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jltxgcy.startservicedemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".StartServiceActivity"
            android:label="@string/title_activity_start_service" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name=".HelloService">
        </service>
            
    </application>

</manifest>

四、StartServiceActivity.java

package com.jltxgcy.startservicedemo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

public class StartServiceActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start_service);
        
        findViewById(R.id.buttonStartService).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(StartServiceActivity.this,HelloService.class);
				startService(intent);
			}
		});
    }


}

五、HelloService.java

package com.jltxgcy.startservicedemo;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import android.os.Process;

public class HelloService extends Service {

	  private Looper mServiceLooper;
	  private ServiceHandler mServiceHandler;
	  public static final String TAG="jltxgcy";


	  private final class ServiceHandler extends Handler {
	      public ServiceHandler(Looper looper) {
	          super(looper);
	      }
	      @Override
	      public void handleMessage(Message msg) {
	    	  Log.d(TAG, "handleMessage"+Thread.currentThread().getId());
	          long endTime = System.currentTimeMillis() + 5*1000;
	          while (System.currentTimeMillis() < endTime) {
	              synchronized (this) {
	                  try {
	                      wait(endTime - System.currentTimeMillis());
	                  } catch (Exception e) {
	                  }
	              }
	          }

	          stopSelf(msg.arg1);
	      }
	  }

	  @Override
	  public void onCreate() {

	    HandlerThread thread = new HandlerThread("ServiceStartArguments",
	            Process.THREAD_PRIORITY_BACKGROUND);
	    thread.start();

	    mServiceLooper = thread.getLooper();
	    mServiceHandler = new ServiceHandler(mServiceLooper);
	  }

	  @Override
	  public int onStartCommand(Intent intent, int flags, int startId) {
	      Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
	      Message msg = mServiceHandler.obtainMessage();
	      msg.arg1 = startId;
	      Log.d(TAG, "onStartCommand"+Thread.currentThread().getId());
	      mServiceHandler.sendMessage(msg);
	      return START_STICKY;
	  }

	  @Override
	  public IBinder onBind(Intent intent) {
	      return null;
	  }
	  
	  @Override
	  public void onDestroy() {
	    Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show(); 
	  }
}

六、解析

        按下startService,回调用onCreate,onStartCommand,Logcat显示如下:

        

        说明onStartCommand在主线程中,handleMessage通过Handler起了一个新的线程完成下载工作,下载工作完成后调用stopSelf

来停止Service,此时调用onDestroy方法。

         第二次点击startService,就只会调用onStartCommand,不会调用onCreate了。

         一般用于后台下载任务,或者当Activity退出后,Service来播放音乐。

         代码地址:https://github.com/jltxgcy/Demo


你可能感兴趣的:(StartService总结)