我有一项服务,我想动态检查调用者是否具有启动此服务的必要权限。我注意到调用者ID始终是定义服务的应用程序,而不是使用该服务的应用程序的实际ID(我通过调用onStartCommand()中的getCallingUid()和getCallingPid()方法来确认。如果不在onStartCommand()中,我应该在哪里执行此检查?我应该怎么做呢?
public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("TAG", "uid: " + getCallingUid() + " pid: " + getCallingPid());
int hasPermission = checkCallingPermission(MainActivity.CUSTOM_PERMISSION);
if (hasPermission == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Created", Toast.LENGTH_SHORT).show();
}
return flags;
}
}
答案 0 :(得分:0)
实现这一目标的唯一方法是使用AIDL使用绑定服务。 Here是如何开始的。如果您在onBind中调用Binder.getCallingPid()
,则必须在您的界面的存根中调用它:
public class MyService extends Service {
public IBinder onBind(Intent intent) {
return mBinder;
}
private final IMyAidlInterface.Stub mBinder = new IMyAidlInterface.Stub() {
@Override
public void myMethod() {
//PID
int pid = Binder.getCallingPid();
Log.d("ITestService in AIDL", String.format("Calling pid in service: %d", pid));
}
};
}
这就是界面的样子:
interface IMyAidlInterface {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
void myMethod();
}