在Android中,如果不使用按钮,则无法启动服务

在Android中,如果不使用按钮,则无法启动服务,android,Android,我想在创建意图时启动此服务。下面是我的服务,但除非手动单击某个按钮,否则服务不会启动。我正在使用startServicenew IntentLogin.this,IMService.class 您后期编辑的代码中没有startService可能是上下文问题,请尝试在创建方法中使用getApplicationContext作为上下文参数。您已使用getApplicationContext,但目的尚未解决。 package at.vcity.androidim.services; impor

我想在创建意图时启动此服务。下面是我的服务,但除非手动单击某个按钮,否则服务不会启动。我正在使用startServicenew IntentLogin.this,IMService.class


您后期编辑的代码中没有startService可能是上下文问题,请尝试在创建方法中使用getApplicationContext作为上下文参数。您已使用getApplicationContext,但目的尚未解决。
package at.vcity.androidim.services;    
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import at.vcity.androidim.Login;
import at.vcity.androidim.Messaging;
import at.vcity.androidim.R;
import at.vcity.androidim.UserSessionManager;
import at.vcity.androidim.communication.SocketOperator;
import at.vcity.androidim.interfaces.IAppManager;
import at.vcity.androidim.interfaces.ISocketOperator;
import at.vcity.androidim.interfaces.IUpdateData;
import at.vcity.androidim.tools.FriendController;
import at.vcity.androidim.tools.LocalStorageHandler;
import at.vcity.androidim.tools.MessageController;
import at.vcity.androidim.tools.XMLHandler;
import at.vcity.androidim.types.FriendInfo;
import at.vcity.androidim.types.MessageInfo;

public class IMService extends Service implements IAppManager, IUpdateData {

    public static String USERNAME;
    public static String PASSWORD, dispName="", id="";
    public static final String TAKE_MESSAGE = "Take_Message";
    public static final String FRIEND_LIST_UPDATED = "Take Friend List";
    public static final String MESSAGE_LIST_UPDATED = "Take Message List";
    public ConnectivityManager conManager = null; 
    private final int UPDATE_TIME_PERIOD = 15000;
    private String rawFriendList = new String();
    private String rawMessageList = new String();

    ISocketOperator socketOperator = new SocketOperator(this);

    private final IBinder mBinder = new IMBinder();
    private String username;
    private String password;
    private UserSessionManager session;
    private boolean authenticatedUser = false;
     // timer to take the updated data from server
    private Timer timer;


    private LocalStorageHandler localstoragehandler; 

    private NotificationManager mNM;

    public class IMBinder extends Binder {
        public IAppManager getService() {
            return IMService.this;
        }

    }

    @Override
    public void onCreate() 
    {       

         mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

         localstoragehandler = new LocalStorageHandler(this);        
        conManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        new LocalStorageHandler(this);

        // Timer is used to take the friendList info every UPDATE_TIME_PERIOD;
        timer = new Timer();   

        Thread thread = new Thread()
        {
            @Override
            public void run() {         

                //socketOperator.startListening(LISTENING_PORT_NO);
                Random random = new Random();
                int tryCount = 0;
                while (socketOperator.startListening(10000 + random.nextInt(20000))  == 0 )
                {       
                    tryCount++; 
                    if (tryCount > 10)
                    {
                        // if it can't listen a port after trying 10 times, give up...
                        break;
                    }

                }
            }
        };      
        thread.start();

    }

    @Override
    public IBinder onBind(Intent intent) 
    {
        return mBinder;
    }




    /**
     * Show a notification while this service is running.
     * @param msg 
     **/
    private void showNotification(String username, String msg) 
    {       
        // Set the icon, scrolling text and TIMESTAMP
        String title = getString(R.string.app_name)+ ": You got a new Message! (" + username + ")";

        String text = username + ": " + 
                    ((msg.length() < 5) ? msg : msg.substring(0, 5)+ "...");

        //NotificationCompat.Builder notification = new NotificationCompat.Builder(R.drawable.stat_sample, title,System.currentTimeMillis());
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.ic_launcher)
        .setContentTitle(title)
        .setContentText(text);          

