美文网首页
Service通知Activity(Broadcast)

Service通知Activity(Broadcast)

作者: 昨天剩下的一杯冷茶 | 来源:发表于2018-11-06 15:57 被阅读9次

    Layout

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout 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"
        android:orientation="vertical"
        tools:context="com.example.hzx.service_broadcast.MainActivity">
    
        <Button
            android:id="@+id/start_service"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="start_service"/>
    
        <Button
            android:id="@+id/bind_service"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="bind_service"/>
        <TextView
            android:id="@+id/text"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Hello World!"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    </LinearLayout>
    
    

    Service

    package com.example.hzx.service_broadcast;
    
    import android.app.Service;
    import android.content.Intent;
    import android.os.Binder;
    import android.os.IBinder;
    import android.support.annotation.Nullable;
    import android.support.v4.content.LocalBroadcastManager;
    import android.util.Log;
    
    /**
     * Created by hzx on 2018/11/6.
     */
    
    public class MyService extends Service {
    
        private final String TAG = "123";
        private MyBinder myBinder = new MyBinder();
        private LocalBroadcastManager localBroadcastManager;
        private int Broadcast_count;
        private MyThread myThread;
        public MyService(){
            this.localBroadcastManager = null;
            this.Broadcast_count = 0;
        }
    
        class MyBinder extends Binder{
            public void init_Broadcast(LocalBroadcastManager localBroadcastManager){
                Log.d(TAG,"service init_Broadcast");
                set_Broadcast(localBroadcastManager);
            }
    
            public int start_Thread(){
                if (get_Broadcast() == null){
                    return -1;
                }
                Log.d(TAG,"service start_Thread");
                myThread = new MyThread();
                myThread.start();
                return 0;
            }
    
        }
        private void set_Broadcast(LocalBroadcastManager localBroadcastManager){
            this.localBroadcastManager = localBroadcastManager;
        }
        private LocalBroadcastManager get_Broadcast(){
            return this.localBroadcastManager;
        }
        private int getBroadcast_count(){
            return this.Broadcast_count;
        }
        private void addBroadcast_count(){
            this.Broadcast_count++;
        }
        class MyThread extends Thread{
            public void run(){
                while(true){
                    //发送本地广播
                    Intent intent = new Intent("com.example.broadcasttest.LOCAL_BROADCAST");
                    intent.putExtra("ble",""+getBroadcast_count());
                    localBroadcastManager.sendBroadcast(intent);
                    addBroadcast_count();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        Log.d(TAG, "-->InterruptedException:" + getBroadcast_count());
                        e.printStackTrace();
                    }
                }
            }
        }
    
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return myBinder;
        }
        public void onCreate(){
            super.onCreate();
            Log.d(TAG,"service onCreate");
        }
        public int onStartCommand(Intent intent,int flags,int startId){
            Log.d(TAG,"service onStartCommand");
            return super.onStartCommand(intent,flags,startId);
        }
        public void onDestroy(){
            Log.d(TAG,"service onDestroy");
            super.onDestroy();
        }
        
    }
    
    

    MainActivity

    package com.example.hzx.service_broadcast;
    
    import android.content.BroadcastReceiver;
    import android.content.ComponentName;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.content.ServiceConnection;
    import android.os.IBinder;
    import android.os.TestLooperManager;
    import android.support.v4.content.LocalBroadcastManager;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;
    import android.widget.Toast;
    
    public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    
        private final String TAG = "123";
        private MyService.MyBinder myBinder;
    
        private IntentFilter intentFilter;
        private LocalReceiver localReceiver;
        private LocalBroadcastManager localBroadcastManager;
    
        private TextView textView;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            Button startService = (Button)findViewById(R.id.start_service);
            startService.setOnClickListener(MainActivity.this);
    
            Button bingService = (Button)findViewById(R.id.bind_service);
            bingService.setOnClickListener(MainActivity.this);
    
            textView = (TextView)findViewById(R.id.text);
    
            localBroadcastManager = LocalBroadcastManager.getInstance(this);
    
            intentFilter = new IntentFilter();
            intentFilter.addAction("com.example.broadcasttest.LOCAL_BROADCAST");
            localReceiver = new LocalReceiver();
            //注册本地广播监听器
            localBroadcastManager.registerReceiver(localReceiver,intentFilter);
    
        }
    
        private ServiceConnection connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                Log.d(TAG,"activity connection");
    
                myBinder = (MyService.MyBinder)iBinder;
                myBinder.init_Broadcast(localBroadcastManager);
                myBinder.start_Thread();
    
            }
            @Override
            public void onServiceDisconnected(ComponentName componentName) {
    
            }
        };
    
        //service 通知 activity
        class LocalReceiver extends BroadcastReceiver {
            public void onReceive(Context context, Intent intent){
                String ble_data = intent.getStringExtra("ble");
                textView.setText(ble_data);
            }
        }
    
        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.start_service:
                    Log.d(TAG,"activity start_service");
                    Intent startIntent = new Intent(this,MyService.class);
                    startService(startIntent);
                    break;
    
                case R.id.bind_service:
                    Log.d(TAG,"activity bind_service");
                    Intent bindIntent = new Intent(this,MyService.class);
                    bindService(bindIntent,connection,BIND_AUTO_CREATE);
                    break;
                default:
                    break;
            }
        }
    }
    
    

    注意:
    1、 需要在清单文件注册
    <service android:name=".MyService"/>

    效果


    image.png

    TIP:


    image.png

    我没有myBinder = (MyService.MyBinder)iBinder;
    直接拿来使用,结果崩溃了。

    相关文章

      网友评论

          本文标题:Service通知Activity(Broadcast)

          本文链接:https://www.haomeiwen.com/subject/bsuuxqtx.html