本地 Services(服务)

来源:互联网 发布:nlp tensorflow 编辑:程序博客网 时间:2024/06/04 01:39

Services

什么是Services

  • android中服务是运行在后台的东西,级别与activity一样。既然说service是运行在后台的服务,那么它就是不可见的,没有界面的东西。可以启动一个服务Service来播放音乐,或者记录地理信息位置的改变,或者启动一个服务来运行并一直监听某种动作。Service和其他组件一样,都是运行在主线程中,因此不能用它来做耗时的请求或者动作。

服务分二种

本地服务

  1. 本地服务, Local Service 用于应用程序内部。在Service可以调用Context.startService()启动,调用Context.stopService()结束。在内部可以调用Service.stopSelf() 或 Service.stopSelfResult()来自己停止。无论调用了多少次startService(),都只需调用一次stopService()来停止。

2 . 远程服务, Remote Service 用于android系统内部的应用程序之间。可以定义接口并把接口暴露出来,以便其他应用进行操作。客户端建立到服务对象的连接,并通过那个连接来调用服务。调用Context.bindService()方法建立连接,并启动,以调用 Context.unbindService()关闭连接。多个客户端可以绑定至同一个服务。如果服务此时还没有加载,bindService()会先加载它。

使用本地服务实现UI更新(示例)

实现步骤

  1. 建立一个类,继承 Service 重写onBind、onCreate、onStartCommand、onDestroy方法。
  2. 在Activiry中,建立 Intent(this,继承Services的类.class)对象,调用服务启动方法startService(intent 刚才建立的对象); 和 stopService(intent); 因为是启动服务,故此需要,在AndroidManifest.xml文件中,写入,允许启动服务。
  3. <service android:name=".MyServices"
    android:enabled="true"
    android:exported="true"
    ></service>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.zking.administrator.g160618_android23_services">    <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=".MyServices"            android:enabled="true"            android:exported="true"            ></service>    </application></manifest>


Activity

public class MainActivity extends AppCompatActivity {    private Intent intent;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //需要启动的服务        intent = new Intent(this,MyServices.class);    }    public void start(View view){         //启动服务        startService(intent);    }    public void stop(View view){       //停止服务        stopService(intent);    }------------------------------------------------------------   //内部(服务)类,编写服务内容 class sendServe extends Thread{        int startid;        //通过 构造函数,传递过来启动的服务id,用来判断,等所有服务只想完后,再自动结束服务        public sendServe (int startId) {           this.startid=startId;        }        public void setIntent(Intent intent) {            this.intent = intent;        }        private Intent intent;        @Override        public void run() {            //建立意图发送广播            intent = new Intent();            //建立广播,频率,推荐使用包名加类名            intent.setAction("ces");            //发送内容            String  fs="ddddddddsfsd方法潍坊市发生生栋覆屋";            for (int i = 0; i <fs.length() ; i++) {                //设定每次广播发送的内容                intent.putExtra("fs",fs.substring(0,i));                try {                  //发一次,暂停1秒                    sleep(1000);                } catch (InterruptedException e) {                    e.printStackTrace();                }                //发送广播                sendBroadcast(intent);            }             //当所有的服务(线程),执行完毕后,停止服务。           stopSelf(startid);        }    }}


第二个Activity

public class MainActivityTwo extends AppCompatActivity {    private ReceiveTwo receiveTwo;    private IntentFilter intd;    private ProgressBar progressBar;    private TextView textView;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main_two);  //显示广播接受到的值        textView = (TextView) findViewById(R.id.tv_main_one);       //这里采用,动态广播接受者        //接受者  对象         receiveTwo=new ReceiveTwo();         //建立广播过滤器         intd=new IntentFilter();         //设定,接受哪个广播         intd.addAction("ces");    }    @Override  //Activity重新开始    protected void onResume() {        super.onResume();       registerReceiver(receiveTwo,intd);    }    @Override //Activity结束    protected void onDestroy() {        super.onDestroy();        unregisterReceiver(receiveTwo);    }------------------------------------------------------------ //内部类, 广播接受者    class ReceiveTwo extends BroadcastReceiver {         String pj="";        int anInt = 0;        @Override // 广播接受方法        public void onReceive(Context context, Intent intent) {    //当时,我指定接受的广播时            if("ces".equals(intent.getAction())){                    pj=textView.getText().toString();                pj+=intent.getStringExtra("fs");                textView.setText("");                textView.setText(pj);            }        }    }}
原创粉丝点击