D.Razvan
D.Razvan

Reputation: 435

Android service with handler and thread

I have an application which starts a new service. In this service I currently have a handler that does some work every minute and then sends the results to the main activity through a BroadcastReceiver. I want the following thing: Every minute create a new thread inside the service, make it do the work and send a message to the handler that it is finnished and then the handler will send to the main activity through a BroadcastReceiver. How can i combine the Thread and the Handler? Here is what I have so far -only part of code of interest-

private Runnable sendUpdatesToUI = new Runnable() {



    public void run() {
        try {
            getAppResources(); //this is the work i want to place in a new thread
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        intent.putExtra(key,value);
        sendBroadcast(intent);
        handler.postDelayed(this, 60*1000); 
    }
};

Here is what i understand i need to do

 private Runnable sendUpdatesToUI = new Runnable() {

    public void run() {
       /* try {
            getAppResources();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/

         Thread t = new Thread() {
            @Override
            public void run(){
                 try {
                    getAppResources();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
               handler.sendEmptyMessage(0);
            }
        };


        handler.postDelayed(this, 60*1000); 
    }
};

And where do i place the handleMessage ? If i place it inside the Runnable it says it is never used locally. I just place it right before the Runnable ?

 public void handleMessage(Message msg){
    if(msg.what == 0){
        intent.putExtra(key,value);
        sendBroadcast(intent);
    }
 }

Is this how I should do it ?

EDIT: Handler code that sends to the main activity some data

 private final Handler handler = new Handler(){
     public void handleMessage(Message msg){
        if(msg.what == 0){
             Log.d("HANDLE","Am primit mesaj");
            //Notify preparations
            intent.putExtra("RunningApps", runningApps.size());
            intent.putExtra("CPU", highestDrainPackageCPU);

            intent.putExtra("GPS",highestDrainPackageGPS);
            intent.putExtra("WIFI", highestDrainPackageWIFI);

            //Now i have all my data, time to send them to the activity
            //First , send the strings to be set in the TextViews
            //Each running app has 7 messages to display -> ArrayList<String>
            for(int i=0;i<runningApps.size();i++){
                intent.putStringArrayListExtra(String.valueOf(i), appInfo.get(i));
            }

            //Next send values to plot the chart
            //CPU energy consumption for highest draining application
            double [] currValues_cpu = new double[tableCPU.get(highestDrainPackageCPU).size()];
            Log.d("CPUSIZE",String.valueOf(currValues_cpu.length));
            for(int j=0;j<tableCPU.get(highestDrainPackageCPU).size();j++){
                currValues_cpu[j]=tableCPU.get(highestDrainPackageCPU).get(j);
                Log.d("CPUVALUE",String.valueOf(currValues_cpu[j])+"For application"+highestDrainPackageCPU);
            }

            intent.putExtra("highestDrainPackageCPU", currValues_cpu);


            //GPS energy consumption for highest draining application
            double [] currValues_gps = new double[tableGPS.get(highestDrainPackageGPS).size()];
            for(int j=0;j<tableGPS.get(highestDrainPackageGPS).size();j++){
                currValues_gps[j]=tableGPS.get(highestDrainPackageGPS).get(j);
            }
            intent.putExtra("highestDrainPackageGPS", currValues_gps);

            //WIFI energy consumption for highest draining application
            double [] currValues_wifi = new double[tableWIFI.get(highestDrainPackageWIFI).size()];
            for(int j=0;j<tableWIFI.get(highestDrainPackageWIFI).size();j++){
                currValues_wifi[j]=tableWIFI.get(highestDrainPackageWIFI).get(j);
            }
            intent.putExtra("highestDrainPackageWIFI", currValues_wifi);

            sendBroadcast(intent);

        }
    }
};

Here is the BroadcastReceiver in the Main Activity and the UpdateUI function:

 private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        updateUI(intent);       
    }
};

public void updateUI(Intent intent){

    resourceTab.removeAllViews();
    //statisticsTab.removeAllViews();

    int apps_no = intent.getIntExtra("RunningApps", 0);

    String highestDrainPackageCPU = intent.getStringExtra("CPU");

    String highestDrainPackageGPS = intent.getStringExtra("GPS");

    String highestDrainPackageWIFI = intent.getStringExtra("WIFI");


    //TO-DO: Get information for each app and store it in textview.Then add it to a linearlayout
    for(int i=0;i<apps_no;i++){

        //Setup delimiter
        View delimitator = new View(this);
        delimitator.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,1));
        delimitator.setBackgroundColor(Color.parseColor("#50FFFFFF"));

        //Extract values
        ArrayList<String> info = new ArrayList<String>();
        info=intent.getStringArrayListExtra(String.valueOf(i));

        for(int j=0;j<info.size();j++){
            TextView infoApp = new TextView(this);
            //////Setup textview//////////
            infoApp = new TextView(this);
            infoApp.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
            infoApp.setTextColor(Color.parseColor("#FFFFFF"));
            infoApp.setText(info.get(j));

            resourceTab.addView(infoApp);
        }

        //Add delimiter
        resourceTab.addView(delimitator);
    }

    double [] cpu_values = intent.getDoubleArrayExtra("highestDrainPackageCPU");

    double [] gps_values = intent.getDoubleArrayExtra("highestDrainPackageGPS");

    double [] wifi_values = intent.getDoubleArrayExtra("highestDrainPackageWIFI");

    //Now plot the graph
    createGraphOverall(cpu_values, gps_values, wifi_values, highestDrainPackageCPU, highestDrainPackageGPS, highestDrainPackageWIFI);

    //Update the table
    updateTable(cpu_values, gps_values, wifi_values, highestDrainPackageCPU, highestDrainPackageGPS, highestDrainPackageWIFI);

}

My Activity was successfully updated before I tried to create a new thread to do the heavy work inside the service.

Upvotes: 1

Views: 4557

Answers (1)

MikeHelland
MikeHelland

Reputation: 1159

EDIT: Sorry, I think I noticed it earlier, and got side tracked with the handler.

You create Thread t, but you never run it.

t.start();

You define handleMessage() as a method of the handler, like this:

handler = new Handler() {

    @Override
    public void handleMessage(Message msg) {

        //TODO: Handle different types of messages

   }
};

Upvotes: 2

Related Questions