允许服务时间来启动 [英] Allowing service time to start up

查看:215
本文介绍了允许服务时间来启动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想启用自动登录到我的应用程序,然而,这产生的问题是,该服务正在启动并绑定都被称为自动登录功能后:

  04-28 20:21:09.061 5427-5427 / com.example.feastapp I / PersonaManager:getPersonaService()名persona_policy
04-28 20:21:09.081 5427-5427 / com.example.feastapp V /自动登录测试:等待... 1/5 @ 268919454
04-28 20:21:14.086 5427-5427 / com.example.feastapp V /自动登录测试:等待... 2/5 @ 268924454
04-28 20:21:19.081 5427-5427 / com.example.feastapp V /自动登录测试:等待... 3/5 @ 268929454
04-28 20:21:24.096 5427-5427 / com.example.feastapp I / PersonaManager:getPersonaService()名persona_policy
04-28 20:21:24.176 5427-5427 / com.example.feastapp V / TEST GCM服务登录:服务是NULL
04-28 20:21:24.236 5427-5427 / com.example.feastapp D / dalvikvm:GC_FOR_ALLOC释放244K,17%免费6485K / 7812K,暂停为15ms,15ms的总
04-28 20:21:24.296 5427-5427 / com.example.feastapp D / dalvikvm:GC_FOR_ALLOC释放1069K,26%免费6881K / 9260K,暂停9ms的,10ms的总
04-28 20:21:24.376 5427-5427 / com.example.feastapp D / libEGL:加载/system/lib/egl/libEGL_mali.so
04-28 20:21:24.381 5427-5427 / com.example.feastapp D / libEGL:加载/system/lib/egl/libGLESv1_CM_mali.so
04-28 20:21:24.386 5427-5427 / com.example.feastapp D / libEGL:加载/system/lib/egl/libGLESv2_mali.so
04-28 20:21:24.391 5427-5427 / com.example.feastapp E /:设备驱动程序API匹配
    设备驱动API版本:23
    用户空间API版本:23
04-28 20:21:24.391 5427-5427 / com.example.feastapp E /:马里:版本=的Linux r3p2-01rel3 BUILD_DATE =周一2月10日15点44分10秒KST 2014年
04-28 20:21:24.446 5427-5427 / com.example.feastapp D / OpenGLRenderer:启用调试模式0
04-28 20:21:24.506 5427-5427 / com.example.feastapp V /服务:该服务连接

我在扩展应用类服务的启动给予了服务时间,但它仍然将启动自动日志功能条款被调用后。

