Class not found when unmarshalling & ProcessKiller: Process
本文处理Android 程序扫描u盘文件,当U盘拔出时导致应用被杀死问题
ProcessKiller: Process com.xxx.xxx.xxx (23174) has open file /storage/usb0/xxx
问题原因
u盘拔出系统杀死持有U盘句柄的进程
解决方案
开启新的进程进行u盘操作
@Override
public void onCreate() {
super.onCreate();
IncomingHandler incomingHandler = new IncomingHandler(this);
mMessenger = new Messenger(incomingHandler);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
static class IncomingHandler extends Handler {
WeakReference serviceWeakReference;
public IncomingHandler(xxx service){
serviceWeakReference = new WeakReference(service);
}
@Override
public void handleMessage(@NotNull Message msg) {
final Message clientMsg = Message.obtain(msg);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("result", xxxInfoList);
clientMsg.setData(bundle);
try {
clientMsg.replyTo.send(clientMsg);
} catch (RemoteException e) {
e.printStackTrace();
Log.i(TAG, "clientMsg.replyTo send exception : " + e.getMessage());
}
}
}
Client
Message msg = Message.obtain(null, Constants.RUN, 0, 0);
msg.replyTo = clientMessage;
sendMsg2Service(msg);
private void startService() {
Intent intent = new Intent(mContext, xxxService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mContext.startForegroundService(intent);
} else {
mContext.startService(intent);
}
mContext.bindService(intent, connection, Service.BIND_AUTO_CREATE);
}
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
mMessenger = new Messenger(iBinder);
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
mMessenger = null;
}
};
private void sendMsg2Service(Message message) {
try {
mMessenger.send(message);
} catch (RemoteException e) {
e.printStackTrace();
}
}
private void init(){
clientMessage = new Messenger(new ClientHandler(this));
}
static class ClientHandler extends Handler{
WeakReference serviceWeakReference;
ClientHandler(xxx musicService){
serviceWeakReference = new WeakReference(musicService);
}
@Override
public void handleMessage(@NonNull Message msg) {
Bundle bundle = msg.getData();
ArrayList xxx = bundle.getParcelableArrayList("result");
}
}
发现问题
Class not found when unmarshalling
处理如下
bundle.setClassLoader(xxxservice.getClassLoader());
总结
- 使用Messenger实现跨进程通讯
- 处理跨进程parcel 解析问题
- Android classloader相关知识