        Intent i = new Intent(this, Messaging.class);
        i.putExtra(FriendInfo.USERNAME, username);
        i.putExtra(MessageInfo.MESSAGETEXT, msg);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i,PendingIntent.FLAG_UPDATE_CURRENT);

        mBuilder.setContentIntent(contentIntent); 

        mBuilder.setContentText("New message from " + username + ": " + msg);

        //TODO: it can be improved, for instance message coming from same user may be concatenated 
        // next version

        // Send the notification.
        // We use a layout id because it is a unique number.  We use it later to cancel.
        mBuilder.setAutoCancel(true);
        mNM.notify((username+msg).hashCode(), mBuilder.build());  

        //mNM.cancel((username+msg).hashCode());
    }


    public String getUsername() {
        System.out.println("public String getUsername() Call Error..............");
        return this.username;
    }


    public String sendMessage(String  action, String  tousername, String message, String latitude, String longitude) throws UnsupportedEncodingException 
    {
        System.out.println("sendMessage> username="+this.username+";to"+tousername+";latitude="+latitude+";longitude="+longitude+";action="+action+";message="+message);
        String params = "username="+ URLEncoder.encode(this.username,"UTF-8") +
                        //"&password="+ URLEncoder.encode(this.password,"UTF-8") +
                        "&to=" + URLEncoder.encode(tousername,"UTF-8") +
                        "&message="+ URLEncoder.encode(message,"UTF-8") +
                        "&action="  + URLEncoder.encode(action,"UTF-8")+
                        "&latitude="+ URLEncoder.encode(latitude,"UTF-8") +
                        "&longitude="+ URLEncoder.encode(longitude,"UTF-8") +
                        "&";        
        //Log.i("PARAMS", params);
        return socketOperator.sendHttpRequest(params);      
    }

    public String sendImageMessage(String  action, String  username, String  tousername, String latitude, String longitude, String file) throws UnsupportedEncodingException 
    {
        System.out.println("sendImageMessage> username="+username+";to="+tousername+";latitude="+latitude+";longitude="+longitude+";action="+action);
        String params = "username="+ URLEncoder.encode(username,"UTF-8") +
                        //"&password="+ URLEncoder.encode(IMService.PASSWORD,"UTF-8") +
                        "&to=" + URLEncoder.encode(tousername,"UTF-8") +
                        "&action="  + URLEncoder.encode(action,"UTF-8")+
                        "&latitude="+ URLEncoder.encode(latitude,"UTF-8") +
                        "&longitude="+ URLEncoder.encode(longitude,"UTF-8") +
                        "&file="+ URLEncoder.encode(file,"UTF-8") +
                        "&";        
        //Log.i("PARAMS", params);
        return socketOperator.sendHttpRequest(params);      
    }


    private String getFriendList() throws UnsupportedEncodingException  {       
        // after authentication, server replies with friendList xml

        session = new UserSessionManager(getApplicationContext());
        HashMap<String, String> user = session.getUserDetailsWithConsignment();
        id= user.get(UserSessionManager.KEY_ID);
        System.out.println(" getFriendList result id="+id);
         rawFriendList = socketOperator.sendHttpRequest(getAuthenticateUserParams(id));
         System.out.println("rawFriendList="+rawFriendList);
         if (rawFriendList != null) {
             this.parseFriendInfo(rawFriendList);
         }
         return rawFriendList;
    }

    private String getMessageList() throws UnsupportedEncodingException     {       
        // after authentication, server replies with friendList xml

         rawMessageList = socketOperator.sendHttpRequest(getAuthenticateUserParams(username));
         if (rawMessageList != null) {
             this.parseMessageInfo(rawMessageList);
         }
         return rawMessageList;
    }

    public String validateUser(String usernameText, String password, String imeiNo) throws UnsupportedEncodingException 
    {
        String params = "mobileno=" + usernameText +
                        "&secretcode=" + password +
                        "&action=" + "validateUser"+
                        "&IMEI=" + imeiNo+
                        "&";
        String result = socketOperator.sendHttpRequest(params);     
        return result;
    }

    public String authenticateUser(String usernameText) throws UnsupportedEncodingException 
    {
        this.username = usernameText;


        String result = this.getFriendList(); //socketOperator.sendHttpRequest(getAuthenticateUserParams(username, password));
        if (result != null && !result.equals(Login.AUTHENTICATION_FAILED)) 
        {           
            // if user is authenticated then return string from server is not equal to AUTHENTICATION_FAILED
            this.authenticatedUser = true;
            rawFriendList = result;
            /*USERNAME = this.username;
            PASSWORD=this.password;*/
            Intent i = new Intent(FRIEND_LIST_UPDATED);                 
            i.putExtra(FriendInfo.FRIEND_LIST, rawFriendList);
            sendBroadcast(i);

            timer.schedule(new TimerTask()
            {           
                public void run() 
                {
                    try {                   
                        //rawFriendList = IMService.this.getFriendList();
                        // sending friend list 
                        Intent i = new Intent(FRIEND_LIST_UPDATED);
                        Intent i2 = new Intent(MESSAGE_LIST_UPDATED);
                        String tmp = IMService.this.getFriendList();
                        String tmp2 = IMService.this.getMessageList();
                        if (tmp != null) {
                            i.putExtra(FriendInfo.FRIEND_LIST, tmp);
                            sendBroadcast(i);   
                            Log.i("friend list broadcast sent ", "");

                        if (tmp2 != null) {
                            i2.putExtra(MessageInfo.MESSAGE_LIST, tmp2);
                            sendBroadcast(i2);  
                            Log.i("friend list broadcast sent ", "");
                        }
                        }
                        else {
                            Log.i("friend list returned null", "");
                        }
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                    }                   
                }           
            }, UPDATE_TIME_PERIOD, UPDATE_TIME_PERIOD);
        }

        return result;      
    }

    public void messageReceived(String username, String message) 
    {               

        //FriendInfo friend = FriendController.getFriendInfo(username);
        MessageInfo msg = MessageController.checkMessage(username);
        if ( msg != null)
        {           
            //System.out.println("@%%%%%%%%%%%@in Mesage Received ="+msg.messagetext);
            Intent i = new Intent(TAKE_MESSAGE);
            i.putExtra(MessageInfo.USERID, username);       
            i.putExtra(MessageInfo.MESSAGETEXT, message);
            sendBroadcast(i);
            String activeFriend = FriendController.getActiveFriend();
            if (activeFriend == null || activeFriend.equals(username) == false) 
            {
                session = new UserSessionManager(getApplicationContext());
                HashMap<String, String> user = session.getUserDetailsWithConsignment();
                dispName= user.get(UserSessionManager.KEY_USER_DISP_NAME);
                localstoragehandler.insert(username,dispName, message);
                showNotification(username, message);


            }

            Log.i("TAKE_MESSAGE broadcast sent by im service", "");
        }   

    }  

    private String getAuthenticateUserParams(String usernameText) throws UnsupportedEncodingException 
    {           

        String params = "username=" + URLEncoder.encode(usernameText,"UTF-8") +
                        "&action="  + URLEncoder.encode("authenticateUser","UTF-8")+
                        "&port="    + URLEncoder.encode(Integer.toString(socketOperator.getListeningPort()),"UTF-8") +
                        "&";        
        return params;      
    }

    public void setUserKey(String value) 
    {       
    }

    public boolean isNetworkConnected() {
        return conManager.getActiveNetworkInfo().isConnected();
    }

    public boolean isUserAuthenticated(){
        return authenticatedUser;
    }

    public String getLastRawFriendList() {      
        return this.rawFriendList;
    }

    @Override
    public void onDestroy() {
        Log.i("IMService is being destroyed", "...");
        super.onDestroy();
    }

    public void exit() 
    {
        timer.cancel();
        socketOperator.exit(); 
        socketOperator = null;
        this.stopSelf();
    }

    public String signUpUser(String usernameText, String passwordText,
            String emailText) 
    {
        String params = "username=" + usernameText +
                        "&password=" + passwordText +
                        "&action=" + "signUpUser"+
                        "&email=" + emailText+
                        "&";

        String result = socketOperator.sendHttpRequest(params);     

        return result;
    }

    public String addNewFriendRequest(String friendUsername) 
    {
        String params = "username=" + this.username +
        "&action=" + "addNewFriend" +
        "&friendUserName=" + friendUsername +
        "&";
        String result = socketOperator.sendHttpRequest(params); 
        return result;
    }

    public String sendFriendsReqsResponse(String approvedFriendNames,
            String discardedFriendNames) 
    {
        String params = "username=" + this.username +
        "&password=" + this.password +
        "&action=" + "responseOfFriendReqs"+
        "&approvedFriends=" + approvedFriendNames +
        "&discardedFriends=" +discardedFriendNames +
        "&";

        String result = socketOperator.sendHttpRequest(params);     

        return result;

    } 

    private void parseFriendInfo(String xml)
    {           
        try 
        {
            SAXParser sp = SAXParserFactory.newInstance().newSAXParser();
            sp.parse(new ByteArrayInputStream(xml.getBytes()), new XMLHandler(IMService.this));     
        } 
        catch (ParserConfigurationException e) {            
            e.printStackTrace();
        }
        catch (SAXException e) {            
            e.printStackTrace();
        } 
        catch (IOException e) {         
            e.printStackTrace();
        }   
    }
    private void parseMessageInfo(String xml)
    {           
        try 
        {
            SAXParser sp = SAXParserFactory.newInstance().newSAXParser();
            sp.parse(new ByteArrayInputStream(xml.getBytes()), new XMLHandler(IMService.this));     
        } 
        catch (ParserConfigurationException e) {            
            e.printStackTrace();
        }
        catch (SAXException e) {            
            e.printStackTrace();
        } 
        catch (IOException e) {         
            e.printStackTrace();
        }   
    }

    public void updateData(MessageInfo[] messages,FriendInfo[] friends,
            FriendInfo[] unApprovedFriends, String userKey) 
    {
        this.setUserKey(userKey);

        //FriendController. 
        MessageController.setMessagesInfo(messages);

        int i = 0;
        while (i < messages.length){
            messageReceived(messages[i].userid,messages[i].messagetext);
            i++;
        }

        FriendController.setFriendsInfo(friends);
        FriendController.setUnapprovedFriendsInfo(unApprovedFriends);

    }

}