我有一个运行并侦听套接字的服务。当它在套接字上接收到“格式”消息时,该服务将启动一个活动以显示视频帧,然后连续发送每个视频帧。
MyService正文:(为简洁起见省略了简化和错误处理)
public class MyService extends Service
{
....
while (_run)
{
Socket s = serverSocket.accept();
Thread connection_handler = new thread( new handleSocketConnection( s );
}
public class handleSocketConnection implements Runnable
{
boolean _run;
Socket s;
handleSocketConnection( Socket socket )
{
_run = true;
s = socket;
}
public void run( )
{
InputStream in = s.getInputStream();
byte bytes[] = new byte[100];
while( _run )
{
in.read( inbytes, 0, 100 );
if ( bytes[0] == 10 ) // if the first byte is a 10 this is a format message
{
bring_activity_foreward();
}
else // otherwise this is video frame data
{
send_activity_bytes( bytes, 100 );
}
}
}
public void bring_activity_foreward()
{
Intent show_intent = new Intent( this.MyActivity.class );
show_intent.setFlags( Intent.FLAG_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK );
startActivity( show_intent );
}
}
}
所有这些都很好,当我收到第一份格式消息并绘制视频帧时,我的活动表现得非常好。然而,发送视频帧数据的服务器将定期发送“格式消息”,以补偿显示、方向等的变化。如果我的活动已经在前台,格式消息调用bring_activity_foreward(它调用startActivity())会导致Activity立即接收到“onPause”,紧接着是“onResume”。由于我的活动在恢复时绑定到服务,并在暂停时解除绑定,因此我的活动不断地解除绑定和重新绑定到服务。这似乎不太高效。
public class ShowFrameActivity extends Activity
{
@Override
public void onCreate( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
setContentView( R.layout.viewframe );
}
@Override onResume( )
{
super.onResume();
bindToService();
}
@Override onPause( )
{
unbindFromService();
}
...
}
有没有办法向我的活动发送意图,以便如果它已经在前台,则不会执行“暂停 -> 恢复”操作?请记住,由于我的startActivity是从服务中调用的,因此必须包括“FLAG_ACTIVITY_NEW_TASK”。
感谢任何评论或建议。
-Z
onPause()
中必须释放相机(请参见10. <b>Important</b>:)。我使用的解决方法是在调用startActivity()
之前检查 Activity 是否在前台。我只需在onResume()
中将静态布尔字段设置为 true,并在onPause()
中将其设置为 false。我确信只有一个实例的 Activity 可以存在(它具有 <b>launchMode=singleTop</b> 并且不能从我的应用程序外部启动),我使用消息将数据从服务传递到 Activity。 - Alex Cohn