该loggingin类:

 公共类LoggingIn延伸活动{    受保护的静态最终诠释NOT_CONNECTED_TO_SERVICE = 0;
    受保护的静态最终诠释FILL_BOTH_USERNAME_AND_PASSWORD = 1;
    公共静态最后弦乐AUTHENTICATION_FAILED =0;
    公共静态最后弦乐FRIEND_LIST =FRIEND_LIST;
    受保护的静态最终诠释MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT = 2;
    受保护的静态最终诠释NOT_CONNECTED_TO_NETWORK = 3;
    私人的EditText usernameText;
    私人的EditText passwordText;    私人的JSONObject resultObject;
    公共静态字符串userid = NULL;    私人经理imService;
    公共静态最终诠释SIGN_UP_ID = Menu.FIRST;
    公共静态最终诠释EXIT_APP_ID = Menu.FIRST + 1;    //对于GCM
    串REGID;
    Google云端通讯GCM;
    的AtomicInteger的msgId =新的AtomicInteger();
    共享preferences preFS;
    上下文语境;    公共静态最后弦乐EXTRA_MESSAGE =消息;
    公共静态最后弦乐PROPERTY_REG_ID =registration_id;
    私有静态最后弦乐PROPERTY_APP_VERSION =appVersion;
    私人最终静态INT PLAY_SERVICES_RESOLUTION_REQUEST = 9000;    私人ServiceConnection mConnection =新ServiceConnection(){
        公共无效onServiceConnected(组件名的className,服务的IBinder){
            imService =((MessagingService.IMBinder)服务).getService();
            Log.v(服务,服务通);
            如果(imService.isUserAuthenticated()==真){
                //意图I =新意图(LoggingIn.this,ListOfFriends.class);
                意图I =新意图(LoggingIn.this,MainActivity.class);
                startActivity(ⅰ);
                LoggingIn.this.finish();
            }
        }        公共无效onServiceDisconnected(组件名的className){
            Log.v(服务,服务断开);
            imService = NULL;
            Toast.makeText(LoggingIn.this,R.string.local_service_stopped,
                    Toast.LENGTH_SHORT).show();
        }
    };    / **
     *当第一次创建活动调用。
     * /
    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
              / *
               *启动并绑定imService
               * /
        bindService(新意图(LoggingIn.this,MessagingService.class)
                mConnection,Context.BIND_AUTO_CREATE);
        //启动乱射:
        。最后的请求队列请求队列= VolleySingleton.getsInstance()getRequestQueue();        //删除标题栏
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);        //删除通知栏
        。this.getWindow()setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);        //对于自动日志记录:
        如果(!SaveShared preference.getUserName(getApplicationContext())。的isEmpty()){            的for(int i = 0;我3;;我++){
                Log.v(自动登录TEST,
                        请稍候+(I + 1)+/ 5 @
                                + SystemClock.elapsedRealtime());
                尝试{
                    视频下载(5000);
                }赶上(InterruptedException的E){
                }            }            的setContentView(R.layout.feast_loading_splash_page);            最终字符串username = SaveShared preference.getUserName(getApplicationContext());            最终的字符串密码= SaveShared preference.getPassword(getApplicationContext());            Log.v(TEST GCM服务登录,共享preF用户名是+使用者名称+和密码+密码);            如果(imService == NULL){
                Log.v(TEST GCM服务登录,服务为空);
                Toast.makeText(getApplicationContext(),
                        R.string.not_connected_to_service,
                        Toast.LENGTH_LONG).show();
                //的ShowDialog(NOT_CONNECTED_TO_SERVICE);
                //返回;
            }否则如果(imService.isNetworkConnected()== FALSE){
                Log.v(TEST GCM服务登录,imService.isNetworkConnected()==假);
                Toast.makeText(getApplicationContext(),
                        R.string.not_connected_to_network,
                        Toast.LENGTH_LONG).show();
                //的ShowDialog(NOT_CONNECTED_TO_NETWORK);            }其他{                Log.v(TEST GCM服务登录,当imService不为空:共享preF用户名是+使用者名称+和密码+密码);                螺纹autoLoginThread =新主题(){
                    私人处理程序处理程序=新的处理程序();                    @覆盖
                    公共无效的run(){
                        字符串结果= NULL;                        尝试{
                            结果= imService.authenticateUser(
                                    userName.trim(),
                                    password.trim());
                        }赶上(UnsupportedEncodingException五){                            e.printStackTrace();
                        }
                        如果(结果== NULL
                                || result.equals(AUTHENTICATION_FAILED)){
                                      / *
                                       * Authenticatin失败,通知用户
                                       * /
                            handler.post(新的Runnable(){
                                公共无效的run(){
                                    Toast.makeText(
                                            getApplicationContext(),
                                            R.string.make_sure_username_and_password_correct,
                                            Toast.LENGTH_LONG).show();                                    //的ShowDialog(MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT);
                                }
                            });                        }其他{/ *
                                       *如果结果不等于身份验证失败,
                                       *结果等于朋友,组列表
                                       *用户0:是朋友,1:是团体
                                       * /                            handler.post(新的Runnable(){
                                公共无效的run(){
                                    意图I =新意图(LoggingIn.this,
                                            MainActivity.class);
                                    startActivity(ⅰ);
                                    LoggingIn.this.finish();                                }
                            });                        }                    }
                };
                autoLoginThread.start();            }        }        的setContentView(R.layout.loggin_in);
        的setContentView(R.layout.feast_login_page);
        //的setTitle(登录);        的ImageButton loginButton =(的ImageButton)findViewById(R.id.button1);        //所以不必手动登录,只要按一下按钮
        usernameText =(EditText上)findViewById(R.id.username);
        passwordText =(EditText上)findViewById(R.id.password);        loginButton.setOnClickListener(新OnClickListener(){
            公共无效的onClick(查看为arg0){
                如果(imService == NULL){
                    Toast.makeText(getApplicationContext(),
                            R.string.not_connected_to_service,
                            Toast.LENGTH_LONG).show();
                    //的ShowDialog(NOT_CONNECTED_TO_SERVICE);
                    返回;
                }否则如果(imService.isNetworkConnected()== FALSE){
                    Toast.makeText(getApplicationContext(),
                            R.string.not_connected_to_network,
                            Toast.LENGTH_LONG).show();
                    //的ShowDialog(NOT_CONNECTED_TO_NETWORK);                }否则如果(usernameText.length()大于0
                        &功放;&安培; passwordText.length()> 0){                    螺纹loginThread =新主题(){
                        私人处理程序处理程序=新的处理程序();                        @覆盖
                        公共无效的run(){
                            字符串结果= NULL;                            尝试{
                                结果= imService.authenticateUser(
                                        usernameText.getText()。的toString()。修剪()
                                        。passwordText.getText()的toString()修剪());
                            }赶上(UnsupportedEncodingException五){                                e.printStackTrace();
                            }
                            如果(结果== NULL
                                    || result.equals(AUTHENTICATION_FAILED)){
                                      / *
                                       * Authenticatin失败,通知用户
                                       * /
                                handler.post(新的Runnable(){
                                    公共无效的run(){
                                        Toast.makeText(
                                                getApplicationContext(),
                                                R.string.make_sure_username_and_password_correct,
                                                Toast.LENGTH_LONG).show();                                        //的ShowDialog(MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT);
                                    }
                                });                            }其他{                                      / *
                                       *如果结果不等于身份验证失败,
                                       *结果等于朋友,组列表
                                       *用户0:是朋友,1:是团体
                                       * /
                                handler.post(新的Runnable(){
                                    公共无效的run(){                                        //如果登录成功,然后保存
                                        //用户名和密码共享
                                        // preferences:                                        SaveShared preference.setUserName(
                                                getApplicationContext(),
                                                usernameText.getText()
                                                        的ToString());                                        SaveShared preference.setPassword(
                                                getApplicationContext(),
                                                passwordText.getText()
                                                        的ToString());                                        意图I =新意图(LoggingIn.this,
                                                MainActivity.class);
                                        startActivity(ⅰ);
                                        LoggingIn.this.finish();                                    }
                                });                            }                        }
                    };
                    loginThread.start();                }其他{
                          / *
                           *用户名或密码不填,提醒用户
                           * /
                    Toast.makeText(getApplicationContext(),
                            R.string.fill_both_username_and_password,
                            Toast.LENGTH_LONG).show();
                    //的ShowDialog(FILL_BOTH_USERNAME_AND_PASSWORD);
                }                //获取用户ID!
                JsonObjectRequest getUserId =新JsonObjectRequest(Request.Method.GET,
                        HTTP://+ Global.getFeastOnline()+/ getUserData /+ usernameText.getText()的toString()+以.json,((字符串)空)
                        新Response.Listener<&JSONObject的GT;(){
                            @覆盖
                            公共无效onResponse(JSONObject的响应){                                //解析JSON:
                                尝试{
                                    resultObject = response.getJSONObject(用户信息);
                                    用户id = resultObject.getString(ID);                                    Log.v(用户ID,用户ID是+用户id);                                }赶上(JSONException E){
                                    e.printStackTrace();
                                }                            }
                        },
                        新Response.ErrorListener(){
                            @覆盖
                            公共无效onErrorResponse(VolleyError错误){
                                Log.d(Error.Response,error.toString());
                            }
                        });                requestQueue.add(getUserId);            }
        });
    }    @覆盖
    保护对话框onCreateDialog(INT ID){
        整型消息= -1;
        开关(ID){
            案例NOT_CONNECTED_TO_SERVICE:
                消息= R.string.not_connected_to_service;
                打破;
            案例FILL_BOTH_USERNAME_AND_PASSWORD:
                消息= R.string.fill_both_username_and_password;
                打破;
            案例MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT:
                消息= R.string.make_sure_username_and_password_correct;
                打破;
            案例NOT_CONNECTED_TO_NETWORK:
                消息= R.string.not_connected_to_network;
                打破;
            默认:
                打破;
        }        如果(消息== -1){
            返回null;
        }其他{
            返回新AlertDialog.Builder(LoggingIn.this)
                    .setMessage(消息)
                    .setPositiveButton(R.string.OK,
                            新DialogInterface.OnClickListener(){
                                公共无效的onClick(DialogInterface对话框,
                                                    INT whichButton){
                                                    / *用户点击OK等做一些东西* /
                                }
                            })。创建();
        }
    }    @覆盖
    保护无效的onPause(){
        super.onPause();
        unbindService(mConnection);
    }    @覆盖
    保护无效onResume(){
        super.onResume();        bindService(新意图(LoggingIn.this,MessagingService.class)
                mConnection,Context.BIND_AUTO_CREATE);
    }    @覆盖
    公共布尔onCreateOptionsMenu(菜单菜单){
        布尔结果= super.onCreateOptionsMenu(菜单);        menu.add(0,SIGN_UP_ID,0,R.string.sign_up);
        menu.add(0,EXIT_APP_ID,0,R.string.exit_application);        返回结果;
    }    @覆盖
    公共布尔onMenuItemSelected(INT FEATUREID,菜单项项){        开关(item.getItemId()){
            案例SIGN_UP_ID:
                意图I =新意图(LoggingIn.this,SigningUp.class);
                startActivity(ⅰ);
                返回true;
            案例EXIT_APP_ID:                返回true;
        }        返回super.onMenuItemSelected(FEATUREID,项目);
    }}


