Android:如果正在运行的服务启动活动B,则启动活动A.

时间:2014-12-17 19:52:10

标签: android android-activity

我遇到了麻烦,无法让它发挥作用。这是空主类别启动器活动的代码,如果服务未运行或用户未通过身份验证,则必须显示启动屏幕,否则启动会话活动。

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;

public class EntryPoint extends Activity {
    private IAppManager imService;

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {

            imService = ((IMService.IMBinder) service).getService();

            // this is not starting activity :(

            // Start converstion activity if service running and user ok
            if (imService.isUserAuthenticated() == true) {
                try {
                    Intent i = new Intent(EntryPoint.this, Conversations.class);
                    startActivity(i);
                    finish();

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }

        // this is not working

        // start login activity if service disconnected

        public void onServiceDisconnected(ComponentName className) {

            imService = null;

            try {
                Intent intent = new Intent(getBaseContext(), Splash.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                startActivity(intent);
                finish();

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Start and bind the imService
        startService(new Intent(EntryPoint.this, IMService.class));
    }

    @Override
    protected void onPause() {

        super.onPause();

        try {
            unbindService(mConnection);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {

        super.onResume();

        try {

            bindService(new Intent(EntryPoint.this, IMService.class),
                    mConnection, Context.BIND_AUTO_CREATE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

当我运行应用时,Conversations既未运行也未运行Splash活动,而是我看到空活动:(也没有错误,只有空EntryPoint活动运行应该实际启动其他活动之一。

有谁知道我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

很可能您的服务没有连接,因此无法与您的活动互动。

单独创建一个intent,然后在startService& bindService,而不是每次为startService&创建一个新的intent实例。 bindService。

另外,为什么要在onResume()上绑定服务?请查看此链接,了解为何可能尽量避免这种情况 - Binding to Service in onCreate() or in onResume()

Intent serviceIntent = new Intent(EntryPoint.this, IMService.class);
startService(serviceIntent);
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);