android Service总结

本文介绍 Android 中 Service 的两种启动方式:通过 startService 和 bindService 方法,并详细阐述了这两种方式的区别及其生命周期回调方法。此外,还展示了如何在 Activity 和 Service 之间建立通信。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建Service有两种方式

        1.通过Context的startServive()方法:访问者与Service之间没有关联,即使访问者退出了,Service仍然运行。

        2.通过Context的bindService()方法:使用该方法启动Service,访问者与Service绑定在一起,访问者一旦退出,Service也就终止。
如果某个程序组件需要在运行时向用户呈现某种界面,或者该程序需要于用户交互,就需要使用Activity,否则就应该考虑使用Service了,
abstract IBinder onBind(Intent intent):该方法返回一个IBinder对象,应用程序可通过该对象与Service组件通信。
void onCreate():该Service第一次被创建后将立即回调该方法。
void onDestory():该Serice被关闭后回调此方法
int onStartCommand(Intent intent, int flags, int startId):每次客户端调用startService(Intent)方法启动该Service时都会回调该方法。
boolean onUnBind(Intent intent):当该Service上绑定的所有客户端都断开链接时将会回调该方法。
每次当Service被创建时会回调onCreate方法,每次Service被启动时会调用Onstar放法-- 多次启动一个已有的Service组件将不会调用onCreate方法,但每次启动时都会调用onStartCommand方法
bindService(Intent service,ServiceConnection conn,int flags),该方法解释如下:

service:该参数通过Intent指定启动的Service。

conn:该对象用于监听访问者与ServiceConnection之间的连接情况,当访问者与Service之间链接成功时将回调该ServiceConnection对象的OnServiceConnected(ComponentName name,IBinder service)
方法;当访问者与Service之间断开链接时将回调该ServiceConnection对象的onServiceDisconnected(ComponentName name)方法
flags:指定绑定时是否自动创建Service(如果Serice还未创建)。该参数可指定为0(不自动创建)或BIND_AUTO_CREATE(自动创建)。
OnServiceConnected中有一个IBinder对象,该对象即可实现与被绑定Service之间的通信。
         当开发Service类时,该Service类必须提供一个IBinder onBind(Intent intent)方法,在绑定本地Service的情况下,onBinder(Intentet intent)方法所返回的IBinder对象将会传给ServiceConnection对象里onServiceConnected(ComponentName name,IBinder service)方法的service参数,这样访问者就可以通过该IBinder对象与Service进行通信

第一种启动 方式:Activity

public class MainActivity extends ActionBarActivity {
    Button start,stop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        start = (Button) findViewById(R.id.start);
        stop = (Button) findViewById(R.id.stop);
        final Intent intent = new Intent();
        intent.setAction("org.crazyit.service.FIRST_SERVICE");
        intent.setPackage(MainActivity.this.getPackageName());
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                startService(intent);
            }
        });
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                stopService(intent);
            }
        });
    }


}
Service

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

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        Log.d("asdf","=====msg===");
        //throw new UnsupportedOperationException("Not yet implemented");
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("asdf","Service is created");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("asdf","Service is onStartcreated");
        return START_STICKY;//用于显示启动和停止service
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("asdf", "Service is Destoryed");
    }
}
第二种启动方式:Service

public class BindService extends Service {
    private int count;
    private  boolean quit;
    private IBinder binder;
    private  String name;
   /* private CatBinder catBinder;
    public  class CatBinder extends ICat.Stub{


    }*/

    public class MyBinder extends Binder{
        public void setName(String s){
            BindService.this.name =s;
        }
        public String getName(){
            return BindService.this.name;
        }
        public int getCount(){
            return count;
        }
    }

    public BindService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.d("asdf", "=======onBind===========");
       return binder;
    }

    @Override
    public void onCreate() {
        binder = new MyBinder();
        super.onCreate();
        new Thread(){
            public void run(){
                while (!quit){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    count++;
                }
            }
        }.start();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d("asdf","=======onUnbind===========");
        return super.onUnbind(intent);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.quit = quit;
        Log.d("asdf","=======onDestroy===========");
    }
}
Activity:

public class MainActivity extends Activity {
    Button bind,unbind,getServiceStatus;
    BindService.MyBinder binder;
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d("asdf","=======onServiceConnection===========");
            binder = (BindService.MyBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d("asdf","=========onServiceDisconnected===========");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bind = (Button) findViewById(R.id.bind);
        unbind = (Button) findViewById(R.id.unbind);
        getServiceStatus = (Button) findViewById(R.id.getServiceStatus);
        final Intent intent = new Intent(MainActivity.this,BindService.class);
        bindService(intent, conn, Service.BIND_AUTO_CREATE);
        bind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binder.setName("AAAAAAAAAAAAAAAAA");
                TextView textView = new TextView(MainActivity.this);
                Log.d("asdf", "====+binder+=====");
                textView.setText(binder.getName() + binder.getCount());
                LinearLayout layout = (LinearLayout) findViewById(R.id.line);
                layout.setOrientation(LinearLayout.VERTICAL);
                layout.addView(textView);
            }
        });


        unbind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                unbindService(conn);
            }
        });
        getServiceStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "Servicecount值为:" + binder.getCount(), Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值