您的位置:首页 > 移动开发 > Android开发

[转载]android service 使用以及aidl使用

2015-10-26 15:44 519 查看
service

将android:exported属性声明为false,则无论你在manifest文件中声明了什么样的过滤条件,这个service都只能为你自己私用。

 

1:service的启动方式

service 是一个在后台运行的服务。你所启动的这个service所做得工作最好在另一个线程中做。因为这个service的线程的工作将阻塞调用它的线程。
在service的onCreate函数中你可能需要启动一个线程来完成service需要干的工作

  public void onCreate() {

    // Start up the thread running the service.  Note that we create a

    // separate thread because the service normally runs in the process's

    // main thread, which we don't want to block.  We also make it

    // background priority so CPU-intensive work will not disrupt our UI.

    HandlerThread thread = new HandlerThread("ServiceStartArguments",

            Process.THREAD_PRIORITY_BACKGROUND);

    thread.start();

   

    // Get the HandlerThread's Looper and use it for our Handler 

    mServiceLooper = thread.getLooper();

    mServiceHandler = new ServiceHandler(mServiceLooper);

  }

 

创建和启动一个service有两种方式

Intent in = new Intent(***);

startService(in) 和 bindService(in)。

与上面相对应,停止一个service也有两种方式

stopService(in)  和 unbindService(in)。

但是不管一个service是如何启动的,它基本都是可以被客户端bind的,除非你禁止他这个功能。所以不要把start和bind看的过分分离

如果是本地的service 则 Intent in = new Intent(this,LocalService.class)。同时那个service要在manifest文件中标明自己的name

<service android:name = ".serviceA"/>

如果是非本地的service 则在Intent中指明就可以了Intent in= new Intent("com.test.A") 与此同时那个非本地的service也要在manifest文件中申明自己的name和intent-filter

    <service android:name = ".serviceA">

            <intent-filter>

               <action android:name="com.test.A"/>

               <category android:name="android.intent.category.DEFAULT" />

           </intent-filter>

        </service>

2:使用startService 和 stopService

这种启动和停止方式是比较简单的。只需要在调用Activity中直接写上就可以了。

2.1service客户端代码

调用service的客户端的activity的代码:

package com.D_activity;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

public class D_activity extends Activity {

    Button b;

    private boolean running =  false;

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

    //设置一个按钮来开启和关闭服务

        b=(Button)findViewById(R.id.button);

    }

    @Override

    protected void onResume() {

//指定一个Intent

       final Intent in = new Intent("com.test.A");

        super.onResume();

        b.setOnClickListener(new OnClickListener(){

            @Override

            public void onClick(View v) {

                if(running){

                    running = false;

        //关闭服务

                    stopService(in);

                    b.setText("start ");

                }

              
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: