Android服务没有停止

时间:2012-10-30 09:14:57

标签: android service android-intent forceclose

在我登录时的应用程序中,我启动了UpdaterService.class。当我退出时,应用程序已成功注销。但是当我再次登录时,它首先提供 FORCE CLOSE ,第二次当我再次登录 AFTER FORCE CLOSE 时,它运行正常。我无法弄清楚背后的问题。

更新程序服务

public class UpdaterService extends Service implements InvitationListener {
    private static XMPPConnection connection;
    String Friend;
    String user = "";
    String senderName ="";
    String subID="";
    int subscription = 1;


    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        // Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
        super.onCreate();
    }   

    @Override
    public void onDestroy() {


        super.onDestroy();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        showToast("My Service Started", 0);
        connection = getConnection();
        if (connection.isConnected()) {
            final Roster roster = connection.getRoster();
            RosterListener r1 = new RosterListener() {

                @Override
                public void presenceChanged(Presence presence) {
                    // TODO Auto-generated method stub

                       //notification("changed");

                }

                @Override
                public void entriesUpdated(Collection<String> arg0) {
                    // TODO Auto-generated method stub
                    //notification("entriesUpdated");
                }

                @Override
                public void entriesDeleted(Collection<String> arg0) {
                    // TODO Auto-generated method stub
                    //notification("entriesDeleted");
                }


                @Override
                public void entriesAdded(Collection<String> arg0) {
                    // TODO Auto-generated method stub
                    Iterator<String> it = arg0.iterator();
                    if (it.hasNext()) {
                        user = it.next();
                    }
                    /*RosterEntry entry = roster.getEntry(user);
                    if(entry.getType().toString().equalsIgnoreCase("to")){
                        int index_of_Alpha = user.indexOf("@");
                        String subID = user.substring(0, index_of_Alpha);

                        notification("Hi,"+subID+" wants to add you");
                    }       */      
                }
            };

            if (roster != null) {
                System.out.println("subscription going on");
                roster.addRosterListener(r1);
            }

        } else {
            showToast("Connection lost-", 0);
        }


        //Group Chat Invitation
        MultiUserChat.addInvitationListener(connection, new InvitationListener() {

            @Override
            public void invitationReceived(Connection arg0, String arg1, String arg2,
                    String arg3, String arg4, Message arg5) {
                // TODO Auto-generated method stub

                System.out.println("Received");
                notification("Invitation Received");

            }
        });

        //presence check
        connection.addPacketListener(new PacketListener() {

            @Override
            public void processPacket(Packet arg0) {
                // TODO Auto-generated method stub

                Presence presence = (Presence)arg0;
                if(presence.getType().equals(Presence.Type.subscribe))
                {

                    user = presence.getFrom();
                    int index_of_Alpha = user.indexOf("@");
                    subID = user.substring(0, index_of_Alpha);

                    /*Roster roster = connection.getRoster();
                    RosterEntry entry = roster.getEntry(user);*/


                        notification("Hi,"+subID+" wants to add you");

                }

                if(presence.getType().equals(Presence.Type.subscribed)){

                    Roster roster = connection.getRoster();
                    RosterEntry entry = roster.getEntry(user);
                    if(entry.getType().toString().equalsIgnoreCase("to")){
                        int index_of_Alpha = user.indexOf("@");
                        subID = user.substring(0, index_of_Alpha);




                }

                }
            }
        },new PacketTypeFilter(Presence.class));

        PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
        final PacketCollector collector = connection.createPacketCollector(filter);
        connection.addPacketListener(new PacketListener() {

            @Override
            public void processPacket(Packet packet) {
                // TODO Auto-generated method stub
                //notification(packet.getFrom());
                packet = collector.nextResult();
                Message message = (Message)packet;
                senderName = packet.getFrom();

                int alphaPOS = senderName.indexOf("@");
                String subSenderName = senderName.substring(0,alphaPOS); 



                notificationforChat(subSenderName+": "+message.getBody(),packet.getFrom().toString());
            }
        }, filter);

         /*while (true) {
                Packet packet = collector.nextResult();
                if (packet instance of Message) {
                    Message message = (Message) packet;
                    if (message != null && message.getBody() != null)
                        System.out.println("Received message from "
                                + packet.getFrom() + " : "
                                + (message != null ? message.getBody() : "NULL"));

                    notification(""+message.getBody());

                }
            }*/

    }

    protected void showToast(String msg, int time) {
        Toast.makeText(this, msg, time).show();
    }

    private XMPPConnection getConnection() {
        return CCMStaticVariable.CommonConnection;
    }

以下是停止服务的代码( LOGOUT 代码)

if (CCMStaticVariable.CommonConnection.isConnected()) {
                    //super.onBackPressed();

                    final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);      
                    alertDialog.setTitle("CCM Logout");
                    alertDialog.setMessage("Are you sure you want to logout?");
                    alertDialog.setIcon(R.drawable.ic_launcher);

                    //Ok button for Logout
                    alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub

                            CCMStaticVariable.CommonConnection.disconnect();

                            Intent serviceIntent = new Intent(UserMenuActivity.this,UpdaterService.class);
                            stopService(serviceIntent);

                            //CCMStaticVariable.CommonConnection.removeConnectionListener(arg0);
                            finish();

                        }
                    });

logcat的

10-30 14:53:00.189: D/dalvikvm(944): GC_CONCURRENT freed 919K, 55% free 3013K/6663K, external 2582K/2706K, paused 8ms+3ms
10-30 14:53:01.248: W/dalvikvm(944): threadid=10: thread exiting with uncaught exception (group=0x40015560)
10-30 14:53:01.278: E/AndroidRuntime(944): FATAL EXCEPTION: AsyncTask #2
10-30 14:53:01.278: E/AndroidRuntime(944): java.lang.RuntimeException: An error occured while executing doInBackground()
10-30 14:53:01.278: E/AndroidRuntime(944):  at android.os.AsyncTask$3.done(AsyncTask.java:200)
10-30 14:53:01.278: E/AndroidRuntime(944):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
10-30 14:53:01.278: E/AndroidRuntime(944):  at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
10-30 14:53:01.278: E/AndroidRuntime(944):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
10-30 14:53:01.278: E/AndroidRuntime(944):  at java.util.concurrent.FutureTask.run(FutureTask.java:138)
10-30 14:53:01.278: E/AndroidRuntime(944):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
10-30 14:53:01.278: E/AndroidRuntime(944):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
10-30 14:53:01.278: E/AndroidRuntime(944):  at java.lang.Thread.run(Thread.java:1019)
10-30 14:53:01.278: E/AndroidRuntime(944): Caused by: java.lang.NullPointerException
10-30 14:53:01.278: E/AndroidRuntime(944):  at org.jivesoftware.smackx.muc.MultiUserChat$1.connectionCreated(MultiUserChat.java:114)
10-30 14:53:01.278: E/AndroidRuntime(944):  at org.jivesoftware.smack.XMPPConnection.initConnection(XMPPConnection.java:607)
10-30 14:53:01.278: E/AndroidRuntime(944):  at org.jivesoftware.smack.XMPPConnection.connectUsingConfiguration(XMPPConnection.java:556)
10-30 14:53:01.278: E/AndroidRuntime(944):  at org.jivesoftware.smack.XMPPConnection.connect(XMPPConnection.java:984)
10-30 14:53:01.278: E/AndroidRuntime(944):  at com.cipl.CCM.frontend.XMPPConn.checkXMPPConnection(XMPPConn.java:51)
10-30 14:53:01.278: E/AndroidRuntime(944):  at com.cipl.CCM.frontend.LoginActivity$LoginUserTask.doInBackground(LoginActivity.java:135)
10-30 14:53:01.278: E/AndroidRuntime(944):  at com.cipl.CCM.frontend.LoginActivity$LoginUserTask.doInBackground(LoginActivity.java:1)
10-30 14:53:01.278: E/AndroidRuntime(944):  at android.os.AsyncTask$2.call(AsyncTask.java:185)
10-30 14:53:01.278: E/AndroidRuntime(944):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
10-30 14:53:01.278: E/AndroidRuntime(944):  ... 4 more
10-30 14:53:01.878: E/WindowManager(944): Activity com.cipl.CCM.frontend.LoginActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4063f7f8 that was originally added here
10-30 14:53:01.878: E/WindowManager(944): android.view.WindowLeaked: Activity com.cipl.CCM.frontend.LoginActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4063f7f8 that was originally added here
10-30 14:53:01.878: E/WindowManager(944):   at android.view.ViewRoot.<init>(ViewRoot.java:258)
10-30 14:53:01.878: E/WindowManager(944):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
10-30 14:53:01.878: E/WindowManager(944):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
10-30 14:53:01.878: E/WindowManager(944):   at android.view.Window$LocalWindowManager.addView(Window.java:424)
10-30 14:53:01.878: E/WindowManager(944):   at android.app.Dialog.show(Dialog.java:241)
10-30 14:53:01.878: E/WindowManager(944):   at com.cipl.CCM.frontend.LoginActivity$LoginUserTask.onPreExecute(LoginActivity.java:130)
10-30 14:53:01.878: E/WindowManager(944):   at android.os.AsyncTask.execute(AsyncTask.java:391)
10-30 14:53:01.878: E/WindowManager(944):   at com.cipl.CCM.frontend.LoginActivity$1.onClick(LoginActivity.java:62)
10-30 14:53:01.878: E/WindowManager(944):   at android.view.View.performClick(View.java:2485)
10-30 14:53:01.878: E/WindowManager(944):   at android.view.View$PerformClick.run(View.java:9080)
10-30 14:53:01.878: E/WindowManager(944):   at android.os.Handler.handleCallback(Handler.java:587)
10-30 14:53:01.878: E/WindowManager(944):   at android.os.Handler.dispatchMessage(Handler.java:92)
10-30 14:53:01.878: E/WindowManager(944):   at android.os.Looper.loop(Looper.java:123)
10-30 14:53:01.878: E/WindowManager(944):   at android.app.ActivityThread.main(ActivityThread.java:3683)
10-30 14:53:01.878: E/WindowManager(944):   at java.lang.reflect.Method.invokeNative(Native Method)
10-30 14:53:01.878: E/WindowManager(944):   at java.lang.reflect.Method.invoke(Method.java:507)
10-30 14:53:01.878: E/WindowManager(944):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-30 14:53:01.878: E/WindowManager(944):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-30 14:53:01.878: E/WindowManager(944):   at dalvik.system.NativeStart.main(Native Method)

LoginActivity

public class LoginActivity extends Activity {
    /** Variable define here. */
    private EditText metLoginUserName, metLoginPassword;
    private Button mbtnLogin;
    private ImageView ivRegister;
    private String Host, username, password;
    private int Port;
    private UserChatActivity xmppClient;
    public static ArrayList<String> all_user = new ArrayList<String>();
    public static CustomProgressDialog mCustomProgressDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loginlayout);

        metLoginUserName = (EditText) this.findViewById(R.id.etLoginUserName);
        metLoginPassword = (EditText) this.findViewById(R.id.etLoginPassword);
        mbtnLogin = (Button) findViewById(R.id.btnLogin);
        ivRegister = (ImageView) findViewById(R.id.ivRegister);

        /** Set the hint in username and password edittext */
        metLoginUserName = CCMStaticMethod.setHintEditText(metLoginUserName,
                getString(R.string.hint_username), true);
        metLoginPassword = CCMStaticMethod.setHintEditText(metLoginPassword,
                getString(R.string.hint_password), true);

        /** Click on login button */
        mbtnLogin.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                /** Login Activity */
                username = metLoginUserName.getText().toString();
                password = metLoginPassword.getText().toString();
                CCMStaticVariable.musername = username;
                CCMStaticVariable.musername = password;
                if(CCMStaticMethod.isInternetAvailable(LoginActivity.this)){
                    LoginUserTask loginUserTask = new LoginUserTask(v.getContext());
                    loginUserTask.execute();
                }
            }
        });

        /** Click on forgot button */
        this.findViewById(R.id.ivForgot).setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(LoginActivity.this,
                                ForgotPassActivity.class));
                    }
                });

        /** Click on register button */
        ivRegister.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this,
                        RegisterActivity.class));
            }
        });
    }

    public class LoginUserTask extends AsyncTask<Void, Void, XMPPConnection> {
        public LoginUserTask(Context context) {
            super();
            this.context = context;
        }
        private Context context;

        @Override
        protected void onPostExecute(XMPPConnection result) {
            if (result != null) {
                /**Start services*/
                startService(new Intent(LoginActivity.this, UpdaterService.class));
                /**Call user menu activity*/    
                //finish();

                LoginActivity.this.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub

                        startActivity(new Intent(LoginActivity.this,UserMenuActivity.class));

                    }
                });

            } else {
                DialogInterface.OnClickListener LoginUnSuccessOkAlertListener = new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                    }
                };
                CCMStaticMethod.showAlert(context, "Login",
                        "Invalid Username or Password. Try Again !", R.drawable.unsuccess,
                        true, true, "Ok", LoginUnSuccessOkAlertListener, null,
                        null);
            }
            mCustomProgressDialog.dismiss();
        }

        @Override
        protected void onPreExecute() {
            mCustomProgressDialog = CustomProgressDialog.createDialog(
                    LoginActivity.this, "", "");
            mCustomProgressDialog.show();
        }

        @Override
        protected XMPPConnection doInBackground(Void... params) {
            CCMStaticVariable.CommonConnection = XMPPConn.checkXMPPConnection(username,
                    password);
            return CCMStaticVariable.CommonConnection;
        }
    }

请让我知道我的错误是什么或者如何解决?

0 个答案:

没有答案