StartService总结

一、整体工程图



二、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


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值