解决方案

我张贴的 ServiceConnection 块内的自动登录code。问题是,该服务仅在的onCreate块之后连接,因此呼吁反对任何东西的时候总是NULL。

 私人ServiceConnection mConnection =新ServiceConnection(){
        公共无效onServiceConnected(组件名的className,服务的IBinder){
            imService =((MessagingService.IMBinder)服务).getService();
            Log.v(服务,服务通);            //允许自动登录!************ **************
            最终字符串username = SaveShared preference.getUserName(getApplicationContext());            最终的字符串密码= SaveShared preference.getPassword(getApplicationContext());            Log.v(TEST GCM服务登录,共享preF用户名是+使用者名称+和密码+密码);            //Log.v(\"TEST GCM服务登录,imService的值是:+ imService.toString());            如果(imService == NULL){
                Log.v(TEST GCM服务登录,服务为空);
                Toast.makeText(getApplicationContext(),
                        R.string.not_connected_to_service,
                        Toast.LENGTH_LONG).show();
                //的ShowDialog(NOT_CONNECTED_TO_SERVICE);
                //返回;
            }否则如果(imService.isNetworkConnected()== FALSE){
                Log.v(TEST GCM服务登录,imService.isNetworkConnected()==假);
                Toast.makeText(getApplicationContext(),
                        R.string.not_connected_to_network,
                        Toast.LENGTH_LONG).show();
                //的ShowDialog(NOT_CONNECTED_TO_NETWORK);            }其他{                Log.v(TEST GCM服务登录,当imService不为空:共享preF用户名是+使用者名称+和密码+密码);                螺纹autoLoginThread =新主题(){
                    私人处理程序处理程序=新的处理程序();                    @覆盖
                    公共无效的run(){
                        字符串结果= NULL;                        尝试{
                            结果= imService.authenticateUser(
                                    userName.trim(),
                                    password.trim());
                        }赶上(UnsupportedEncodingException五){                            e.printStackTrace();
                        }
                        如果(结果== NULL
                                || result.equals(AUTHENTICATION_FAILED)){
                                      / *
                                       * Authenticatin失败,通知用户
                                       * /
                            handler.post(新的Runnable(){
                                公共无效的run(){
                                    Toast.makeText(
                                            getApplicationContext(),
                                            R.string.make_sure_username_and_password_correct,
                                            Toast.LENGTH_LONG).show();                                    //的ShowDialog(MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT);
                                }
                            });                        }其他{/ *
                                       *如果结果不等于身份验证失败,
                                       *结果等于朋友,组列表
                                       *用户0:是朋友,1:是团体
                                       * /                            handler.post(新的Runnable(){
                                公共无效的run(){
                                    意图I =新意图(LoggingIn.this,
                                            MainActivity.class);
                                    startActivity(ⅰ);
                                    LoggingIn.this.finish();                                }
                            });                        }                    }
                };
                autoLoginThread.start();            }            如果(imService.isUserAuthenticated()==真){
                //意图I =新意图(LoggingIn.this,ListOfFriends.class);
                意图I =新意图(LoggingIn.this,MainActivity.class);
                startActivity(ⅰ);
                LoggingIn.this.finish();
            }
        }        公共无效onServiceDisconnected(组件名的className){            Log.v(服务,服务断开);
            imService = NULL;
            Toast.makeText(LoggingIn.this,R.string.local_service_stopped,
                    Toast.LENGTH_SHORT).show();
        }
    };

