ps这是service 优先级 防止被回收的方法
setForeground(true)
或者
startForeground(1, notification);
.要想访问一个远程服务里的方法 需要用到aidl (会自动在gen目录下生成java文件)
一 创建一个服务 这个服务里面有一个要被调用的方法.
package cn.itcast.remoteservice;
import android.app.IntentService;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.test.IsolatedContext;
public class RemoteService extends Service {
@Override
public IBinder onBind(Intent intent) {
return new MyBinder();
}
private class MyBinder extends IService.Stub{
@Override
public void callMethodInService() throws RemoteException {
sayHelloInService();
}
}
/**
* 服务里面的一个方法
*/
public void sayHelloInService(){
System.out.println("hello in service");
}
@Override
public void onCreate() {
System.out.println("remote service oncreate");
super.onCreate();
}
}
把.java的后缀名改成aidl 把接口里面定义的访问权限的修饰符都给删除
IService.aidl
package cn.itcast.remoteservice;
interface IService {
void callMethodInService();
}
三 定义一个mybinder对象 extends IService.Stub, 在onbind
方法里面把mybinder返回回去
private class MyBinder extends IService.Stub{
@Override
public void callMethodInService() throws RemoteException {
sayHelloInService();
}
}
另一个程序中的Activity: 这样这个程序中也要把 上面的那个aidl 复制进去
package cn.itcast.callremote;
import cn.itcast.remoteservice.IService;
import android.app.Activity;
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.view.View;
public class DemoActivity extends Activity {
IService iService;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = new Intent();
intent.setAction("cn.itcast.remoteservice");
bindService(intent, new MyConn(), BIND_AUTO_CREATE);
}
public void click(View view){
try {
// 调用了远程服务的方法
iService.callMethodInService();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class MyConn implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
iService = IService.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
}
}
这个方法会有一个参数 这个参数就是 MyBinder的对象
六 IService = IService.Stub.asInterface(myBinder)