Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/195.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 当从服务器接收到新数据(作为事件)时,如何从Running服务再次启动MainActivity(其应用程序被强制终止)?_Android_Service_Server - Fatal编程技术网

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。