服务启动活动时间过长

时间:2017-11-05 16:59:46

标签: android android-intent android-activity service

我有一个Service,当一个函数给我true时,它会启动一个新的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秒来启动新的{{ 1}},你有什么技巧可以避免这种情况吗?

我正在使用Activity,因为我发现那个人说它应该解决这个问题: Starting an activity from a service after HOME button pressed without the 5 seconds delay

注意

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

3 个答案:

答案 0 :(得分:7)

我无法在任何地方发表评论,所以我将这个类似问题的解决方案作为答案

  经过多次挖掘,找出问题的原因。显然地   它不是一个错误,它是一个不允许服务或   BroadcastReceivers可在家中播放长达5秒的活动   按下按钮。没有简单的方法来克服这一点。

     

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

     

我用添加到窗口管理器的Window替换了活动   正在运行的服务。这不会造成任何延误。

来源链接Stackoverflow

答案 1 :(得分:3)

我们首先无法更新服务中任何与UI相关的内容,既没有调用活动也没有更新任何UI元素,我也遇到了同样的问题。

然后我使用 EventBus 库来传达来自服务的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));
 }
 }

答案 2 :(得分:0)

我使用PendingIntent方法进行测试,但无法发现任何错误。这似乎工作正常。但是,作为参考,这是我在最后尝试的内容:

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);
    }
}

您可以尝试使用相同的代码。可能会有所帮助。