I wish to enable automatic login to my app, yet the problem that is arising is that the service is being started and bound after the automatic login features are being called:

04-28 20:21:09.061    5427-5427/com.example.feastapp I/PersonaManager﹕ getPersonaService() name persona_policy
04-28 20:21:09.081    5427-5427/com.example.feastapp V/AUTO LOGIN TEST﹕ Waiting... 1/5 @ 268919454
04-28 20:21:14.086    5427-5427/com.example.feastapp V/AUTO LOGIN TEST﹕ Waiting... 2/5 @ 268924454
04-28 20:21:19.081    5427-5427/com.example.feastapp V/AUTO LOGIN TEST﹕ Waiting... 3/5 @ 268929454
04-28 20:21:24.096    5427-5427/com.example.feastapp I/PersonaManager﹕ getPersonaService() name persona_policy
04-28 20:21:24.176    5427-5427/com.example.feastapp V/TEST GCM Service Login﹕ Service is NULL
04-28 20:21:24.236    5427-5427/com.example.feastapp D/dalvikvm﹕ GC_FOR_ALLOC freed 244K, 17% free 6485K/7812K, paused 15ms, total 15ms
04-28 20:21:24.296    5427-5427/com.example.feastapp D/dalvikvm﹕ GC_FOR_ALLOC freed 1069K, 26% free 6881K/9260K, paused 9ms, total 10ms
04-28 20:21:24.376    5427-5427/com.example.feastapp D/libEGL﹕ loaded /system/lib/egl/libEGL_mali.so
04-28 20:21:24.381    5427-5427/com.example.feastapp D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_mali.so
04-28 20:21:24.386    5427-5427/com.example.feastapp D/libEGL﹕ loaded /system/lib/egl/libGLESv2_mali.so
04-28 20:21:24.391    5427-5427/com.example.feastapp E/﹕ Device driver API match
    Device driver API version: 23
    User space API version: 23
04-28 20:21:24.391    5427-5427/com.example.feastapp E/﹕ mali: REVISION=Linux-r3p2-01rel3 BUILD_DATE=Mon Feb 10 15:44:10 KST 2014
04-28 20:21:24.446    5427-5427/com.example.feastapp D/OpenGLRenderer﹕ Enabling debug mode 0
04-28 20:21:24.506    5427-5427/com.example.feastapp V/Service﹕ The service is connected

I have the service startup in the extended application class to give the service time, yet it still starts after the auto log feature clause is called.

The loggingin class:

public class LoggingIn extends Activity {

    protected static final int NOT_CONNECTED_TO_SERVICE = 0;
    protected static final int FILL_BOTH_USERNAME_AND_PASSWORD = 1;
    public static final String AUTHENTICATION_FAILED = "0";
    public static final String FRIEND_LIST = "FRIEND_LIST";
    protected static final int MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT = 2;
    protected static final int NOT_CONNECTED_TO_NETWORK = 3;
    private EditText usernameText;
    private EditText passwordText;

    private JSONObject resultObject;
    public static String userId = null;

    private Manager imService;
    public static final int SIGN_UP_ID = Menu.FIRST;
    public static final int EXIT_APP_ID = Menu.FIRST + 1;

    // For GCM
    String regid;
    GoogleCloudMessaging gcm;
    AtomicInteger msgId = new AtomicInteger();
    SharedPreferences prefs;
    Context context;

