两种服务(StartService 和bindService)

概念:
1、startService(Intent)通过这种方式开启的服务,执行的生命周期方法:
第一次调用startService的时候:onCreate→onStartCommand
再次调用startService的时候:只执行onStartCommand
2、想停止用startService开启的服务要使用stopService(Intent),stopService执行之后,Service会走onDestroy()方法,执行之后Service销毁,再次调用stopService没有反应
3、如果在Activity中通过startService方法开启一个服务,当Activity退出的时候Service不会销毁,依然在后台运行,只有手动调用stopService或者在应用管理器中关闭Service,服务才会销毁
4、通过startService可以提高应用的优先级

在MainActivity中代码*************
···
public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
public void start(View v){
    //使用显示意图开启service服务
    Intent service = new Intent();
    //通过方法开启服务
    startService(service);
}
public void stop(View v){
    Intent intent = new Intent();
    
}

}

···
在创建一个类 MyService 继承Sercive
-----------------代码如下-----------
···
public class MyService extends Service{

@Override
public IBinder onBind(Intent intent) {
Log.e("TAG", "onBind");
    return null;
}
@Override
public void onCreate() {
     Log.e("TAG", "onCreate");
    
    super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
     Log.e("TAG", "onStartCommand");
    return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
     Log.e("TAG", "onDestroy");
    super.onDestroy();
}

}

···
xml.---------------
···

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="开启服务" 
    android:onClick="start"
    />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="停止服务" 
    android:onClick="stop"
    />

</LinearLayout>
···
BindService--------------------------
1、开启服务时生命周期比较:
bindService onCreate→onBind(只会执行一次)
startService onCreate→onStartCommand(调用一次startService执行一次)
2、startService开启的服务跟Activity没有关系,bindService开启的服务,跟Activity之间不求同生,但求同死,Activity退出的时候必须通过unbindService关闭服务
3、startService结束的时候stopService可以调用多次,只有第一次调用的时候有效,bindService结束的时候unbindService只能调用一次,调用多次应用会抛异常
4、bindService的时候传入的第二个参数是ServiceConnection,只有当onBind方法返回不为空的时候才会调用onServiceConnected

布局中*****************

···
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="bind开启服务"
android:onClick="start"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="bind关闭服务"
android:onClick="stop"

    />
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="调用服务的方法" 
    
    android:onClick="method"
    />

···
在MainActivity中实现这三个方法
我们写一个类继承Service
···
package com.example.test23_bindsecevice;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class BindService extends Service{

@Override
public IBinder onBind(Intent intent) {
  Log.e("TAG", "onBind");
    return new MyBinder();
}

@Override
public void onCreate() {
Log.e("TAG", "onBind");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("TAG", "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.e("TAG", "onDestroy");
super.onDestroy();
}
public void showToast(String s){
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
public class MyBinder extends Binder{
public void method(String s){
showToast(s);
}
public void showToast2(String s){
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
}
}

···
在MainActivity中***********
···
public class MainActivity extends Activity {
private MyConnection conn;
MyBinder myBinder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onDestroy() {
super.onDestroy();
//把service关闭 解除跟当前Activiy的绑定
unbindService(conn);

}
public void start(View v){
     Intent service = new Intent(this,BindService.class);
     //通过绑定的方式开启service
      conn = new MyConnection();
      //使用bindService 开启反服务
      //参数 1. intent 包含要启动的service
      //2.   ServiceConnection接口 通过它可以接受服务开启或者停止的消息
      //3.开启服务时操作的选项 一般传入BIND_AUTO_CREATE自动创建service
     bindService(service, conn, BIND_AUTO_CREATE);//绑定存在自动创建
     
     
}
public void stop(View v){
    //使用bindService开启服务  要是用unbindService停止
    unbindService(conn);
}
public void method(View v){

// BindService service = new BindService();
// service.showToast("12112");
myBinder.method("dfdg");
myBinder.showToast2("4512") ;

}
private class MyConnection implements ServiceConnection{
    
    @Override//当服务与Activity 连接时建立
    public void onServiceConnected(ComponentName name, IBinder service) {
        //只有当service onbind方法返回值不为null 调用
        Log.e("TAG", "onServiceConnected");
         myBinder=(MyBinder) service;
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.e("TAG", "onServiceDisconnected");
        
    }
    
}

}

···
混合服务:
混合开启,混合关闭,

*************xml********
···
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="start开启"
android:onClick="start"
/>

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="stop关闭"
    android:onClick="stop" />

<Button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="bind开启" 
    android:onClick="bindstart"/>

<Button
    android:id="@+id/button4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="unbind关闭"
    android:onClick="unbind" />

···

;写一个类继承Service

************代码如下***************
···
public class MixStartService extends Service{

@Override
public IBinder onBind(Intent intent) {
 Log.e("TAG", "onBind");
    return new Binder();
}

@Override
public void onCreate() {
Log.e("TAG", "onCreate");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("TAG", "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.e("TAG", "onDestroy");
super.onDestroy();

}
}
···

在MainActivity中****************
···
public class MainActivity extends Activity {
MyConnection conn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//start方式
public void start(View v){
Intent service = new Intent(this,MixStartService.class);
startService(service);

}

public void  stop(View v){
    Intent service = new Intent(this,MixStartService.class);
  stopService(service);
}
//绑定方式

public void startbind(View v){
Intent service = new Intent(this,MixStartService.class);
conn=new MyConnection();

bindService(service, conn, BIND_AUTO_CREATE);

}
public void  unbind(View v){
    unbindService(conn);
}
private class MyConnection implements ServiceConnection{

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
   Log.e("TAG", "onServiceConnected");
        
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        
    }
    
}

}

···

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容