Activty和Service之间通信

概念:

通过Intent在ACtivity和Service之间通信
//定义Intent
private Intent serviceIntent;				
//将MainActivity和EchoService服务进行联系
serviceIntent=new Intent(MainActivity.this,EchoService.class);
//启动服务
startService(serviceIntent);
//绑定服务
bindService(serviceIntent,this, Context.BIND_AUTO_CREATE);
//解绑服务
unbindService(this);


启动Service两种方式
startService
bindService

一。创建MainActivity界面,和EchoService服务,在MainActivity创建5个BUTTON来进行,启动服务,关闭服务,绑定服务,解绑服务,获取服务中的值。
MainActivity界面

package com.example.service;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements Button.OnClickListener, ServiceConnection {

    private Button btnStartService;
    private  Button btnStopService;

    private Intent serviceIntent;

    private Button btnBindService;
    private  Button btnUbindService;

    private EchoService echoService=null;

    private Button getCurrent;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        btnStartService=(Button)findViewById(R.id.btnStartService);
        btnStartService.setOnClickListener(this);
        btnStopService=(Button)findViewById(R.id.btnStopService);
        btnStopService.setOnClickListener(this);

        serviceIntent=new Intent(MainActivity.this,EchoService.class);

        btnBindService=(Button)findViewById(R.id.btnBindService);
        btnBindService.setOnClickListener(this);
        btnUbindService=(Button)findViewById(R.id.btnUnbindService);
        btnUbindService.setOnClickListener(this);

        getCurrent=(Button)findViewById(R.id.btngetCurrent);
        getCurrent.setOnClickListener(this);
    }
    public void onClick(View v){
        switch (v.getId()){
            case R.id.btnStartService:
                startService(serviceIntent);//启动服务
                break;
            case R.id.btnStopService:
                stopService(serviceIntent);//停止服务
                break;
            case R.id.btnBindService:
                bindService(serviceIntent,this, Context.BIND_AUTO_CREATE);//绑定服务
                break;
            case R.id.btnUnbindService:
                unbindService(this);//解绑服务
                echoService=null;
                break;
            case R.id.btngetCurrent://通过点击获得EchoServcice中i的值
                System.out.println("当前数字是: "+echoService.getCurrentint());
        }
    }
    //当绑定服务后,会自动调用这个函数
    public  void onServiceConnected(ComponentName var1, IBinder binder){
        echoService=((EchoService.EchoServiceBinder)binder).getService();//通过内部类获取类的实例
        System.out.println("当前数字是: "+echoService.getCurrentint());

     System.out.println("---------------onServiceConnected");
    }
    public  void onServiceDisconnected(ComponentName var1){
        System.out.println("--------------- onServiceDisconnected");
    }

}

EchoService界面

package com.example.service;

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

import java.util.Timer;
import java.util.TimerTask;

public class EchoService extends Service {
    public IBinder onBind(Intent arg0){
        System.out.println("--------------------------- onBind");
        return echoServiceBinder;
    }
    public void onCreate(){
        System.out.println("-------------------- onCreate");
        startTimer();
        super.onCreate();
    }
    public void onDestroy(){
        stopTimer();
        super.onDestroy();
        System.out.println("---------------------onDestroy");
    }

    public int getCurrentint(){
        return i;
    }

    //定义内部类
    private final EchoServiceBinder echoServiceBinder=new EchoServiceBinder();
    public class EchoServiceBinder extends Binder{      //创建内部类
       public EchoService getService(){
           return EchoService.this;//取得服务的实例
       }
    }

    //定义定时器
    private  int i=0;
    private Timer timer=null;
    private TimerTask task=null;
    public  void startTimer(){
        if(timer==null){
            timer=new Timer();
            task=new TimerTask() {
                @Override
                public void run() {//每隔1s调用一次
                    i++;
                    System.out.println(i);
                }
            };
            timer.schedule(task,1000,1000);//任务  启动延时  没个多少秒
        }
    }
    public  void stopTimer() {
        if (timer != null)
        {
            timer.cancel();
            task.cancel();

            timer=null;
            task=null;
        }
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnStartService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="42dp"
        android:text="Start"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnStopService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="28dp"
        android:text="Stop"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnStartService" />

    <Button
        android:id="@+id/btnBindService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="1dp"
        android:layout_marginLeft="1dp"
        android:layout_marginTop="42dp"
        android:text="BindService"
        app:layout_constraintStart_toStartOf="@+id/btnUnbindService"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnUnbindService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="28dp"
        android:layout_marginEnd="100dp"
        android:layout_marginRight="100dp"
        android:text="UnbindService"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnBindService" />

    <Button
        android:id="@+id/btngetCurrent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="78dp"
        android:layout_marginLeft="78dp"
        android:layout_marginTop="46dp"
        android:text="getCurrent"
        app:layout_constraintStart_toStartOf="@+id/btnStopService"
        app:layout_constraintTop_toBottomOf="@+id/btnStopService" />

</androidx.constraintlayout.widget.ConstraintLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.service">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        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=".EchoService"></service>
    </application>

</manifest>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值