    public static final String EXTRA_MESSAGE = "message";
    public static final String PROPERTY_REG_ID = "registration_id";
    private static final String PROPERTY_APP_VERSION = "appVersion";
    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            imService = ((MessagingService.IMBinder) service).getService();
            Log.v("Service", "The service is connected");


            if (imService.isUserAuthenticated() == true) {
                // Intent i = new Intent(LoggingIn.this, ListOfFriends.class);
                Intent i = new Intent(LoggingIn.this, MainActivity.class);
                startActivity(i);
                LoggingIn.this.finish();
            }
        }

        public void onServiceDisconnected(ComponentName className) {
            Log.v("Service", "The service is disconnected");
            imService = null;
            Toast.makeText(LoggingIn.this, R.string.local_service_stopped,
                    Toast.LENGTH_SHORT).show();
        }
    };

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
              /*
               * Start and bind the imService
               */
        bindService(new Intent(LoggingIn.this, MessagingService.class),
                mConnection, Context.BIND_AUTO_CREATE);


        // Initiate Volley:
        final RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();

        //Remove title bar
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);

        //Remove notification bar
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        // For auto logging in:
        if (!SaveSharedPreference.getUserName(getApplicationContext()).isEmpty()) {

            for (int i = 0; i < 3; i++) {
                Log.v("AUTO LOGIN TEST",
                        "Waiting... " + (i + 1) + "/5 @ "
                                + SystemClock.elapsedRealtime());
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                }

            }

            setContentView(R.layout.feast_loading_splash_page);

            final String userName = SaveSharedPreference.getUserName(getApplicationContext());

            final String password = SaveSharedPreference.getPassword(getApplicationContext());

            Log.v("TEST GCM Service Login", "SharedPref Username is " + userName + " and password " + password);

            if (imService == null) {
                Log.v("TEST GCM Service Login", "Service is NULL");
                Toast.makeText(getApplicationContext(),
                        R.string.not_connected_to_service,
                        Toast.LENGTH_LONG).show();
                // showDialog(NOT_CONNECTED_TO_SERVICE);
                //return;
            } else if (imService.isNetworkConnected() == false) {
                Log.v("TEST GCM Service Login", "imService.isNetworkConnected() == false");
                Toast.makeText(getApplicationContext(),
                        R.string.not_connected_to_network,
                        Toast.LENGTH_LONG).show();
                // showDialog(NOT_CONNECTED_TO_NETWORK);

            } else {

                Log.v("TEST GCM Service Login", "When imService is not null: SharedPref Username is " + userName + " and password " + password);

                Thread autoLoginThread = new Thread() {
                    private Handler handler = new Handler();

                    @Override
                    public void run() {
                        String result = null;

                        try {
                            result = imService.authenticateUser(
                                    userName.trim(),
                                    password.trim());
                        } catch (UnsupportedEncodingException e) {

                            e.printStackTrace();
                        }
                        if (result == null
                                || result.equals(AUTHENTICATION_FAILED)) {
                                      /*
                                       * Authenticatin failed, inform the user
                                       */
                            handler.post(new Runnable() {
                                public void run() {
                                    Toast.makeText(
                                            getApplicationContext(),
                                            R.string.make_sure_username_and_password_correct,
                                            Toast.LENGTH_LONG).show();

                                    // showDialog(MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT);
                                }
                            });

                        } else {                                      /*
                                       * if result not equal to authentication failed,
                                       * result is equal to friend and group list of
                                       * the user 0: is for friends, 1: is for groups
                                       */

                            handler.post(new Runnable() {
                                public void run() {
                                    Intent i = new Intent(LoggingIn.this,
                                            MainActivity.class);
                                    startActivity(i);
                                    LoggingIn.this.finish();

                                }
                            });

                        }

                    }
                };
                autoLoginThread.start();

            }

        }

        setContentView(R.layout.loggin_in);
        setContentView(R.layout.feast_login_page);
        //setTitle("Login");

        ImageButton loginButton = (ImageButton) findViewById(R.id.button1);

        // So don't need to log in manually, just click the button
        usernameText = (EditText) findViewById(R.id.username);
        passwordText = (EditText) findViewById(R.id.password);

        loginButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                if (imService == null) {
                    Toast.makeText(getApplicationContext(),
                            R.string.not_connected_to_service,
                            Toast.LENGTH_LONG).show();
                    // showDialog(NOT_CONNECTED_TO_SERVICE);
                    return;
                } else if (imService.isNetworkConnected() == false) {
                    Toast.makeText(getApplicationContext(),
                            R.string.not_connected_to_network,
                            Toast.LENGTH_LONG).show();
                    // showDialog(NOT_CONNECTED_TO_NETWORK);

                } else if (usernameText.length() > 0
                        && passwordText.length() > 0) {

                    Thread loginThread = new Thread() {
                        private Handler handler = new Handler();

                        @Override
                        public void run() {
                            String result = null;

                            try {
                                result = imService.authenticateUser(
                                        usernameText.getText().toString().trim(),
                                        passwordText.getText().toString().trim());
                            } catch (UnsupportedEncodingException e) {

                                e.printStackTrace();
                            }
                            if (result == null
                                    || result.equals(AUTHENTICATION_FAILED)) {
                                      /*
                                       * Authenticatin failed, inform the user
                                       */
                                handler.post(new Runnable() {
                                    public void run() {
                                        Toast.makeText(
                                                getApplicationContext(),
                                                R.string.make_sure_username_and_password_correct,
                                                Toast.LENGTH_LONG).show();

                                        // showDialog(MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT);
                                    }
                                });

                            } else {

                                      /*
                                       * if result not equal to authentication failed,
                                       * result is equal to friend and group list of
                                       * the user 0: is for friends, 1: is for groups
                                       */
                                handler.post(new Runnable() {
                                    public void run() {

                                        // If log in successful, then save
                                        // username and password to shared
                                        // preferences:

                                        SaveSharedPreference.setUserName(
                                                getApplicationContext(),
                                                usernameText.getText()
                                                        .toString());

                                        SaveSharedPreference.setPassword(
                                                getApplicationContext(),
                                                passwordText.getText()
                                                        .toString());

                                        Intent i = new Intent(LoggingIn.this,
                                                MainActivity.class);
                                        startActivity(i);
                                        LoggingIn.this.finish();

                                    }
                                });

                            }

                        }
                    };
                    loginThread.start();

                } else {
                          /*
                           * Username or Password is not filled, alert the user
                           */
                    Toast.makeText(getApplicationContext(),
                            R.string.fill_both_username_and_password,
                            Toast.LENGTH_LONG).show();
                    // showDialog(FILL_BOTH_USERNAME_AND_PASSWORD);
                }

                // GET the users id!!
                JsonObjectRequest getUserId = new JsonObjectRequest(Request.Method.GET,
                        "http://" + Global.getFeastOnline() + "/getUserData/" + usernameText.getText().toString() + ".json", ((String) null),
                        new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {

                                // Parse the JSON:
                                try {
                                    resultObject = response.getJSONObject("userInfo");
                                    userId = resultObject.getString("id");

                                    Log.v("USER ID", "The user id is " + userId);

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

                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Log.d("Error.Response", error.toString());
                            }
                        });

                requestQueue.add(getUserId);

            }
        });
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        int message = -1;
        switch (id) {
            case NOT_CONNECTED_TO_SERVICE:
                message = R.string.not_connected_to_service;
                break;
            case FILL_BOTH_USERNAME_AND_PASSWORD:
                message = R.string.fill_both_username_and_password;
                break;
            case MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT:
                message = R.string.make_sure_username_and_password_correct;
                break;
            case NOT_CONNECTED_TO_NETWORK:
                message = R.string.not_connected_to_network;
                break;
            default:
                break;
        }

        if (message == -1) {
            return null;
        } else {
            return new AlertDialog.Builder(LoggingIn.this)
                    .setMessage(message)
                    .setPositiveButton(R.string.OK,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int whichButton) {
                                                    /* User clicked OK so do some stuff */
                                }
                            }).create();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unbindService(mConnection);
    }

    @Override
    protected void onResume() {
        super.onResume();

        bindService(new Intent(LoggingIn.this, MessagingService.class),
                mConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        boolean result = super.onCreateOptionsMenu(menu);

        menu.add(0, SIGN_UP_ID, 0, R.string.sign_up);
        menu.add(0, EXIT_APP_ID, 0, R.string.exit_application);

        return result;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {

        switch (item.getItemId()) {
            case SIGN_UP_ID:
                Intent i = new Intent(LoggingIn.this, SigningUp.class);
                startActivity(i);
                return true;
            case EXIT_APP_ID:

                return true;
        }

        return super.onMenuItemSelected(featureId, item);
    }

}

解决方案

I posted the auto login code within the ServiceConnection block. The issue was that the service is connected only after the onCreate block, therefore it was always NULL when calling anything against it.

private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            imService = ((MessagingService.IMBinder) service).getService();
            Log.v("Service", "The service is connected");

            // Allowing autologin!!**********************************************************
            final String userName = SaveSharedPreference.getUserName(getApplicationContext());

            final String password = SaveSharedPreference.getPassword(getApplicationContext());

            Log.v("TEST GCM Service Login", "SharedPref Username is " + userName + " and password " + password);

            //Log.v("TEST GCM Service Login", "The value of imService is: " + imService.toString());

            if (imService == null) {
                Log.v("TEST GCM Service Login", "Service is NULL");
                Toast.makeText(getApplicationContext(),
                        R.string.not_connected_to_service,
                        Toast.LENGTH_LONG).show();
                // showDialog(NOT_CONNECTED_TO_SERVICE);
                //return;
            } else if (imService.isNetworkConnected() == false) {
                Log.v("TEST GCM Service Login", "imService.isNetworkConnected() == false");
                Toast.makeText(getApplicationContext(),
                        R.string.not_connected_to_network,
                        Toast.LENGTH_LONG).show();
                // showDialog(NOT_CONNECTED_TO_NETWORK);

            } else {

                Log.v("TEST GCM Service Login", "When imService is not null: SharedPref Username is " + userName + " and password " + password);

                Thread autoLoginThread = new Thread() {
                    private Handler handler = new Handler();

                    @Override
                    public void run() {
                        String result = null;

                        try {
                            result = imService.authenticateUser(
                                    userName.trim(),
                                    password.trim());
                        } catch (UnsupportedEncodingException e) {

                            e.printStackTrace();
                        }
                        if (result == null
                                || result.equals(AUTHENTICATION_FAILED)) {
                                      /*
                                       * Authenticatin failed, inform the user
                                       */
                            handler.post(new Runnable() {
                                public void run() {
                                    Toast.makeText(
                                            getApplicationContext(),
                                            R.string.make_sure_username_and_password_correct,
                                            Toast.LENGTH_LONG).show();

                                    // showDialog(MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT);
                                }
                            });

                        } else {                                      /*
                                       * if result not equal to authentication failed,
                                       * result is equal to friend and group list of
                                       * the user 0: is for friends, 1: is for groups
                                       */

                            handler.post(new Runnable() {
                                public void run() {
                                    Intent i = new Intent(LoggingIn.this,
                                            MainActivity.class);
                                    startActivity(i);
                                    LoggingIn.this.finish();

                                }
                            });

                        }

                    }
                };
                autoLoginThread.start();

            }

            if (imService.isUserAuthenticated() == true) {
                // Intent i = new Intent(LoggingIn.this, ListOfFriends.class);
                Intent i = new Intent(LoggingIn.this, MainActivity.class);
                startActivity(i);
                LoggingIn.this.finish();
            }
        }

        public void onServiceDisconnected(ComponentName className) {

            Log.v("Service", "The service is disconnected");
            imService = null;
            Toast.makeText(LoggingIn.this, R.string.local_service_stopped,
                    Toast.LENGTH_SHORT).show();
        }
    };

这篇关于允许服务时间来启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