I have a Service with a Notification with a Progress Bar inside. This Service is started when i open the Main Activity and works fine. But, when i close Main Activity (onDestroy() is called) the Notification is like refreshed. This is the code of my Service.
#Override
public void onCreate() {
super.onCreate();
Mypreferences prefs = new Mypreferences(this);
String minutes = prefs.getStringValueOf("Minutes");
final NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
d = Integer.valueOf(minutes)*60;
builder.setSmallIcon(R.drawable.ic_action_about);
builder.setContentTitle(getString(R.string.app_name));
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<d;i++) {
builder.setProgress(d, d-i, false);
builder.setContentInfo(d-i+"/"+d);
notificationManager.notify(0, builder.build());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
Integer d it's 60 and countdown works fine but when i close MainActivity if for example ProgressBar is at 40, return to 60. Why? How can i solve?
Service code
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
pref = new SharedPref(this);
map = pref.getAllPrefs();
boolean delay = pref.loadBooleanPref("delay");
String delayTime = pref.loadStringValue("DelayTime");
if(delay && delayTime != null) {
new CountDownTimer(TimeUnit.MINUTES.toMillis(Long.valueOf(delayTime)), 1000) {
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
getInfo();
}
}.start();
} else {
getInfo();
}
}
Related
I want to track user location continuously even after they close the app. The service continuously stores location on DB and a wakefulintent starts a timertask to upload it to server. I have used
LocationServices.FusedLocationApi.requestLocationUpdates(Utils.googleApiClient,
mlocationrequest, this);
on a service. I have declared service on manifest as
<service
android:name="com.projest.services.BackgroundService"
android:enabled="true"
android:process=":Background">
</service>
and called servicew on my main activity using
Intent service = new Intent(this, BackgroundService.class);
startService(service);
but the service is not working. I couldn't see log.
public class BackgroundService extends Service implements LocationListener{
public static final String TAG = "BackgroundService";
Context context;
LocationRequest mlocationrequest;
private static int UPDATE_INTERVAL = 10000; // 10 sec
private static int FATEST_INTERVAL = 5000; // 5 sec
public BackgroundService(Context context){
this.context = context;
}
public BackgroundService(){
}
public void onCreate(){
try{
super.onCreate();
if(Utils.DEBUG)Log.d(TAG,"inside onCreate");
}catch(Exception e){
if(Utils.DEBUG)Log.d(TAG,"problem oncreate");
}
}
public int onStartCommand(){
if(Utils.DEBUG)Log.d(TAG,"inside onStartCommand");
if(!Utils.startGpsTracker)
{
Utils.startGpsTracker=true;
toggleGPS(true);
}
buildGoogleApiClient();
Utils.googleApiClient.connect();
if (Utils.googleApiClient.isConnected()) {
startLocationUpdates();
}
return START_STICKY;
}
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "Connected to GoogleApiClient");
if (Utils.latestLocation == null) {
Utils.latestLocation = LocationServices.FusedLocationApi.getLastLocation(Utils.googleApiClient);
if(Utils.DEBUG)Log.d(TAG,"inside onconnected");
try {
storeGpsinDb();
if(Utils.DEBUG)Log.d(TAG,"trouble opening storeGPS");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
startLocationUpdates();
}
private void startLocationUpdates() {
// TODO Auto-generated method stub
try {
if (Utils.googleApiClient.isConnected()) {
LocationServices.FusedLocationApi.requestLocationUpdates(Utils.googleApiClient, mlocationrequest, this);
if(Utils.DEBUG)Log.d(TAG,"inside startlocationupdates");
}
} catch (SecurityException ex) {
}
}
#Override
public void onLocationChanged(Location location) {
Utils.latestLocation = location;
try {
storeGpsinDb();
if(Utils.DEBUG)Log.d(TAG,"inside onlocationchanged");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected synchronized void buildGoogleApiClient() {
if (Utils.googleApiClient == null) {
Utils.googleApiClient = new GoogleApiClient.Builder(this.context).addApi(LocationServices.API).build();
if(Utils.DEBUG)Log.d(TAG,"googleAPIclient");
}
createLocationRequest();
}
private void createLocationRequest() {
// TODO Auto-generated method stub
mlocationrequest = new LocationRequest();
mlocationrequest.setInterval(UPDATE_INTERVAL);
mlocationrequest.setFastestInterval(FATEST_INTERVAL);
mlocationrequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if(Utils.DEBUG)Log.d(TAG,"inside createlocationrequest");
}
public void onConnectionSuspended(int cause) {
Utils.googleApiClient.connect();
if(Utils.DEBUG)Log.d(TAG,"insise connectionsuspended");
}
#Override
public void onDestroy() {
if(Utils.DEBUG)Log.d(TAG,"inside onDestroy");
stopLocationUpdates();
Utils.googleApiClient.disconnect();
super.onDestroy();
}
protected void stopLocationUpdates() {
if (Utils.googleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(Utils.googleApiClient, this);
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
private void toggleGPS(boolean enable) {
String provider = Settings.Secure.getString(context.getContentResolver(),Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(Utils.DEBUG)System.out.println("toggleGPS:" + provider);
if (provider.contains("gps") == enable) {
if(Utils.DEBUG)System.out.println("toggleGPS:enable true");
return; // the GPS is already in the requested state
}
if(Utils.DEBUG)System.out.println("toggleGPS:enable false");
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
this.context.sendBroadcast(poke);
}
private void storeGpsinDb() throws IOException {
if (!(Utils.latestLocation==null)) {
}else{
}
// }
}
}
What mistake am I making
I am working two weeks on this.Please help me.
you need to define android:stopWithTask="false" in manifest.
the process(Threads) run from the service will stop working if your app is removed from the recent apps. To ensure that your processes(Threads) remains always in running condition you have to Override onTaskRemoved() method and add code to restart Tasks like below.
#Override
public void onTaskRemoved(Intent rootIntent){
Intent restartServiceTask = new Intent(getApplicationContext(),this.getClass());
restartServiceTask.setPackage(getPackageName());
PendingIntent restartPendingIntent =PendingIntent.getService(getApplicationContext(), 1,restartServiceTask, PendingIntent.FLAG_ONE_SHOT);
AlarmManager myAlarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
myAlarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartPendingIntent);
super.onTaskRemoved(rootIntent);
}
I am trying to communicate with USB using InputOutput stream, I use constructor and make the communication part in a common class and I do use it inside a fragment, if i use it inside an activity it works properly if i use inside a fragment, the application hangs to overcome the problem i terminated the connection while OnPause but while resume connection not retains only on fragment same logic works on activity, I use some animations inside like Video is that be a reason?
#SuppressLint("ValidFragment")
public class Run_Screen extends Fragment implements OnClickListener {
Usb_Communciation usbCom;
RelativeLayout R_RelativeLayout, Run_Screen_Layout, Screen_Lock_Layout;
static SharedPreferences sharedpreferences;
Animation wipe;
static int machine;
MyLog myLog = new MyLog();
View root = null;
static Activity thisActivity = null;
#Override
public void onAttach(Activity activity) {
act = activity;
super.onAttach(activity);
thisActivity = Run_Screen.this.getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (Vars.Screen_Size == 400) {
root = inflater.inflate(R.layout.run_screen_400, container, false);
} else if (Vars.Screen_Size == 600) {
root = inflater.inflate(R.layout.run_screen_600, container, false);
} else if (Vars.Screen_Size == 800) {
root = inflater.inflate(R.layout.run_screen_800, container, false);
} else {
root = inflater.inflate(R.layout.run_screen, container, false);
}
sharedpreferences = this.getActivity().getSharedPreferences(Vars.MyPre, Context.MODE_PRIVATE);
GlobalClass.Current_Screen = "Run_Screen";
cmg = new Comment_Generate(act);
R_Wiper = (ImageButton) root.findViewById(R.id.R_Wiper);
wipe = AnimationUtils.loadAnimation(act, R.anim.wipe);
wipe.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationEnd(Animation arg0) {
// TODO Auto-generated method stub
Wiper_anim.setVisibility(View.INVISIBLE);
R_Wiper.setVisibility(View.VISIBLE);
}
#Override
public void onAnimationRepeat(Animation arg0) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationStart(Animation arg0) {
// TODO Auto-generated method stub
Wiper_anim.setVisibility(View.VISIBLE);
}
});
R_Pause_Play.setOnClickListener(this);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
usbCom = new Usb_Communciation(Run_Screen.this.getActivity(), getActivity().getIntent());
}
#Override
public void onPause() {
super.onPause();
Usb_Communciation.AppDisconnect(Run_Screen.this.getActivity());
}
public void CheckFunc(){
if(Vars.ChangeMAchine==1){
R_Progress.setVisibility(View.VISIBLE);
R_Separator.setVisibility(View.VISIBLE);
R_Run.setVisibility(View.INVISIBLE);
R_Pause.setVisibility(View.VISIBLE);
R_Stop.setVisibility(View.VISIBLE);
R_Pause_Play.setVisibility(View.INVISIBLE);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.R_Pause_Play:
DisableAll();
Reset_Machine_State(-2);
Vars.ChangeMAchine=1;
CheckFunc();
R_Progress.setVisibility(View.VISIBLE);
Send_Comment(Vars.C_Start_Machine, 0, 0);
myLog.Cmd("Write", Vars.C_Start_Machine, "0", "0",
"Start The Machine");
break;
}
}
private void Send_Comment(String Comment_No, int Address, int Data) {
Sending_Comment = cmg.Generate_Comment_for(Comment_No, Address, Data);
usbCom.Send_message(Sending_Comment);
}
public void SetUserLevelControls() {
Vars.CurrentUserLevel = sharedpreferences.getInt(Vars.UserLevel, 5);
if (Permission.Launcher_Operator_Screen_Defect_Height <= Vars.CurrentUserLevel) {
Screen_Lock_Layout.setVisibility(View.GONE);
} else {
Screen_Lock_Layout.setVisibility(View.VISIBLE);
}
if (Permission.Launcher_Operator_Screen_General <= Vars.CurrentUserLevel) {
R_Run.setOnClickListener(this);
R_Pause.setOnClickListener(this);
R_Stop.setOnClickListener(this);
R_Pause_Play.setOnClickListener(this);
Run_Lock.setVisibility(View.GONE);
} else {
R_Run.setOnClickListener(null);
R_Pause.setOnClickListener(null);
R_Stop.setOnClickListener(null);
R_Pause_Play.setOnClickListener(null);
Run_Lock.setVisibility(View.VISIBLE);
}
}
}
constructor class
public Usb_Communciation(Context mContext, Intent intent) {
try {
PackageManager manager = mContext.getPackageManager();
PackageInfo info = manager.getPackageInfo(mContext.getPackageName(), 0);
Log.d(TAG, "Info:" + info.packageName + "\n" + info.versionCode + "\n" + info.versionName);
} catch (PackageManager.NameNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
accessoryManager = new USBAccessoryManager(handler, USBAccessoryWhat);
accessoryManager.enable(mContext, intent);
}
AppDisconnect
public static void AppDisconnect(Context context) {
switch(firmwareProtocol) {
case 2:
byte[] commandPacket = new byte[2];
commandPacket[0] = (byte) APP_DISCONNECT;
commandPacket[1] = 0;
accessoryManager.write(commandPacket);
break;
}
try {
while(accessoryManager.isClosed() == false) {
Thread.sleep(2000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
accessoryManager.disable(context);
disconnectAccessory();
}
I am new to android. I am trying using AIDL.
What I am tryng is take initial value i.e 0 from the Textview and tryng to increment its value by calling a method defined in aidl file(using service.)
But the TextView is not updating on button click.
Kindly Help.
Here is my code.
CounterService.aidl
package com.example.counter;
interface CounterService {
int updateCounter(in int var);
}
CounterServ.java (Exposing service)
package com.example.counter;
public class CounterServ extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return new CounterService.Stub() {
#Override
public int updateCounter(int var) throws RemoteException {
// TODO Auto-generated method stub
return var + 1;
}
};
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
User Activity using service.
public class MainActivity extends Activity {
CounterService myservice;
AdditionServiceConnection connection;
class AdditionServiceConnection implements ServiceConnection {
public void onServiceConnected(ComponentName name, IBinder Service) {
myservice = CounterService.Stub.asInterface(Service);
Toast.makeText(MainActivity.this, "Service connected", Toast.LENGTH_LONG)
.show();
}
public void onServiceDisconnected(ComponentName name) {
myservice = null;
Toast.makeText(MainActivity.this, "Service connected", Toast.LENGTH_LONG)
.show();
}
}
private void initService() {
connection = new AdditionServiceConnection();
Intent i = new Intent();
i.setClassName("com.example",com.example.counter.MainActivity.class.getName());
boolean ret = bindService(i, connection, Context.BIND_AUTO_CREATE);
}
private void releaseService() {
unbindService(connection);
connection = null;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initService();
Button update = (Button)findViewById(R.id.button1);
update.setOnClickListener(new View.OnClickListener() {
TextView value=(TextView)findViewById(R.id.textView1);
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int val,res=-1;
val=Integer.parseInt(value.getText().toString());
try{
res=myservice.updateCounter(val);
}
catch(Exception e)
{e.printStackTrace();}
value.setText(res);
}
});
}
protected void onDestroy() {
releaseService();
}
}
Convert res into text format by applying following code and try
String str = String.valueOf(res);
value.setText(str);
I got where I was lacking. I didnt register this service in the menifest file and therefore was not able to use it.
I currently have a running service that receives messages from sockets every time another user sends someone a message. Now in the activity I can easily call a dialog to display a notice that a message has been received, however I want to do that from the running service. How can I get about with this?
Here is my running service.
public class MyService extends Service implements ChatCallbackAdapter {
public StartSocket connect;
public static Context mContent;
private ConnectSocket connectsocket;
final Context context = this;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onStart(Intent intent, int startId) {
System.out.println("Service is running");
connectsocket= new ConnectSocket(this);
connectsocket.start();
connect=new StartSocket();
}
public void startNotification(){
Intent intent = new Intent(this, ReceiveNotification.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
// Build notification
// Actions are just fake
Notification noti = new Notification.Builder(this)
.setContentTitle("Received a message")
.setContentText("Subject").setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent)
.addAction(R.drawable.ic_launcher, "Rply", pIntent)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Hide the notification after its selected
noti.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, noti);
}
#Override
public void callback(JSONArray data) throws JSONException {
// TODO Auto-generated method stub
}
#Override
public void on(String event, JSONObject data) {
// TODO Auto-generated method stub
}
#Override
public void onMessage(String message) {
// TODO Auto-generated method stub
}
#Override
public void onMessage(JSONObject json) {
// TODO Auto-generated method stub
}
#Override
public void onConnect() {
// TODO Auto-generated method stub
}
#Override
public void onDisconnect() {
// TODO Auto-generated method stub
}
#Override
public void onConnectFailure() {
// TODO Auto-generated method stub
}
#Override
public void onMessageReceived(Message m) {
// TODO Auto-generated method stub
System.out.println("Received a message in service");
if(m.status.equals("ready")){
connectsocket.login(SaveSharedPreference.getUserName(getApplicationContext()), SaveSharedPreference.getUserId(getApplicationContext()));
connectsocket.subscribe();
}
if(m.status.equals("message")){
//getMsg(m.msg, m.name);
startNotification();
System.out.println("Received a message "+m.msg+" and a name "+m.name);
final String name=m.name;
final String pid=m.pid;
final String msg=m.msg;
//Intent intenter=new Intent(TabExercise.this, CreateNotification.class);
//startActivity(intenter);
//runOnUiThread(new Runnable(){
//public void run(){
//Handler handler = new Handler(Looper.getMainLooper());
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder.setTitle(name+" just sent you a message");
alertDialogBuilder.setMessage("Click yes to go to the message");
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Intent inte=new Intent(MyService.this, Chat.class);
Bundle extras=new Bundle();
extras.putString("name", name);
extras.putString("pid", pid);
extras.putString("msg", msg);
inte.putExtras(extras);
startActivity(inte);
dialog.cancel();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
//}
//});
}
}
}
You have 2 options:
Use Messenger Pattern as explained in documentation here.
Use LocalBroadcastManager to send out a broadcast from service, and make the target activity implement BroadcastReceiver to listen to that broadcast.
An advantage the Messenger have is that service can select to notify one particular messenger of all its clients.
I'm developing an application. When i exit from the application, it will be opened again (The first activity is called again and again). So i couldn't able to exit from it.
In some other activities I use EXIT button and proper code to exit. Even when I click the EXIT button on those activities, it will start login activity. (login page is opened)
In my application, I use
1) Main
2) ScreenActivity
3) Login
flow: (from main->screenActivity->login)
The start page (1st activity) is posted below
public class main extends Activity {
static ConnectivityManager conMgr;
BackgroundThread backgroundThread;
TextView myText;
boolean myTextOn = true;
Cursor cursor;
String response="";
public SQLiteAdapter mySQLiteAdapter;
private SQLiteDatabase sqLiteDatabase;
SimpleCursorAdapter cursorAdapter;
public class BackgroundThread extends Thread {
boolean running = false;
void setRunning(boolean b){
running = b;
}
#Override
public void run() {
// TODO Auto-generated method stub
//super.run();
while(running){
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(Exception e)
{
}
handler.sendMessage(handler.obtainMessage());
}
}
}
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//super.handleMessage(msg);
if (myTextOn){
myTextOn = false;
myText.setVisibility(View.GONE);
}
else{
myTextOn = true;
myText.setVisibility(View.VISIBLE);
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thread);
myText = (TextView)findViewById(R.id.mytext);
}
#Override
protected void onStart() {
conMgr = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
// TODO Auto-generated method stub
super.onStart();
if(isInternetAvailable())
{
Toast.makeText(this, "online", Toast.LENGTH_LONG).show();
startActivity(new Intent(main.this, ScreenActivity.class));
}
else{
startActivity(new Intent(main.this, splashscreen.class));
Toast.makeText(this, "offline", Toast.LENGTH_LONG).show();
}
backgroundThread = new BackgroundThread();
backgroundThread.setRunning(true);
backgroundThread.start();
}
private boolean isInternetAvailable() {
ConnectivityManager cm=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
boolean retry = true;
backgroundThread.setRunning(false);
while(retry){
try {
backgroundThread.join();
retry = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(Exception e)
{
}
}
}
public void onDEstroy()
{
super.onDestroy();
}
}
ScreenActivity:
public class ScreenActivity extends Activity implements AnimationListener {
private TextView animatedView3;
//ImageView image;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
/* Animation animation1 = AnimationUtils.loadAnimation(this,
R.anim.anima);
animation1.setAnimationListener(this);
View animatedView1 = findViewById(R.id.aet1);
animatedView1.startAnimation(animation1);
/** set time to splash out */
final int welcomeScreenDisplay = 9000;
/** create a thread to show splash up to splash time */
Thread welcomeThread = new Thread() {
int wait = 0;
#Override
public void run() {
try {
super.run();
/**
* use while to get the splash time. Use sleep() to increase
* the wait variable for every 100L.
*/
while (wait < welcomeScreenDisplay) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
System.out.println("EXc=" + e);
} finally {
/**
* Called after splash times up. Do some action after splash
* times up. Here we moved to another main activity class
*/
startActivity(new Intent(ScreenActivity.this,
login.class));
}
}
};
welcomeThread.start();
}
public void onAnimationStart(Animation animation) {
}
public void onAnimationEnd(Animation animation) {
//Toast.makeText(this, "Animation ended", Toast.LENGTH_SHORT).show();
if (animatedView3.getVisibility() == View.VISIBLE) {
animatedView3.setVisibility(View.INVISIBLE);
} else {
animatedView3.setVisibility(View.VISIBLE);
}
}
public void onAnimationRepeat(Animation animation) {
// Toast.makeText(this, "Animation rep", Toast.LENGTH_SHORT).show();
}
}
Please can anyone explain about the problem and how to solve it? I didn't understand.
Place finish() in your loginActivity and for other Activities as well else stack will store the list of visited Activities.