2

I've searched a lot on the Internet trying to find an answer for my needs, but in vain. Here's my problem: I'm making an app that "counts time". The user press "Start" button and then go away for pretty much a long time of work on the field (2h,even more). Then he has to come back and press the "End" button to show he have finished his job. My app then computes how long has he worked ( and some other thing I wont explain here ), and the user send the total of his work hours by mails to his superior. Problem is : -First my app is closed when the phone is locked and so the Start time is lost and calculations are off. -Second : the user has to repeat the Start-End cycle many times a day, so i have a way of computing the total work hours, but again it's lost when the app is closed

So I'm opened to any idea/suggestions to solve my issues :) Oh and I have Huawei P8 Lite for info, if that matters in anyway

    protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mContext=MainActivity.this;

    mTimeListenerD.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {  //Button to set the Start time
            setDebutTime();
            checkEnabled();
            writeToFile(sName,sTempsTravail);
        }
    });
    mTimeListenerF.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) { //Button to set the End Time
            setFinTime();
            checkEnabled();
            getHeureSupp(mTimeD, mTimeF);
            FindSmallest(TimeRegister);
            Clock();
            writeToFile(sName,sTempsTravail);
            readFromFile();
            try {
                copyFile(src,dst);
            } catch (IOException e) {
                e.printStackTrace();
            }
            Reinit();
        }
    });
    mMail.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            sendMail();
        }
    }); //Send data by mail
    readFromFile();
    getName();
    checkEnabled();
}
   public Calendar setDebutTime() { // Set the Start Time
    mTimeD = Calendar.getInstance();
    mTimeD.getTime();
    //Toast.makeText(this, mTimeD.getTime().toString(), Toast.LENGTH_SHORT).show();
    sDebut = mTimeD.get(Calendar.DAY_OF_MONTH) + "/" + mTimeD.get(Calendar.MONTH) + "/" + mTimeD.get(Calendar.YEAR) + "--" + mTimeD.get(Calendar.HOUR_OF_DAY) + ":" + mTimeD.get(Calendar.MINUTE) + ":" + mTimeD.get(Calendar.SECOND);
    mGetTimeDebut.setText("" + sDebut);
    start=true;
    notif=false;
    String pathToMyAttachedFile = "/Android/data/com.example.benjii.saphir_astreinte/files/Documents/SAPHIRAgent.csv"; //A changer
    File root = Environment.getExternalStorageDirectory();
    File file = new File(root, pathToMyAttachedFile);
    boolean deleted =file.delete();
    if(!deleted){file.delete();}

    return mTimeD;
}

public Calendar setFinTime() { // set the End Time
    mTimeF = Calendar.getInstance();
    mTimeF.getTime();
    // Toast.makeText(this, mTimeF.getTime().toString(), Toast.LENGTH_SHORT).show();
    sFin = mTimeF.get(Calendar.DAY_OF_MONTH) + "/" + mTimeF.get(Calendar.MONTH) + "/" + mTimeF.get(Calendar.YEAR) + "--" + mTimeF.get(Calendar.HOUR_OF_DAY) + ":" + mTimeF.get(Calendar.MINUTE) + ":" + mTimeF.get(Calendar.SECOND);
    mGetTimeFin.setText("" + sFin);
    start=false;
    notif=true;
    return mTimeF;
}

Then I have some function to do the calculations I need with the worked hours.

Once it is done I write it into a file on Internal Storage but then copy it to external storage:

      public void writeToFile(String Name,String TempsTravail){ //File that'll be send by mail
     try{
        OutputStreamWriter StrW= new OutputStreamWriter(this.openFileOutput("SAPHIRAgent.csv", Context.MODE_PRIVATE));
        src=mContext.getFilesDir().getAbsolutePath()+"/file.csv";
        dst=mContext.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath()+"/file.csv";
        //Toast.makeText(this,dst,Toast.LENGTH_LONG).show();
        StrW.append(Name);
        StrW.append(separator);
        StrW.append(sDebut);
        StrW.append(separator);
        StrW.append(sFin);
        StrW.append(separator);
        StrW.append(TempsTravail);
        StrW.append("\n"+mTempsTravail);
        if(cool){
            StrW.append(separator);
            StrW.append(sCool);
        }
        if(warning){
            StrW.append(separator);
            StrW.append(sWarning);
        }
        if(critical){
            StrW.append(separator);
            StrW.append(sCritical);
        }
        StrW.flush();
        StrW.close();
    }
    catch (IOException e){
        Log.e("ExceptionFile","Failed to write "+e.toString());
    }

}

Then I send the file by mail:

    public void sendMail(){ //SendMail function
    Intent emailIntent = new Intent(Intent.ACTION_SEND);
    final String[] to={"xxx@gmail.com"};
    final String subj="Sortie Agent "+sName;
    final String body="Voir pièce jointe";

    emailIntent.setType("text/plain");
    emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, subj);
    emailIntent.putExtra(Intent.EXTRA_TEXT, body);

    File root = Environment.getExternalStorageDirectory();
    String pathToMyAttachedFile = "/Android/data/com.example.myapp/files/Documents/file.csv";
    File file = new File(root, pathToMyAttachedFile);
    //Toast.makeText(this,"RootPath "+root.getAbsolutePath(),Toast.LENGTH_LONG).show();
    if (!file.exists() || !file.canRead()) {
        Toast.makeText(this,"ToastError",Toast.LENGTH_LONG).show();
        return;
    }
    Uri uri = Uri.fromFile(file);
    emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
    startActivity(Intent.createChooser(emailIntent, "Choisissez votre application de Mail (Gmail,Outlook...)"));

}

But as I said, my app constantly closing is such an issue to my work, I hope you have any solutions !

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Arendhal
  • 573
  • 5
  • 11

2 Answers2

1

Activity's are designed to stop once the phone sleeps. What you need is a background service that runs always.

https://developer.android.com/training/run-background-service/create-service.html

http://www.vogella.com/tutorials/AndroidServices/article.html

Matthew Shearer
  • 2,715
  • 3
  • 23
  • 32
  • Thank you for your time, I'd look into that and let you know my progess! Also can I put my entire app as a service? – Arendhal Apr 29 '17 at 09:37
  • Services do not have a UI, which it sounds like you need. – Matthew Shearer Apr 29 '17 at 15:23
  • So I've modified my app as you advised. I've added a service and doing the calculations i need by it even writing to the file, but still after some time my service is closed. Any idea on how I can get it running always? Btw I have a condition in my onStartCommand() Method which make my service working by showing a notification while the user haven't press the "End" button on the UI. At first I thought this condition would be enough but apprently not – Arendhal Apr 30 '17 at 10:48
  • May be drifting into a separate from the original problem. But maybe try something like http://stackoverflow.com/a/17256163/1856361 – Matthew Shearer Apr 30 '17 at 20:03
1

So thanks to @Matthew Shearer, I've been able to fix my issues,learn many things about services and have a fully functionnal app on all phones, but Huawei.I learnt that Huawei phones had a specific function called "Protected Apps" which gave me many problems to keep my service alive. But there is a solution here : "Protected Apps" setting on Huawei phones, and how to handle it

Copy paste the code, use the ifHuaweiAlert() in the onCreate() and enjoy!

Arendhal
  • 573
  • 5
  • 11