• android service broadcastreceiver intentfilter


    service 组件,和UI并不进行交互,运行在后台,可以和其他组件进行交互

    broadcastreceiver,广播是一种广泛运用的在应用程序之间传输信息的机制 。而 BroadcastReceiver 是对发送出来的广播进行过滤接收并响应的一类组件

    intentfilter Intent类似于Windows中的消息,而intentfilter可以理解为消息过滤器

    下面我们用例子来说明如何运用这三种组件

    首先,我们建立一个Serivce,他的作用是每间隔一秒生成一个随机数,并将随机数放到Intent中

    然后声明一个action,在Service中进行广播,在MainActivity中来接收这个广播,并显示随机数.

    为了可以使服务停止,我们另外建立了一个BroadCastReceiver 来接受广播,当判断广播内容是停止服务时,调用停止服务.

    在服务的onCreate中,注册广播接收器组件,在onDestory中取消注册广播接收组件

    在onStartCommand中声明了一个IntentFilter用来过滤广播消息,设定Action

    先来看下Service和停止服务用的BroadCastReceiver 

    package com.ssln.broadcastreceiver_service_intentfilter;
    
    import android.app.Service;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.os.IBinder;
    import android.util.Log;
    
    public class MyService extends Service {
    
        public final static int CMD_STOP_SERVICE=1;    //停止服务
        private CommandReciver cmdReceiver;
        private boolean flag;
        public final static String action="com.ssln.broadcastreceiver_service_intentfilter.MyService";
        private static final String TAG = "MyService";
    
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    
        @Override
        public void onCreate() {
            flag = true;
            cmdReceiver = new CommandReciver();
            super.onCreate();
            Log.i(TAG, "MyService-->onCreate");
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.i(TAG, "MyService-->onStartCommand");
            IntentFilter filter = new IntentFilter(); // 建立IntentFilter对象
            filter.addAction(action);
            // 注册广播接收,并设置接受的action
            registerReceiver(cmdReceiver, filter);
            Log.i(TAG, "MyService-->注册BroadcastReceiver成功");
            // 启动线程
            doJob();
            return super.onStartCommand(intent, flags, startId);
        }
    
        @Override
        public void onDestroy() {
            Log.i(TAG, "MyService-->onDestroy");
            // 取消广播接受的注册
            unregisterReceiver(cmdReceiver);
            Log.i(TAG, "MyService-->取消注册BroadcastReceiver成功");
            super.onDestroy();
        }
    
        /**
         * 执行线程
         */
        private void doJob() {
            new Thread() {
                public void run() {
                    while (flag) {
                        try {
                            Thread.sleep(1000);// 睡眠一秒
                        } catch (Exception exp) {
                            exp.printStackTrace();
                        }
                        Intent intent=new Intent();
                        //设置action
                        intent.setAction(action);
                        //设置随机数
                        intent.putExtra("data", Math.random());
                        //发送广播
                        sendBroadcast(intent);
                        Log.i(TAG, "MyService-->doJob");
                    }
                }
    
            }.start();
        }
    
        /**
         * 为了Service的停止,为Service注册Broadcast Receiver组件
         * @author ssln
         *
         */
        private class CommandReciver extends BroadcastReceiver {
    
            @Override
            public void onReceive(Context context, Intent intent) {
                int cmd=intent.getExtras().getInt("cmd",-1);
                if(cmd==CMD_STOP_SERVICE){
                    //停止线程
                    flag=false;
                    //停止服务
                    stopSelf();
                }
            }
    
        }
    }

    在来看看MainActivity.java

    在onclick中,我们看到btnStart是启动了我们自定义的服务,而btnStop是发送了一个停止服务的广播内容

    package com.ssln.broadcastreceiver_service_intentfilter;
    
    import android.app.Activity;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.TextView;
    
    public class MainActivity extends Activity implements OnClickListener{
    
        private static final String TAG = "MainActivity";
        private TextView tvData;
        private Button btnStart,btnStop;
        private DataReceiver datareceiver;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            tvData=(TextView)findViewById(R.id.tvData);
            btnStart=(Button)findViewById(R.id.btnStart);
            btnStop=(Button)findViewById(R.id.btnStop);
            
            btnStart.setOnClickListener(this);
            btnStop.setOnClickListener(this);
        }
     
        /**
         * 注册广播接收
         */
        private void RegDataReceiver()
        {
            if(datareceiver==null)
            {
                //注册action
                datareceiver=new DataReceiver();
                IntentFilter filter=new IntentFilter();
                //添加接受的action
                filter.addAction(MyService.action);
                //注册
                registerReceiver(datareceiver, filter);
                Log.i(TAG, "注册广播成功");
            }
        }
        /**
         * 取消注册
         */
        private void UnRegDataReceiver()
        {
            if(datareceiver!=null)
            {
                unregisterReceiver(datareceiver);
                datareceiver=null;
                Log.i(TAG, "取消注册广播");
            }
        }
    
        @Override
        protected void onResume() {
            RegDataReceiver();
            Log.i(TAG, "onResume");
            super.onResume();
        }
    
        @Override
        protected void onPause() {
            UnRegDataReceiver();
            Log.i(TAG, "onPause");
            super.onPause();
        }
    
    
        /**
         * 接受线程发送过来的数据
         * @author ssln
         *
         */
        private class DataReceiver extends BroadcastReceiver{
    
            @Override
            public void onReceive(Context context, Intent intent) {
                double data=intent.getDoubleExtra("data", 0.0d);
                if(data==0)
                {
                    int cmd=intent.getIntExtra("cmd", -1);
                    if(cmd==MyService.CMD_STOP_SERVICE)
                        tvData.setText("停止服务成功");
                    else
                        tvData.setText("未知数据");
                }
                else
                {
                    tvData.setText("Service 发送的数据为: "+String.valueOf(data));
                }
            }
            
        }
    
        @Override
        public void onClick(View v) {
            if(v==btnStart)
            {
                Intent myIntent=new Intent(MainActivity.this,MyService.class);
                startService(myIntent);
                tvData.setText("启动服务成功 ");
            }
            else if(v==btnStop)
            {
                Intent myIntent=new Intent();
                myIntent.setAction(MyService.action);
                myIntent.putExtra("cmd", MyService.CMD_STOP_SERVICE);
                sendBroadcast(myIntent);
            }
        }
    }

    activity_main.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/LinearLayout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="com.ssln.broadcastreceiver_service_intentfilter.MainActivity" >
    
        <TextView
            android:id="@+id/tvData"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />
    
        <Button
            android:id="@+id/btnStart"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="启动服务" />
    
        <Button
            android:id="@+id/btnStop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="停止服务" />
    
    </LinearLayout>

    最后,记得在AndroidManifest.xml中注册我们的服务,否则启动不了的啊

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.ssln.broadcastreceiver_service_intentfilter"
        android:versionCode="1"
        android:versionName="1.0" >
    
        <uses-sdk
            android:minSdkVersion="17"
            android:targetSdkVersion="20" />
    
        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name=".MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <!-- 注册服务 -->
            <service android:name="MyService"></service>
        </application>
    
    </manifest>

    看下效果,每秒生成的随机数都不同

    我们点击停止后,会停止服务

  • 相关阅读:
    14_部署LNMP环境、构建LNMP平台、地址重写
    13_搭建Nginx服务器、配置网页认证、基于域名的虚拟主机、ssl虚拟主机
    12_rsync+SSH同步
    11_DNS子域授权、分离解析、缓存DNS服务器
    10_自定义yum仓库、源码编译安装
    09_parted分区工具、交换分区、链路聚合
    08_简单MariaDB数据库的管理
    bzoj1396
    bzoj4154
    bzoj3489
  • 原文地址:https://www.cnblogs.com/alwaysfirst/p/4009108.html
Copyright © 2020-2023  润新知