Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7822315
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T07:53:46+00:00 2026-06-02T07:53:46+00:00

i got a small problem with interrupts. in my android login activity, i start

  • 0

i got a small problem with interrupts. in my android login activity, i start a thread (which defines the duration of my session). what i want is that when im in a different activity/class and i press the logout button, i should stop the thread thats doing the countdown and be able to logIn again.

the only way i know to interrupt thereads are by

Thread.currentThread().interrupt();

but i dont want to interrupt the current thread, i want to interrupt the thread by its id, which im able to get by getId().

this is my activity class code:

import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.AndroidApp.R;
import com.AndroidApp.domain.Utente;
import com.AndroidApp.pagine.MenuPagina;


public class LoginActivity extends Activity {

    final String TAG = "LogIN";
    ArrayList<HashMap<String, String>> mylist;

    private Button bLogin, bExit;
    private EditText utente, passwd;
    private MediaPlayer mpButtonClick = null;
    private SharedPreferences mPreferences; 
    public Thread sessionTimer;
    public long tId = -1;

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

        mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);

        SharedPreferences.Editor editor = mPreferences.edit();
        editor.clear();
        editor.commit();

        String nome = mPreferences.getString("nome", "Nessuno");
        setTitle("Sessione di : " + nome);
        Log.w("TotThreads", Integer.toString(Thread.activeCount()));
        if (MenuPagina.reset){
            Log.w("LogIn", "trying to interrupt");


            //this is where im trying to interrypt the thread



            MenuPagina.reset = false;
        }

        if (!checkLoginInfo()) {

            mpButtonClick = MediaPlayer.create(this, R.raw.button);

            bLogin = (Button)findViewById(R.id.bLogin);
            bLogin.setOnClickListener(new View.OnClickListener() {

                public void onClick(View view) {

                    mpButtonClick.start();

                    Log.v(TAG, "Trying to Login");
                    utente = (EditText)findViewById(R.id.etUtente);
                    passwd = (EditText)findViewById(R.id.etPassword);

                    String username = utente.getText().toString();
                    username = ("aaa@ffff.it");
                    String password = md5(passwd.getText().toString());
                    Log.v(TAG, password);

                    XMLFunctionsLogin.getInstance().setNewURL("u=" + username + "&p=" + password);
                    String xml = XMLFunctionsLogin.getXML();
                    Document doc = XMLFunctionsLogin.xmlFromString(xml); 
                    int status = XMLFunctionsLogin.errStatus(doc); 

                    Log.v("status", Integer.toString(status));
                    if ((status == 0)) {
                        NodeList nodes = doc.getElementsByTagName("login"); 
                        Element e = (Element) nodes.item(0);
                        Utente utente = new Utente();
                        utente.setIdUtente(XMLFunctionsLogin.getValue(e, "idUtente"));
                        utente.setNome(XMLFunctionsLogin.getValue(e, "nome"));
                        utente.setCognome(XMLFunctionsLogin.getValue(e, "cognome"));
                        Log.v("utente", utente.getCognome().toString());

                        Log.v(TAG, "5");

                        List<NameValuePair> nvps = new ArrayList<NameValuePair>(2);
                        nvps.add(new BasicNameValuePair("utente", username));
                        nvps.add(new BasicNameValuePair("password", password));
                        Log.v(TAG, nvps.get(0).toString());
                        Log.v(TAG, nvps.get(1).toString());

                        // Store the username and password in SharedPreferences after the successful login
                        SharedPreferences.Editor editor = mPreferences.edit();
                        editor.putString("userName", username);
                        editor.putString("password", password);
                        editor.putString("idUtente", utente.getIdUtente());
                        editor.putString("nome", utente.getNome());
                        editor.putString("cognome", utente.getCognome());
                        editor.commit();


                        Log.v(TAG, "Successo");

                        sessionTimer = new Thread() {
                            @Override
                            public void run() {
                                long tId = Thread.currentThread().getId();
                                Log.w("TTthread Id", Long.toString(tId));
                                for (int i = 30; i >= 0; i -= 1) {
                                    if (i == 0) {
                                        System.out.print("timer finito");
                                        Log.i("Timer", "timer finito");
                                        LoginActivity.this.runOnUiThread(new Runnable() { 
                                            public void run() { 
                                                Toast.makeText(LoginActivity.this, "ti si è scaduta la sessione", Toast.LENGTH_LONG).show(); 
                                            }
                                        });
                                        Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
                                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                        startActivity(intent);
                                        //System.exit(0);
                                    } try {
                                        Thread.sleep(1000);
                                        Log.i("Timer", Integer.toString(i));
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    } finally {
                                        finish();
                                    }
                                }
                            }

                        };
                        sessionTimer.start();


                        Log.v(TAG, "Successo2");


                        /*
                        Counter timer = new Counter();
                        timer.start();

                         */

                        Toast.makeText(LoginActivity.this, "LogIn con successo", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(LoginActivity.this, MenuPagina.class);
                        startActivity(intent);

                    } else {
                        final String errorMessage = XMLFunctionsLogin.errStatusDesc(doc);
                        Log.v("fallimento", errorMessage);
                        LoginActivity.this.runOnUiThread(new Runnable() { 
                            public void run() { 
                                Toast.makeText(LoginActivity.this, errorMessage, Toast.LENGTH_LONG).show(); 
                            }
                        });

                        Intent intent = getIntent();
                        finish();
                        startActivity(intent);
                    }
                }

            });

            bExit = (Button)findViewById(R.id.bExit);
            bExit.setOnClickListener(new View.OnClickListener() {

                public void onClick(View view) {
                    mpButtonClick.start();
                    finish();
                }
            });
        }
    }

    //Checking whether the username and password has stored already or not
    private final boolean checkLoginInfo() {
          boolean username_set = mPreferences.contains("UserName");
          boolean password_set = mPreferences.contains("PassWord"); 
          if ( username_set || password_set ) {
                return true;
          } 
          return false;
    }

    //md5 for crypting and hash
    private static String md5(String data) {
        byte[] bdata = new byte[data.length()];
        int i;
        byte[] hash;

        for (i = 0; i < data.length(); i++)
            bdata[i] = (byte) (data.charAt(i) & 0xff);

        try {
            MessageDigest md5er = MessageDigest.getInstance("MD5");
            hash = md5er.digest(bdata);
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e);
        }

        StringBuffer r = new StringBuffer(32);
        for (i = 0; i < hash.length; i++) {
            String x = Integer.toHexString(hash[i] & 0xff);
            if (x.length() < 2)
                r.append("0");
            r.append(x);
        }
        return r.toString();
    }
}

