Android记录三(绑定Service进行通信)

Service类:

package com.example.wlb.launchlocalapp;

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

public class MyService extends Service {
    public MyService() {
    }

    private boolean serviceRunning = false;
    private String data ="Service is running...";

    @Override
    public IBinder onBind(Intent intent) {
        return new Binder();
    }

    public class Binder extends android.os.Binder{
        void setData(String data){
            MyService.this.data = data;
        }
/*另外界可以访问到Service*/
        public MyService geService(){
            return MyService.this;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("Service onCommand.");
        data = intent.getStringExtra("data");

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("Service onCreate.");
        serviceRunning = true;

        new Thread(){
            @Override
            public void run() {
                super.run();

                int i = 0;

                while (serviceRunning) {
                    i++;
                    String str = i+":"+data;
                    System.out.println(str);

                    if(callback != null){
                        callback.onDataChange(str);
                    }

                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("Service onDestory.");
        serviceRunning = false;
    }

    /*返回函数*/
    private Callback callback = null;
    public void setCallback(Callback callback) {
        this.callback = callback;
    }
    public Callback getCallback() {
        return callback;
    }

    public static interface Callback{
        void onDataChange(String data);
    }
}

MainActivitty类

package com.example.wlb.launchlocalapp;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.Image;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

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

    private TextView textView;
    private EditText editText;
    private Intent intent;

    private MyService.Binder binder = null;
    private TextView tvOut;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main1);

        textView = (TextView) findViewById(R.id.textView);
        editText = (EditText) findViewById(R.id.editText);
        textView.setText("显示的信息是:" + getApp().getTextData());
        tvOut = (TextView) findViewById(R.id.tvOut);


        findViewById(R.id.btnStart).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(MainActivity.this,LocalAppAty.class);
                startActivity(i);
            }
        });

        findViewById(R.id.btnSave).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((App)getApplicationContext()).setTextData(editText.getText().toString());
                textView.setText("显示的信息是:" + getApp().getTextData());

            }
        });

/*Service的启动与关闭*/
        intent = new Intent(MainActivity.this,MyService.class);
//        findViewById(R.id.btnStartService).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                startService(intent);
//            }
//        });
//        findViewById(R.id.btnStoptService).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                stopService(intent);
//            }
//        });
        findViewById(R.id.btnStartService).setOnClickListener(this);
        findViewById(R.id.btnStoptService).setOnClickListener(this);
        findViewById(R.id.btnBindtService).setOnClickListener(this);
        findViewById(R.id.btnUnbindtService).setOnClickListener(this);
        findViewById(R.id.btnSyncData).setOnClickListener(this);


//        TextView tv = new TextView(this);
//        tv.setText(R.string.show1);
//        setContentView(tv);

//        ImageView iv = new ImageView(this);
//        iv.setImageResource(R.mipmap.ic_launcher);
//        setContentView(iv);
    }

    public App getApp(){
        return (App) getApplicationContext();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

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

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btnStartService:
                intent.putExtra("data",editText.getText().toString());
                startService(intent);
                break;
            case R.id.btnStoptService:
                stopService(intent);
                break;
            case R.id.btnBindtService:
                bindService(intent, this, Context.BIND_AUTO_CREATE);
                break;
            case R.id.btnUnbindtService:
                unbindService(this);
                break;
            /*把editText的数据传送到外界*/
            case R.id.btnSyncData:
                if (binder != null){
                    binder.setData(editText.getText().toString());
                };
                break;
        }
    }



    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        System.out.println("Service connected.");
        binder = (MyService.Binder) service;
        binder.geService().setCallback(new MyService.Callback() {
            @Override
            public void onDataChange(String data) {
                Message msg = new Message();
                Bundle b = new Bundle();
                b.putString("data",data);
                msg.setData(b);
                handler.sendMessage(msg);
            }
        });
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        System.out.println("Service disconnected.");
    }

    /*用于把Service线程的数据传到UI线程*/
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            tvOut.setText(msg.getData().getString("data"));
        }
    };

}

Layout布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/textView" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/tvOut" />


    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="请输入:"
        android:id="@+id/editText" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="保存"
        android:id="@+id/btnSave" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="跳转"
        android:id="@+id/btnStart" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="开启服务"
        android:id="@+id/btnStartService" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="关闭服务"
        android:id="@+id/btnStoptService" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="绑定服务"
        android:id="@+id/btnBindtService" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="解绑服务"
        android:id="@+id/btnUnbindtService" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="同步Service"
        android:id="@+id/btnSyncData" />
</LinearLayout>

AndroidManifest.xml

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

    <application
        android:name=".App"
        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>
        <activity android:name=".LocalAppAty">
            <intent-filter>
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true"></service>
    </application>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值