简体   繁体   中英

How to keep service alive even when I close the app?

I am new to android. I have developed a small chat application, which is having register page, login screen and friendslist screen. When the user register and login, he will be redirected to the friends list page. And it is working good. I used sharedpreference for once the user register second time they directly redirected to the friends list page. But here it is not I close my application.

Can anyone help me?

Thanks in advance.

This is my Registration.java

private ServiceConnection mConnection = new ServiceConnection() {


public void onServiceConnected(ComponentName className, IBinder service) {

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

    public void onServiceDisconnected(ComponentName className) {
        // This is called when the connection with the service has been
        // unexpectedly disconnected -- that is, its process crashed.
        // Because it is running in our same process, we should never
        // see this happen.
     imService = null;
        Toast.makeText(SignUp.this, R.string.local_service_stopped,
                Toast.LENGTH_SHORT).show();
    }
};

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);



setContentView(R.layout.sign_up_screen);
setTitle("Sign up");


Button signUpButton = (Button) findViewById(R.id.signUp);
Button cancelButton = (Button) findViewById(R.id.cancel_signUp);
usernameText = (EditText) findViewById(R.id.userName);
passwordText = (EditText) findViewById(R.id.password);
passwordAgainText = (EditText) findViewById(R.id.passwordAgain);
eMailText = (EditText) findViewById(R.id.email);

SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
if(pref.getBoolean("activity_executed", false)){
Intent intent = new Intent(this, FriendList.class);
startActivity(intent);
finish();
} else {
Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.putString("username", usernameText.getText().toString());
ed.putString("password", passwordText.getText().toString());
ed.commit();
}

signUpButton.setOnClickListener(new OnClickListener(){
public void onClick(View arg0)
{   
if (usernameText.length() > 0 &&    
passwordText.length() > 0 &&
passwordAgainText.length() > 0 &&
eMailText.length() > 0
)

{

if (passwordText.getText().toString().equals(passwordAgainText.getText().toString())){

if (usernameText.length() >= 5 && passwordText.length() >= 5) {

Thread thread = new Thread(){
String result = new String();
@Override
public void run() {
result = imService.signUpUser(usernameText.getText().toString(),
passwordText.getText().toString(),
eMailText.getText().toString());

handler.post(new Runnable(){

public void run() {
if (result.equals(SERVER_RES_RES_SIGN_UP_SUCCESFULL)) {
/*editor.putString("register","true");
editor.commit();*/
Toast.makeText(getApplicationContext(),R.string.signup_successfull,    Toast.LENGTH_LONG).show();
startActivity(new Intent (SignUp.this, Login.class));
SignUp.this.finish();

}
 else if (result.equals(SERVER_RES_SIGN_UP_USERNAME_CRASHED)){
Toast.makeText(getApplicationContext(),R.string.signup_username_crashed,     Toast.LENGTH_LONG).show();
//showDialog(SIGN_UP_USERNAME_CRASHED);
}
else //if (result.equals(SERVER_RES_SIGN_UP_FAILED))
{
Toast.makeText(getApplicationContext(),R.string.signup_failed,   Toast.LENGTH_LONG).show();

}   
 }

 });
 }

 };
thread.start();
 }
else{
Toast.makeText(getApplicationContext(),R.string.username_and_password_length_short, Toast.LENGTH_LONG).show();

}   
}
 else {
      Toast.makeText(getApplicationContext(),R.string.signup_type_same_password_in_password_fields, Toast.LENGTH_LONG).show();

//showDialog(TYPE_SAME_PASSWORD_IN_PASSWORD_FIELDS); }

}
else {
 Toast.makeText(getApplicationContext(),R.string.signup_fill_all_fields,    Toast.LENGTH_LONG).show();
 }  
}
});


}

This is Login.java

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

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

        if (imService.isUserAuthenticated() == true)
        {
         Intent i = new Intent(Login.this, FriendList.class);   
startActivity(i);
Login.this.finish();
        }
    }

    public void onServiceDisconnected(ComponentName className) {

     imService = null;
        Toast.makeText(Login.this, R.string.local_service_stopped,
                Toast.LENGTH_SHORT).show();
    }
   };
 @Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

 startService(new Intent(Login.this, IMService.class)); 


    setContentView(R.layout.login_screen);
    setTitle("Login");

    Button loginButton = (Button) findViewById(R.id.login);
    cancelButton = (Button) findViewById(R.id.cancel_login);
    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();

return;
}
 else if (imService.isNetworkConnected() == false)
{
Toast.makeText(getApplicationContext(),R.string.not_connected_to_network, Toast.LENGTH_LONG).show();

}
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(),   passwordText.getText().toString());
} catch (UnsupportedEncodingException e) {

e.printStackTrace();
}
 if (result == null || result.equals(AUTHENTICATION_FAILED))
{

handler.post(new Runnable(){
 public void run() {    
Toast.makeText(getApplicationContext(),R.string.make_sure_username_and_password_correct, Toast.LENGTH_LONG).show();


}   
});

}
else {


handler.post(new Runnable(){
public void run() { 
Intent i = new Intent(Login.this, FriendList.class);    
//i.putExtra(FRIEND_LIST, result);
startActivity(i);   
Login.this.finish();
}   
});

}

}
};
loginThread.start();

 }
else {

Toast.makeText(getApplicationContext(),R.string.fill_both_username_and_password,     Toast.LENGTH_LONG).show();

}   
}
    });

    cancelButton.setOnClickListener(new OnClickListener(){

public void onClick(View arg0)
{   
imService.exit();
finish();

}

    });


}

Maybe the 'foreground' service is what you want.

http://developer.android.com/guide/components/services.html#Foreground

A foreground service is a service that's considered to be something the user is actively aware of and thus not a candidate for the system to kill when low on memory. A foreground service must provide a notification for the status bar, which is placed under the "Ongoing" heading, which means that the notification cannot be dismissed unless the service is either stopped or removed from the foreground.

For example, a music player that plays music from a service should be set to run in the foreground, because the user is explicitly aware of its operation ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM