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

3. 打开LongExistService.java, 点击菜单 Source-> Override/implement Method.

选中onCreate(), onDestroy(), onStart(), onStartCommand(), onUnbind(). 

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

4. LongExistService.java文件内容为:

package com.pyk.les;

import Android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class LongExistService extends Service {
   
    public int getCount() {
        Log.d(TAG, "LongExistService::getCount");
        return 0;
    }

public String getTime() {
        java.util.Date date = new java.util.Date();       
        Log.d(TAG, "LongExistService::onCreate");
        return date.toLocaleString();
    }
   
    private final IlongExistService.Stub binder=new IlongExistService.Stub() {
        public int getCount() {
            Log.d(TAG, "IlongExistService::getCount");
            return LongExistService.this.getCount();
        }

public String getTime() {
            Log.d(TAG, "IlongExistService::getTime");
            return LongExistService2.this.getTime();
        }
    };
   
    final String TAG = "LongExistService";
   
    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate");
        super.onCreate();
    }

@Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy");
        super.onDestroy();
    }

@Override
    public void onStart(Intent intent, int startId) {
        Log.d(TAG, "onStart");
        super.onStart(intent, startId);
    }

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

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

@Override
    public void onRebind(Intent intent) {
        Log.d(TAG, "onRebind");
        super.onRebind(intent);
    }

@Override
    public IBinder onBind(Intent arg0) {
        Log.d(TAG, "onBind");
        return binder;
    }
}

5. 因为增加了AIDL的接口,我们需要先定义一个AIDL文件,比如IlongExistService.aidl.文件内容为:

package com.pyk.les;

 

interface IlongExistService {

int getCount();

String getTime();

}

这里必须是后缀为aidl,我试过用.java文件定义一个同样的接口,结果不能正常运行。所以这个看来是个必须起名为aidl文件的要求。

6.修改AndroidManifest.xml, 添加如下定义。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.pyk.les2" android:versionCode="1" android:versionName="1.0">
 <application android:label="Single Service">
  <service android:name=".LongExistService">
   <intent-filter>
    <action android:name="com.pyk.les.IlongExistService"></action>
   </intent-filter>
  </service>
 </application>
 <uses-sdk android:minSdkVersion="8" />
</manifest>  

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

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