Android学习笔记:Activity跨进程调用service(3)

7.到此,service已经实现了。下面我们另外生成一个项目的Activity来bind这个service。

按照前面的步骤1. 我们生成一个activity。注意请用另外一个package name。Activity.java的文件内容为:

package com.pyk.client;

import com.pyk.les.IlongExistService;
import Android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;

public class MyActivity extends Activity {
 final String TAG = "MyActivity";
 final Intent myIntent = new Intent("com.pyk.les.IlongExistService");
 private boolean startedService = false;
 private IlongExistService leservice = null;
 ServiceConnection myServiceConnection = new ServiceConnection()
 {
  public void onServiceConnected(ComponentName name, IBinder service) {
   leservice = IlongExistService.Stub.asInterface(service);
  }

public void onServiceDisconnected(ComponentName name) {   
   leservice = null;
  }
  
 };
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);       
        setContentView(R.layout.main);
        //myIntent.setClass(this, LongExistService.class);
  startedService = bindService(new Intent("com.pyk.les.IlongExistService"), myServiceConnection, BIND_AUTO_CREATE);
  try {
            Log.i(TAG, "getCount value:" + leservice.getCount());
   Log.i(TAG, "getTime value:" + leservice.getTime());
        }catch (RemoteException ex)
        {}
    }

@Override
 protected void onDestroy() {
  if (startedService)
  {
   unbindService(myServiceConnection);
  }
  Log.i(TAG, "onDestroy");
  super.onDestroy();
 }
 
}

8. 将IlongExistService.aidl拷贝过来,连同package的目录一起拷贝。然后刷新一下Activity项目,就能在project explorer里看到了。 

这样,当Activity启动时,就会bind service并调用service的方法。Activity退出时会unbind。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwdjzz.html