any help would be much appreciated.
thanks!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T07:53:49+00:00Added an answer on June 2, 2026 at 7:53 am

    When you start a thread you should save the Thread object and then call interrupt on that Thread object:

     Thread thread = new Thread(yourRunnable);
     thread.start();
     ...
     thread.interrupt();
    

    So with the code you just added, you would do:

    sessionTimer.interrupt();
    

    Also, be aware that interrupting the thread will only cause sleep() and wait() calls to throw InterruptedException or set the thread interrupt flag. It will not stop the thread from executing. This means that you thread should use code like:

     // loop until we are interrupted
     while (!Thread.currentThread().isInterrupted()) {
        ...
        // if you use sleep or wait it should do:
        try {
           Thread.sleep(someMillis);
        } catch (InterruptedException e) {
           // if you are not quitting then you need to reset the interrupted flag
           Thread.currentThread.interrupt();
           // otherwise it is typical to quit the thread if interrupted
           return;
        }
     }
    

    So with the code you just posted, when you are doing your sleep you should exit the run() method which will stop the thread.

                    try {
                        Thread.sleep(1000);
                        Log.i("Timer", Integer.toString(i));
                    } catch (InterruptedException e) {
                        // quit because we were interrupted
                        return;
                    } finally {
                        finish();
                    }
    

    Also, remember that if a separate thread is calling interrupt() on the sessionTimer, then it should be marked as volatile.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've got a small Cocoa problem. I have a StatusBar application that has an
I came up with a small problem. Now, I've got a program which plots
I've got a seemingly small problem using LaTeX, which i can't find the answer
I got a small problem that I can't figure out. I have a superclass
I've got small wpf application deployed using ClickOnce technology. The problem is that when
I have got a small problem in an Android app I am working on
I've got a small problem I'm struggling to solve. Let's say I've got an
Can anyone help with a small problem. I've got a nice simple CSS dropdown
I've got a problem with NHibernate trying to load a small hierarchy of data.
I've got a small program that displays third-party generated HTML pages. It's really just

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.