从服务启动活动需要很长时间

我有一个Service ,当一个function给我,它会启动一个新的Activity但它需要5秒钟…

我读过关于这个issue ,我发现在StackOverflow这个例子“避免”这个错误..

 Intent intent = new Intent(this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0); try { pendingIntent.send(); } catch (PendingIntent.CanceledException e) { e.printStackTrace(); } 

但不幸的是,它并没有启动更快的Activity ,我不需要中立(如果可能的话更好),但我不想等待+5秒来启动新的Activity ,你有没有什么窍门可以避免这个?

我正在使用PendingIntent因为我发现那个说应该解决这个问题的人: 在没有5秒延迟的情况下按HOMEbutton之后从服务开始一个活动

注意

如果我按back button它自动启动,0延迟,但我正在按home button

Solutions Collecting From Web of "从服务启动活动需要很长时间"

我到处都不能评论,所以我把这个类似问题的解决scheme作为答案

多挖后,找出问题的原因。 显然这不是一个错误,它是一个function,它不允许服务或BroadcastReceivers按下主页button后最多5秒启动活动。 没有简单的方法来克服这一点。

更多信息请访问: https : //code.google.com/p/android/issues/detail?id = 4536

我用添加到正在运行的服务的窗口pipe理器的窗口replace了活动。 这不会造成任何延迟。

源代码链接Stackoverflow

首先,我们无法更新任何与UI相关的服务,既不会调用活动也不会更新任何UI元素,我也面临同样的问题。

然后,我使用EventBus库来交stream服务的UI元素下面是示例示例

 public class SendSPLocationService extends Service { Handler mHandler = new Handler(); Thread downloadThread; boolean isRunning = true; private VolleyHelper volleyHelper; @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public void onCreate() { // Toast.makeText(this, " MyService Created ", Toast.LENGTH_LONG).show(); volleyHelper = new VolleyHelper(this); } @Override public int onStartCommand(Intent intent, int flags, int startId) { final Timer t = new Timer(); t.schedule(new TimerTask() { @Override public void run() { Log.d("run: ", "service is running!"); try { EventBus.getDefault().post(new FutureJobEvent(false, error.networkResponse.statusCode, errorJson.getString("message"))); } catch (JSONException e) { e.printStackTrace(); } // t.cancel(); Log.d("run: ", "service is stopped!"); } }, 0, 5000); return START_STICKY; } } 

使用下面的代码触发事件观察..在活动/片段

 @Override public void onStart() { super.onStart(); if (!EventBus.getDefault().isRegistered(this)) EventBus.getDefault().register(this); } @Override public void onStop() { super.onStop(); if (EventBus.getDefault().isRegistered(this)) EventBus.getDefault().unregister(this); } @Subscribe(threadMode = ThreadMode.MAIN) public void onMessageEvent(TrackSPEvent event) { if (event.success) { startActivity(new Intent(this,MainActivity.class)); } } 

我用PendingIntent方法进行了testing,发现任何错误。 这似乎工作正常。 不过,作为参考,这里是我在我的最后尝试的:

 public class MyService extends Service { public static final String SERVICE_COMMAND = "COMMAND"; public static final String TAG = "MyService"; public static final int SERVICE_START = 0x01; public static final int START_ACTIVITY = 0x02; private class ServiceHandler extends Handler { public ServiceHandler(HandlerThread thread) { super(thread.getLooper()); } @Override public void handleMessage(Message msg) { switch (msg.what) { case START_ACTIVITY: Intent ActivityIntent = new Intent(getApplicationContext(), TestActivity.class); ActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, ActivityIntent, 0); try { pendingIntent.send(); } catch (PendingIntent.CanceledException e) { e.printStackTrace(); } Log.e(TAG, "Service started activity -> " + System.currentTimeMillis()); default: break; } super.handleMessage(msg); } } private HandlerThread mThread; private ServiceHandler mHandler; public MyService() { mThread = new HandlerThread("ServiceThread"); mThread.start(); mHandler = new ServiceHandler(mThread); } @Override public int onStartCommand(Intent intent, int flags, int startId) { int id = intent.getIntExtra(SERVICE_COMMAND, SERVICE_START); switch (id) { case START_ACTIVITY: Log.e(TAG, "onStartCommand Service -> " + System.currentTimeMillis()); mHandler.sendEmptyMessage(START_ACTIVITY); break; default: break; } return START_STICKY; } @Nullable @Override public IBinder onBind(Intent intent) { return null; } } 

活动代码:

 public class MainActivity extends AppCompatActivity { private static final String TAG = "Main"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.e(TAG, "onCreate main activity -> " + System.currentTimeMillis()); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); Intent intent = new Intent(this, MyService.class); startService(intent); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onPause() { super.onPause(); Log.e(TAG, "onPause main activity -> " + System.currentTimeMillis()); Intent intent = new Intent(this, MyService.class); intent.putExtra(MyService.SERVICE_COMMAND, MyService.START_ACTIVITY); startService(intent); } } 

你可以在你的结尾尝试相同的代码。 可能会有帮助。