Application is repeatedly opened - java

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.

Related

Service doesn't run on continuous background location tracking

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);
}

Handling OnPause and OnResume inside fragments android

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();
}

Issues with stopping MediaPlayer

My application contains one mediaplayer with one (play/pause) button in audio.xml , but the problem is that I am not able to find right code to stop MediaPlayer before the page gets destroyed and because of that the app crashes when i log in audio page (xml) and quit without running mediaplayer , here is the code i used:
public class audio extends Langue implements Runnable,
OnClickListener, OnSeekBarChangeListener {
private SeekBar seekBar;
private Button startMedia;
// private Button stopMedia;
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audio);
seekBar = (SeekBar) findViewById(R.id.seekBar1);
startMedia = (Button) findViewById(R.id.button1);
//stopMedia = (Button) findViewById(R.id.button2);
startMedia.setOnClickListener(this);
//stopMedia.setOnClickListener(this);
seekBar.setOnSeekBarChangeListener(this);
seekBar.setEnabled(false);
}
public void run() {
int currentPosition = mp.getCurrentPosition();
int total = mp.getDuration();
while (mp != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
public void onClick(View v) {
if (v.equals(startMedia)) {
if (mp == null) {
mp = MediaPlayer.create(getApplicationContext(), R.raw.espoir);
seekBar.setEnabled(true);
}
if (mp.isPlaying()) {
mp.pause();
startMedia.setText("Play");
} else {
mp.start();
startMedia.setText("Pause");
seekBar.setMax(mp.getDuration());
new Thread(this).start();
}
}
/* if (v.equals(stopMedia) && mp != null) {
if (mp.isPlaying() || mp.getDuration() > 0) {
mp.stop();
mp = null;
startMedia.setText("Play");
seekBar.setProgress(0);
}
}
*/
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
try {
if (mp.isPlaying() || mp != null) {
if (fromUser)
mp.seekTo(progress);
} else if (mp == null) {
Toast.makeText(getApplicationContext(), "Media is not running",
Toast.LENGTH_SHORT).show();
seekBar.setProgress(0);
}
} catch (Exception e) {
Log.e("seek bar", "" + e);
seekBar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
// stop song
#Override
protected void onPause(){
super.onPause();
mp.stop();
finish();
}
}
Do something like this into the onPause() method for preventing crash
try{
mp.stop();
} catch(Exception e) {
}
finish();

Service and Notification refreshed when Activity is closed

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();
}
}

Stop threads created by Android Service

I currently have an app which when a button is pressed starts a service and within the service a thread is created.
I then have a second button (which appears once the first it pressed) that should shut down the service and in turn kill the thread, below is my current code however the service seems to stop but the thread keeps going.
public class MainActivity extends Activity {
private static Button lock = null;
private static Button unlock = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lock = (Button) this.findViewById(R.id.lock);
unlock = (Button) this.findViewById(R.id.unlock);
lock.setOnClickListener(btn_lock);
unlock.setOnClickListener(btn_unlock);
unlock.setVisibility(View.VISIBLE);
lock.setVisibility(View.GONE);
text.setVisibility(View.GONE);
startService(new Intent(this, MainService.class));
}
private OnClickListener btn_lock = new OnClickListener() {
public void onClick(View v) {
unlock.setVisibility(View.VISIBLE);
lock.setVisibility(View.GONE);
startService(new Intent(MainActivity.this, MainService.class));
}
};
private OnClickListener btn_unlock = new OnClickListener() {
public void onClick(View v) {
unlock.setVisibility(View.GONE);
lock.setVisibility(View.VISIBLE);
stopService(new Intent(MainActivity.this, MainService.class));
}
};
}
And then my service class looks like:
public class MainService extends Service {
Thread 1Thread;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
1Thread = new Thread() {
public void run() {
while(true){
try {
Thread.sleep(180000); // 3 minutes
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("TEST", "Thread is still here!");
}
}
};
}
#Override
public void onDestroy() {
1Thread.interrupt();
}
#Override
public void onStart(Intent intent, int startId) {
1Thread.start();
}
}
Hope someone can help and if you need any more info let me know!
boolean mStatus = true;
#Override
public void onCreate() {
1Thread = new Thread() {
public void run() {
while (mStatus) {
try {
Thread.sleep(180000); // 3 minutes
} catch (InterruptedException e) {
e.printStackTrace();
continue;
}
Log.i("TEST", "Thread is still here!");
}
};
}
#Override
public void onDestroy() {
mStatus = false;
1Thread.interrupt();
}
Your thread is not handling interrupt, in while loop in each iteration check if thread is interrupted, if so then do not continue the loop:
while(!Thread.currentThread().isInterrupted()){
try {
Thread.sleep(180000); // 3 minutes
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
break; //BREAK here, as thread was interrupted
}
Log.i("TEST", "Thread is still here!");
}
Also on click of second button, you should interrupt this thread:
1Thread.interrupt();

Categories