Android 当从服务器接收到新数据(作为事件)时,如何从Running服务再次启动MainActivity(其应用程序被强制终止)?
这是一个场景Android 当从服务器接收到新数据(作为事件)时,如何从Running服务再次启动MainActivity(其应用程序被强制终止)?,android,service,server,Android,Service,Server,这是一个场景 App is opened User clicks on a button that starts a service. (Service always is run in background and check recieving new data from server) User presses home key and then long presses home key and clears application from task list completely.
App is opened
User clicks on a button that starts a service.
(Service always is run in background and check recieving new data from server)
User presses home key and then long presses home key and clears application from task list completely.
Service continues to run, although app has closed.
我可以通过阅读以下链接确定该应用程序是否已被终止:
当从服务器接收到新数据(作为事件)时,如何从Running服务再次启动MainActivity(其应用程序被强制终止)?您可以广播一个动作,并使用
广播接收器
接收该动作,然后从广播接收器
的onReceive
方法启动main活动
:
public void onReceive(Context context, ...)
{
Intent intent = new Intent(context,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
或从服务使用:
Intent intent = new Intent(this,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
您可以广播一个动作,并使用
BroadCastReceiver
接收该动作,然后从BroadCastReceiver
的onReceive
方法启动MainActivity
:
public void onReceive(Context context, ...)
{
Intent intent = new Intent(context,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
或从服务使用:
Intent intent = new Intent(this,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
但我不使用从广播。我只从服务中使用。必须从广播中使用?@setareab不一定,您可以在服务中简单地调用startActivity(intent),但最好设置广播接收器。记住使用FLAG_ACTIVITY_NEW_TASK,因为您是从服务启动活动的,但在MainActivity被终止时我没有上下文。@对于不需要上下文的服务,只需使用startActivity,但此行在我的服务中有错误:Intent Intent=NEW Intent(MainActivity.class,Intent.FLAG_ACTIVITY_NEW_TASK);但我不使用从广播。我只从服务中使用。必须从广播中使用?@setareab不一定,您可以在服务中简单地调用startActivity(intent),但最好设置广播接收器。记住使用FLAG_ACTIVITY_NEW_TASK,因为您是从服务启动活动的,但在MainActivity被终止时我没有上下文。@对于不需要上下文的服务,只需使用startActivity,但此行在我的服务中有错误:Intent Intent=NEW Intent(MainActivity.class,Intent.FLAG_ACTIVITY_NEW_TASK);作为用户,我不希望应用程序意外弹出UI。作为用户,我不希望应用程序意外弹出UI。