Click here to Skip to main content
15,946,525 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am new to Android programming am trying to make an app that simulates the Producer Consumer app. The specifications of the app are as under: 1. I have a Button "Produce Items" which when clicked is supposed to increment the number if items in a thread-safe container (can be anything) by 1. 2. Aside of the Main Activity, I have a local service PCService class which is supposed to act as the Consumer. 3. I have two button to Start and Stop the Service respectively. Once Started, the PCService must execute in a thread of its own so as not to block the Main UI Thread. It must consume all items, post Toast messages using a handler indicating the name of the current function being executed and also, post the number of items that were consumed from the container (say if the container has 10 items, the notification should be :10 items removed). Thereafter, the thread must sleep for say 5 seconds and then repeat the process.

So far, I have managed the following: 1. Set the Layout for my app 2. Made the necessary Service and functions to Start/Stop the service. Made a thread in the service which currently simple keeps incrementing a count variable (for debugging purpose only)

I need help with the following:
1. My Service starts properly but doesn't Stop when I click the corresponding button.
2. This is the Main Part: How do I share my container (say a variable, itemsCount) which is in my Main Activity with the Service in the desired manner. I need the Service to consume all items and send the notification to the Activity so that the count can be set to 0 and be displayed accordingly. This process has to be continuous. So what should I be using here: Broadcast Senders/Receivers, intent messages, what??!!

I just can't understand what to do here so please I need some simplified help (kindly avoid using hi-fi terms or please just elaborate on what you are trying to say, because they sound good while conveying no meaning to a novice). It would be great if someone can not only guide me through this but also, asses my code for bad programming practices and other errors. Thanks in Advance :). Eagerly waiting for useful replies...

(Here is my code, I apologize for the long post but just want to make everything as clear as possible)

My activity layout, activity_pc.xml

Java
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".PCActivity" >

    <LinearLayout
        android:id="@+id/itemCountContainer"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/itemsLabelTextView"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:text="@string/itemsLabelTextView"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/itemsCountTextView"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/itemsCountTextView"
            android:textSize="20sp" />

    </LinearLayout>

    <LinearLayout 
        android:id="@+id/buttonsContainer"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="4"
        android:orientation="horizontal">

        <Button
            android:id="@+id/produceItemButton"
            android:layout_height="wrap_content"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:text="@string/produceItemButton"
            android: önClick="produceItemInContainer" /> 

    </LinearLayout>

    <LinearLayout 
        android:id="@+id/buttonsContainer"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal">

        <Button
            android:id="@+id/startServiceButton"
            android:layout_height="wrap_content"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:text="@string/startServiceButton"
            android: önClick="startPCService" /> 

        <Button
            android:id="@+id/stopServiceButton"
            style="@style/AppTheme"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/stopServiceButton"
            android: önClick="stopPCService" />

    </LinearLayout>

</LinearLayout>


PCActivity.java (Main class file)

Java
package com.example.pcservice;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;


public class PCActivity extends Activity {

    public int ContainerItems;
    PCService myService;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pc);

        ContainerItems = 0;
        TextView itemsCountTextView = (TextView) findViewById(R.id.itemsCountTextView);
        itemsCountTextView.setText(Integer.toString(ContainerItems));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.pc, menu);
        return true;
    }

    public void produceItemInContainer(View view)
    {
        ContainerItems = ContainerItems + 1;
        TextView itemsCountTextView = (TextView) findViewById(R.id.itemsCountTextView);
        itemsCountTextView.setText(Integer.toString(ContainerItems));
    }

    public int consumeItemFromContainer()
    {
        int temp = ContainerItems;
        return temp;
    }

    public void startPCService(View view)
    {
        startService(new Intent(this, PCService.class));
    }

    public void stopPCService(View view)
    {
        stopService(new Intent(this, PCService.class));
    }
}


My Service Class, PCService.java

Java
package com.example.pcservice;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

public class PCService extends Service {

    private boolean isRunning = true;

    private int countItems;

    private final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
              if(msg.arg1 == -1)
                    Toast.makeText(getApplicationContext(),"PCService.onBind()", Toast.LENGTH_LONG).show();
              else if(msg.arg1 == -2)
                  Toast.makeText(getApplicationContext(),"PCService.onCreate()", Toast.LENGTH_LONG).show();
              else if(msg.arg1 == -3)
                  Toast.makeText(getApplicationContext(),"PCService.onStartCommand()", Toast.LENGTH_LONG).show();
              else if(msg.arg1 == -4)
                  Toast.makeText(getApplicationContext(),"PCService.onDestroy()", Toast.LENGTH_LONG).show();
              else
                  Toast.makeText(getApplicationContext(),msg.arg1+"items removed", Toast.LENGTH_LONG).show();
        }
    };  

    @Override
    public IBinder onBind(Intent intent) 
    {
            Message msg = handler.obtainMessage();
            msg.arg1 = -1;
            handler.sendMessage(msg);
            //Not implemented...this sample is only for starting and stopping services.
            return null;
    }

    @Override
    public void onCreate() 
    {
            super.onCreate();
            Message msg = handler.obtainMessage();
            msg.arg1 = -2;
            handler.sendMessage(msg);
    } 

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

            //Start a Background thread
            isRunning = true;
            Thread serviceThread = new Thread(new serviceThread());
            serviceThread.start();

            Message msg = handler.obtainMessage();
            msg.arg1 = -3;
            handler.sendMessage(msg);

            // We want this service to continue running until it is explicitly
            // stopped, so return sticky.
            return START_STICKY;
    }

    @Override
    public void onDestroy() 
    {
            super.onDestroy();

            Message msg = handler.obtainMessage();
            msg.arg1 = -4;
            handler.sendMessage(msg);

            //Stop the Background thread
            isRunning = false;
    }

    //The thread in which the service shall run
    private class serviceThread implements Runnable
    {

            public void run()
            {
                    try
                    {
                            countItems = 0;
                            while(isRunning)
                            {
                                    //countItems = obj.ContainerItems;

                                    countItems++;

                                    Message msg = handler.obtainMessage();
                                    msg.arg1 = countItems;
                                    handler.sendMessage(msg);

                                    Thread.currentThread().sleep(2000);
                            }

                            System.out.println("Service Thread is finished.........");
                    }
                    catch(Exception e)
                    {
                            e.printStackTrace();
                    }
            }
    }

}


Manifest xml file:


Java
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.pcservice"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.pcservice.PCActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>

        <service
                android:name="com.example.pcservice.PCService"
                android:enabled="true" />

    </application>

</manifest>
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900