三种Service:应用内不可交互,可交互,应用间可交互(客户端,服务端AIDL)

客户端MainActivity:

public class MainActivity extends Activity {

 private Button button_one;
 private Button button_two;
 private Button button_three;
 private Button button_fore;
 private Button button_five;
 private Button button_one_stop;
 private Button button_two_stop;

 // 应用内不可交互的service,适合做后台服务,如网络下载(用户通过Intent传入Url到Service,推荐使用IntentService).
 private Intent myServiceIntent = null;

 // 应用内通信,如音乐播放器,在服务中控制播放器的播放、暂停、停止,在Activity中通过对服务操作控制播放器。
 private BindServiceTest bindService;
 private Intent myBindServiceIntent = null;
 private ServiceConnection con = new ServiceConnection() {

  /**
   * 服务所在进程被kill或是crash时系统调用,而不是unbindService时调用
   */
  @Override
  public void onServiceDisconnected(ComponentName name) {
   Toast.makeText(getApplicationContext(), "BindServiceTest Service disconnect",Toast.LENGTH_SHORT).show();
  }

  /**
   * 服务连接时调用,若已经连接不进行调用
   */
  @Override
  public void onServiceConnected(ComponentName name, IBinder service) {
   bindService = ((MyBinder) service).getService();
   Toast.makeText(getApplicationContext(),  "BindServiceTest Service Connect",Toast.LENGTH_SHORT).show();
   Toast.makeText(getApplicationContext(),
     "bindService.increaseCount======"
       + bindService.increaseCount(),Toast.LENGTH_SHORT).show();
   Toast.makeText(getApplicationContext(),  "bindService.getCount();======" + bindService.getCount(),Toast.LENGTH_SHORT).show();
  }
 };

 private MyAIDLInterface binder2 = null;
 private Intent myAIDLServiceIntent;
 private ServiceConnection con2 = new ServiceConnection() {

  @Override
  public void onServiceDisconnected(ComponentName name) {

  }

  @Override
  public void onServiceConnected(ComponentName name, IBinder service) {
   binder2 = MyAIDLInterface.Stub.asInterface(service);
  }
 };

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  button_one = (Button) findViewById(R.id.service_one);
  button_two = (Button) findViewById(R.id.service_two);
  button_three = (Button) findViewById(R.id.service_three);
  button_fore = (Button) findViewById(R.id.service_fore);
  button_five = (Button) findViewById(R.id.service_five);
  button_one_stop = (Button) findViewById(R.id.service_one_stop);
  button_two_stop = (Button) findViewById(R.id.service_two_stop);
  myServiceIntent = new Intent(this, MyService.class);
  myBindServiceIntent = new Intent(this, BindServiceTest.class);
  myAIDLServiceIntent = new Intent(
    "com.trinea.android.demo.remote.MyAIDLServiceAction");

  // 启动不可交互的service
  button_one.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    startService(myServiceIntent);

   }
  });
  button_one_stop.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    // 停止不可交互service
    stopService(myServiceIntent);
   }
  });
  // 启动应用内可交互的service
  button_two.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    bindService(myBindServiceIntent, con,
      MainActivity.this.BIND_AUTO_CREATE);
   }
  });
  button_two_stop.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    // 停止可交互service
    if (bindService != null) {
     unbindService(con);
     bindService = null;
    }
   }
  });
  // 启动应用间可交互的service
  button_three.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    // 服务绑定
    boolean result = bindService(myAIDLServiceIntent, con2,
      Context.BIND_AUTO_CREATE);
    if (!result) {
     binder2 = null;
     Toast.makeText(getApplicationContext(), "服务绑定失败。",
       Toast.LENGTH_SHORT).show();
    }
   }
  });
  // 得到应用间服务中属性值
  button_fore.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    try {
     if (binder2 != null) {
      Toast.makeText(getApplicationContext(),
        "Service count:" + binder2.getCount(),
        Toast.LENGTH_SHORT).show();
     } else {
      Toast.makeText(getApplicationContext(), "请先绑定服务。",
        Toast.LENGTH_SHORT).show();
     }
    } catch (Exception e) {
     // TODO: handle exception
    }
   }
  });
  // 解除应用间绑定服务。
  button_five.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    if (binder2 != null) {
     unbindService(con2);
     binder2 = null;
    }
   }
  });
 }

 @Override
 protected void onDestroy() {
  // TODO Auto-generated method stub
  super.onDestroy();
 }

}

