Service 入门——service调用执行顺序&利用service模拟完成一个后台服务

package com.example.xh.myapplication;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
//MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private Button btnStart,btnStop;
    private Button btnBind,btnUnBind;
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //连接成功,自动调用
            Log.i("Activity","onServiceConnected");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            //连接无效时调用
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }
    private void init() {
        btnStart =(Button)findViewById(R.id.btnStart);
        btnStop =(Button)findViewById(R.id.btnStop);
        btnStart.setOnClickListener(this);
        btnStop.setOnClickListener(this);
        btnBind=(Button)findViewById(R.id.btnBind);
        btnUnBind=(Button)findViewById(R.id.btnUnBind);
        btnBind.setOnClickListener(this);
        btnUnBind.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(MainActivity.this,MyService.class);
        switch(v.getId()){
            case R.id.btnStart:
                startService(intent);//onCreate>>onStartCommand
                break;
            case R.id.btnStop:
                stopService(intent);
                break;
            case R.id.btnBind:
                bindService(intent,conn,BIND_AUTO_CREATE);//bindService必须要有一个连接存在 onCreate>>onBind
                break;
            case R.id.btnUnBind:
                unbindService(conn);
                break;
        }
    }
}

 

package com.example.xh.myapplication;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
//MyService.java
public class MyService extends Service {
    private static final String TAG = "MyService";
    /*
     只在生命周期第一次被调用
     */
    @Override
    public void onCreate(){
        super.onCreate();
        Log.i(TAG,"onCreate");
    }
    @Override
    public void onDestroy() {
        Log.i(TAG,"onDestroy");
        super.onDestroy();
    }
    /*
     每次startService启用时会被调用
    */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG,"onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }
    /*
     bingService启动时调用,在整个生命周期中只被调用一次
     */
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG,"onBind");
        return new MyBinder();
    }
    class  MyBinder extends Binder{

    }
}

 

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.xh.myapplication">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="Service"/>
            </intent-filter>
        </service>
    </application>

</manifest>

 

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
    tools:context="com.example.xh.myapplication.MainActivity">
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="startService"
        android:id="@+id/btnStart"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="68dp" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="stopService"
        android:id="@+id/btnStop"
        android:layout_alignTop="@+id/btnStart"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Bind"
        android:id="@+id/btnBind"
        android:layout_centerVertical="true"
        android:layout_toLeftOf="@+id/btnStop"
        android:layout_toStartOf="@+id/btnStop" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="UnBind"
        android:id="@+id/btnUnBind"
        android:layout_alignParentBottom="true"
        android:layout_alignRight="@+id/btnStop"
        android:layout_alignEnd="@+id/btnStop" />

</LinearLayout>

—————————————————————————————————————————————————————————————————————————

DemoActivity.java

 

package com.example.xh.serviceapp;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/**
 * Created by XH on 2016/8/17.
 */
public class DemoActivity extends Activity {
    private EditText etChinese,etMath,etEnglish;
    private TextView tvResult;
    private Button btnCK;
    private ComputeService.ComputeBinder binder =null;
    private ServiceConnection conn=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
                 Log.i("TEST","onServiceConnected");
                 binder=(ComputeService.ComputeBinder)service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent service = new Intent(DemoActivity.this,ComputeService.class);
        bindService(service,conn,BIND_AUTO_CREATE);
        init();
    }

    @Override
    protected void onDestroy() {
        unbindService(conn);
        super.onDestroy();
    }

    private void init() {
        etChinese=(EditText)findViewById(R.id.etChinese);
        etMath=(EditText)findViewById(R.id.etMath);
        etEnglish=(EditText)findViewById(R.id.etEnglish);
        tvResult=(TextView)findViewById(R.id.tvResult);
        btnCK=(Button)findViewById(R.id.btnCK);
        btnCK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    //从文本框中读取输入的成绩
                    double chinese = Double.parseDouble(etChinese.getText().toString());
                    double math = Double.parseDouble(etMath.getText().toString());
                    double english = Double.parseDouble(etEnglish.getText().toString());
                    //请求对象完成工作
                    if(binder != null){
                          double result = binder.calcAvg(chinese, math, english);
                          //显示
                          tvResult.setText("三门课平均成绩为:" + result);}
                }catch (NumberFormatException ex){

                }catch (Exception ex){

                }
            }
        });
    }
}

ComputeService.java

package com.example.xh.serviceapp;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class ComputeService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return new ComputeBinder();
    }
    public class ComputeBinder extends Binder{
        /*
         计算平均值
          scores可变数组,参数可以是0~N个
          retur   n
         */
        public double calcAvg(double...scores){
            int count = scores.length;
            if (count==0){
                return 0;
            }
            double sum = 0;
            for (double s:scores){
                sum+=s;
            }
            return sum/count;
        }
    }
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="com.example.xh.serviceapp.MainActivity">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:id="@+id/linearLayout"
        android:weightSum="1">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="语文:"
            android:id="@+id/textView"
            android:layout_alignParentTop="true"
            android:layout_alignRight="@+id/linearLayout"
            android:layout_alignEnd="@+id/linearLayout"
            android:layout_marginRight="101dp"
            android:layout_marginEnd="101dp" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/etChinese" />

    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/linearLayout"
        android:layout_centerHorizontal="true"
        android:id="@+id/linearLayout2"
        android:weightSum="1">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="数学:"
            android:id="@+id/textView3"
            android:layout_alignTop="@+id/linearLayout"
            android:layout_alignRight="@+id/linearLayout"
            android:layout_alignEnd="@+id/linearLayout"
            android:layout_marginRight="125dp"
            android:layout_marginEnd="125dp" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/etMath" />

    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearLayout3"
        android:layout_below="@+id/linearLayout2"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:weightSum="1">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="英语:"
            android:id="@+id/textView5"
            android:layout_centerVertical="true"
            android:layout_alignRight="@+id/linearLayout3"
            android:layout_alignEnd="@+id/linearLayout3" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/etEnglish" />

    </LinearLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="确定"
        android:layout_below="@+id/linearLayout3"
        android:layout_alignRight="@+id/linearLayout3"
        android:layout_alignEnd="@+id/linearLayout3"
        android:layout_marginRight="139dp"
        android:layout_marginEnd="139dp"
        android:id="@+id/btnCK" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:id="@+id/tvResult"
        android:text=""
        android:textColor="@color/colorAccent"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/btnCK" />

</RelativeLayout>

onStartCommand测试:在service里面获取成绩将成绩传给service

 

 

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值