使用线程设置后台进程以处理Android中的工作

时间:2012-04-12 15:02:37

标签: java android multithreading user-interface background-process

您好我正在尝试在执行时创建示例应用,将您带回主屏幕,运行后台进程,并显示吐司点数。

我认为在后台进程中我需要一个单独的线程来完成我需要的任何工作。这是我的主要活动代码(BackGroundPrcessingExampleActivity):

enter code here
public class BackGroundProcessExampleActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        try {

            Intent myIntent = new Intent(this, MyService.class);
            startService(myIntent);

            moveTaskToBack(false);

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

以下是“MyService.java”中的代码:

enter code here
public int onStartCommand(Intent intent, int flags, int startId) {

    Toast.makeText(getBaseContext(), "Service is started!", 1).show();

    myHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            super.handleMessage(msg);


                Toast.makeText(getBaseContext(), "Hello!",
                        Toast.LENGTH_SHORT).show();
        }
    };



    Runnable runnable = new Runnable() {
        @Override
        public void run() {



            while (true) {

                try {               

                    Thread.sleep(2);

                    myHandler.sendEmptyMessage(0);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    new Thread(runnable).start();

    return super.onStartCommand(intent, flags, startId);
}

我遇到的问题是Toast消息没有出现。我可以放置断点并看到它正在逐步执行代码,但不会显示任何消息。我认为可能是背景不正确?我是否需要UI的上下文(BackGroundPRcessExampleActivity)?感谢任何帮助,提前谢谢。

d

2 个答案:

答案 0 :(得分:0)

试一试 -

public int onStartCommand(Intent intent, int flags, int startId) {
Handler mHandler = new Handler();
Toast.makeText(getApplicationContext(), "Service is started!", 1).show();

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        while (true) {
            try { 
                Thread.sleep(5000);

                mHandler.post(new Runnable() {
              @Override
               public void run() {
                        Toast.makeText(getApplicationContext(), "Hello!", Toast.LENGTH_LONG).show();
                  }
               });
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
};
new Thread(runnable).start();

return super.onStartCommand(intent, flags, startId);

}

答案 1 :(得分:0)

在回复的帮助下,这最终对我有用。已添加通知代码。

    @Override
public int onStartCommand(Intent intent, int flags, int startId) {

    final NotificationManager notificationManager = (NotificationManager) 
            getSystemService(NOTIFICATION_SERVICE);

    // Create Notifcation
    final Notification notification = new Notification(R.drawable.ic_launcher,
        "A new notification", System.currentTimeMillis());

    // Cancel the notification after its selected
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    //
    notification.number += 1;

    // Specify the called Activity
    Intent intent2 = new Intent(this, NotificationReceiver.class);

    Toast.makeText(getApplicationContext(), "Service is started!", 1)
            .show();

    PendingIntent activity = PendingIntent.getActivity(this, 0, intent2, 0);
    notification.setLatestEventInfo(this, "This is the title",
        "This is the text", activity);


    myHandler = new Handler();

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            int i = 0;

            while (true) {
                final int x = i++;

                try {
                    Thread.sleep(500);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }

                myHandler.post(new Runnable() {

                    @Override
                    public void run() {

                        try {
                            Toast.makeText(getApplicationContext(),
                                    "Hello!" + String.valueOf(x),
                                    3).show();

                            if(x == 100)
                                notificationManager.notify(0, notification);
                            Thread.sleep(1);

                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    };
    new Thread(runnable).start();

谢谢大家的帮助。

d