不可交互Service:

public class MyService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this, "Service Create", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "Service Destroty", Toast.LENGTH_SHORT).show();
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "Service Start", Toast.LENGTH_SHORT).show();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

 

 

应用内可交互Service:

public class BindServiceTest extends Service {

    private int      count;
    private MyBinder myBinder = new MyBinder();

    @Override
    public void onCreate() {
     Toast.makeText(getApplicationContext(),"BindServiceTest Service onCreate",Toast.LENGTH_SHORT).show();
        count = 0;
        super.onCreate();
    }

    @Override
    public void onDestroy() {
     Toast.makeText(getApplicationContext(),"BindServiceTest Service onDestroy",Toast.LENGTH_SHORT).show();
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 服务被绑定时调用
     * 返回值用于让调用者和服务通信,传入ServiceConnection的public void onServiceConnected(ComponentName name, IBinder service)函数第二个参数
     */
    @Override
    public IBinder onBind(Intent intent) {
        return myBinder;
    }

    public int getCount() {
        return count;
    }

    public int increaseCount() {
        return ++count;
    }

    public int decreaseCount() {
        return --count;
    }

    public class MyBinder extends Binder {

        BindServiceTest getService() {
            return BindServiceTest.this;
        }
    }
}

 

应用间可交互AIDL:

package com.example.aidlservice;

interface MyAIDLInterface {

     int getCount();

     void setCount(int count);
}

 

 

应用间可交互service

服务端AIDL

package com.example.aidlservice;

interface MyAIDLInterface {

     int getCount();

     void setCount(int count);
}

 服务端service:

package com.example.aidlservice;

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

public class MyAIDLService extends Service {

 private int mCount;
 private MyAIDLInterface.Stub myBinder = new MyAIDLInterface.Stub() {

  @Override
  public void setCount(int count) throws RemoteException {
   mCount = count;
  }

  @Override
  public int getCount() throws RemoteException {
   return mCount;
  }
 };

 @Override
 public void onCreate() {
  mCount = 0;
  Toast.makeText(getApplicationContext(), "MyAIDLService onCreate",Toast.LENGTH_SHORT).show();
  super.onCreate();
 }

 @Override
 public void onDestroy() {
  Toast.makeText(getApplicationContext(), "MyAIDLService onDestroy",Toast.LENGTH_SHORT).show();
  super.onDestroy();
 }

 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
  Toast.makeText(getApplicationContext(),Integer.toString(mCount),Toast.LENGTH_SHORT).show();
  return super.onStartCommand(intent, flags, startId);
 }

 public int getCount() {
  return mCount;
 }

 /**
  * 服务被绑定时调用 返回值用于让调用者和服务通信,传入ServiceConnection的public void
  * onServiceConnected(ComponentName name, IBinder service)函数第二个参数
  */
 @Override
 public IBinder onBind(Intent intent) {
  return myBinder;
 }
}

 

更多相关文章

  1. android 客户端无法解析php服务端返回的json
  2. android 客户端与服务端的通信 发送get和post请求并获取数据
  3. android 与c#服务端DES加密不一致问题解决
  4. 用.Net打造一个移动客户端(Android/IOS)的服务端框架NHM(四)——Andr
  5. 【Android 开发】: Android客户端与服务端之间使用JSON交互数据
  6. 快速开发框架Afinal的使用(数据库操作,HTTP请求,网络图片加载,控件绑
  7. android差分更新之服务端
  8. Android从服务端获取json解析显示在客户端上面
  9. Android客户端采用Http 协议Post方式请求与服务端进行数据交互

随机推荐

  1. 升级Android内置apk版本
  2. Android开发环境配置简介
  3. 用于替代 Android(安卓)自带 Dialog 和 P
  4. Android(安卓)最全面试题汇总(问题+答案+
  5. 深入理解Android(安卓)WebView
  6. adb devices找不到设备
  7. Support v4 v7 v13: Android(安卓)Support
  8. android学习笔记-1
  9. Android(安卓)- 文本框的输入法控制和默
  10. Android性能调优工具TraceView介绍