HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Performing a background task and managing battery notifications for Android

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
performingmanagingbackgroundandroidbatterynotificationsforandtask

Problem

On the main view, all you see is a button to click on that says, "start setup". Once the user clicks on Start Setup, a file is read in the background and a progress bar is shown in the main thread. Once the "setup" is complete, a "Setup Complete" notification should pop up. After that, some kind of status indicating the battery level or status should display to the user.

Here are my attempts so far. I've included it in a Pastebin. Feel free to ask me if you would like to see the views or something else.

```
//Main Activity.java

package com.example.Patient_Device;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.io.*;

public class MainActivity extends Activity {

//fields
private ProgressDialog progressBar;
private Context context;

/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_setup);
//Set the context
context = this;

//Initialize the start setup button and add an onClick event listener to the button
final Button start_setup_button = (Button) findViewById(R.id.start_setup_button);
start_setup_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {

//Executes the AsyncTask
new RetrieveInfoTask().execute();

//Instantiates the intent to launch a new activity
Intent myIntent = new Intent(MainActivity.this, RetrieveInfoActivity.class);
MainActivity.this.startActivity(myIntent);

}
});
}

public class RetrieveInfoTask extends AsyncTask {

//Call

Solution

//Methods that retrieves information from the user device. This is performed in the Background thread
    private void retrieveInfo() {

        try {

            //Reading the drawable resource line by line
            String str="";
            StringBuffer buf = new StringBuffer();
            InputStream is = MainActivity.this.getResources().openRawResource(R.drawable.user_info);
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            if (is!=null) {
                while ((str = reader.readLine()) != null) {
                    buf.append(str + "\n" );
                }
            }
            is.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


This method doesn't return any result.
You read into a buffer and then you discard it.

Lets say you return the contents of the buffer. Just to give this function some purpose.

This code, whilst involved in multi-threaded code, runs on a single thread. You create a new InputStream, one that you won't share. So the StringBuffer doesn't need to be synchronized. As a result, you can use StringBuilder. It's faster.

For more details on StringBuilder versus StringBuffer, see this Stack Overflow question.
https://stackoverflow.com/questions/355089/stringbuilder-and-stringbuffer

Only put in a try statement what you need to put in a try statement.

try {

            //Reading the drawable resource line by line
            String str="";
            StringBuffer buf = new StringBuffer();
            InputStream is = MainActivity.this.getResources().openRawResource(R.drawable.user_info);
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            if (is!=null) {
                while ((str = reader.readLine()) != null) {
                    buf.append(str + "\n" );
                }
            }
            is.close();

        }


String str is not exceptional, so it goes out of the try statement.

Neither is the buffer.

The InputStream might throw Resources.NotFoundException.

The BufferedReader can throw IOException.

So we get this:

String str="";
        StringBuffer buf = new StringBuffer();
        try {

            //Reading the drawable resource line by line

            InputStream is = MainActivity.this.getResources().openRawResource(R.drawable.user_info);
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            if (is!=null) {
                while ((str = reader.readLine()) != null) {
                    buf.append(str + "\n" );
                }
            }
            is.close();

        }


And then we only catch that which CAN be thrown

catch (IOException | Resources.NotFoundException e) {
            e.printStackTrace();
        }


(You might wanna do something sensible with it, like error handling).

Code Snippets

//Methods that retrieves information from the user device. This is performed in the Background thread
    private void retrieveInfo() {

        try {

            //Reading the drawable resource line by line
            String str="";
            StringBuffer buf = new StringBuffer();
            InputStream is = MainActivity.this.getResources().openRawResource(R.drawable.user_info);
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            if (is!=null) {
                while ((str = reader.readLine()) != null) {
                    buf.append(str + "\n" );
                }
            }
            is.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
try {

            //Reading the drawable resource line by line
            String str="";
            StringBuffer buf = new StringBuffer();
            InputStream is = MainActivity.this.getResources().openRawResource(R.drawable.user_info);
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            if (is!=null) {
                while ((str = reader.readLine()) != null) {
                    buf.append(str + "\n" );
                }
            }
            is.close();

        }
String str="";
        StringBuffer buf = new StringBuffer();
        try {

            //Reading the drawable resource line by line

            InputStream is = MainActivity.this.getResources().openRawResource(R.drawable.user_info);
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            if (is!=null) {
                while ((str = reader.readLine()) != null) {
                    buf.append(str + "\n" );
                }
            }
            is.close();

        }
catch (IOException | Resources.NotFoundException e) {
            e.printStackTrace();
        }

Context

StackExchange Code Review Q#63588, answer score: 2

Revisions (0)

No revisions yet.