带有处理程序和线程的Android服务

时间:2014-01-19 13:08:04

标签: android multithreading android-service

我有一个启动新服务的应用程序。在这个服务中,我目前有一个处理程序,每分钟做一些工作,然后通过BroadcastReceiver将结果发送到主活动。我想要以下内容:每分钟在服务内部创建一个新线程,使其完成工作并向处理程序发送消息,使其完成,然后处理程序将通过BroadcastReceiver发送到主活动。我如何结合线程和处理程序?这是迄今为止我所拥有的代码 - 只是感兴趣的代码的一部分 -

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

这是我理解我需要做的事情

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

我在哪里放置handleMessage?如果我将它放在Runnable中,它说它从不在本地使用。我只是把它放在Runnable之前?

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

这是我应该怎么做的?

编辑:向主要活动发送一些数据的处理程序代码

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

        }
    }
};

这是Main Activity和UpdateUI函数中的BroadcastReceiver:

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

}

在我尝试创建新线程以完成服务中的繁重工作之前,我的活动已成功更新。

1 个答案:

答案 0 :(得分:2)

编辑:抱歉,我想我之前已经注意到了这一点,并且与处理程序进行了跟踪。

您创建了Thread t,但您从未运行它。

t.start();

将handleMessage()定义为处理程序的方法,如下所示:

handler = new Handler() {

    @Override
    public void handleMessage(Message msg) {

        //TODO: Handle different types of messages

   }
};