Search code examples
javaandroidmultithreadinguser-interfacebackground-process

Setting up a background process with Threading to handle work in Android


Hello I am trying to create a sample app when executed, will bring you back to the home screen , run a back ground process, and display toast points.

I figure that I will need a separate thread in the background process to do whatever work I need. Here is the Code of my Main Activity(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();
        }
    }

Here is the Code from "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);
}

The problem I am having is that the Toast message is not appearing. I can put breakpoints and see that it is stepping through the code but no message appears. I think it might be that the context is not correct? Do I need the UI's Context(BackGroundPRcessExampleActivity)? Any help is appreciated, thanks in advance.

D


Solution

  • With the help of the replies, this is what eventually worked for me. There is notification code added.

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

    Thank you everyone for their help.

    D