1

I trying to develop an application to implement the poll notifications from server. Simply I wrote an application that checks the new data from the server. When i launch the application it run a service that checks the server periodically. There are two cases: when the Main activity is running and the application works fine. But the problem that i have when i destroyed the main activity. Because when i am checking the difference between the old data and the new data is based on the Main activity array-list ( array-list is for the list-view and it's value is from the server). Therefore, i have a problem with that if anyone can help me.

My question is : How to get the number of array-list items when the main activity is destroyed? i.e., to implement the poll notification.

UPDATED

First: this is the Main activity Class also it contains the Service that running:

public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener{

    public static boolean running;
    public SwipeRefreshLayout mSwipeRefreshLayout;
    ListView listView;
    private PendingIntent pendingIntent;

   public static ArrayAdapter<String> adapter;;
    ProgressDialog progressDialog;
   public static ArrayList<String> arrayList;
    public static String url="http://192.168.1.103/test/index.php";
    public  int number;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        running=true;

        Intent alarmIntent = new Intent(MainActivity.this, AlarmReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent, 0);

        mSwipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swipe_refresh_layout);

        listView = (ListView)findViewById(R.id.list_item);

        progressDialog=new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Wait Please ");
        progressDialog.show();
       // ArrayAdapter arrayAdapter =new ArrayAdapter(this,android.R.layout.simple_list_item_1,)



        mSwipeRefreshLayout.setOnRefreshListener(this);

        mSwipeRefreshLayout.post(new Runnable() {
                                     @Override
                                     public void run() {

                                         mSwipeRefreshLayout.setRefreshing(true);

                                         LoadNews loadNews = new LoadNews(MainActivity.this, progressDialog);
                                         loadNews.execute(url);

                                     }
                                 }
        );
    }

    @Override
    protected void onStop() {

        this.number=10;


        super.onStop();
    }

    public  int getNumber()
    {
        return number;
    }

    @Override
    protected void onDestroy() {



        super.onDestroy();

        running=false;
        this.number=10;

     //  AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
       // manager.cancel(pendingIntent);


    }

    private  void refreshcontent() {

       LoadNews loadNews=new LoadNews(MainActivity.this,progressDialog);
       loadNews.execute(url);
        if(arrayList.size()==0);
           // Toast.makeText(getApplicationContext(),"EMPTY",Toast.LENGTH_LONG).show();
        else {
           // Toast.makeText(getApplicationContext(),"NOT",Toast.LENGTH_LONG).show();
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, arrayList);
        listView.setAdapter(adapter);}
        mSwipeRefreshLayout.setRefreshing(false);
      //  MainActivity.number_items=listView.getCount();
    }



    @Override
    public  void onRefresh() {

        refreshcontent();
    }



    public void Setads(ArrayList<String> studentslist) {

      arrayList=studentslist;

        Collections.reverse(arrayList);

       adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,arrayList);
        listView.setAdapter(adapter);
        mSwipeRefreshLayout.setRefreshing(false);

        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        int interval = 20000;
        Intent alarmIntent = new Intent(MainActivity.this, MyService.class);

        Intent intent;
        manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);


    }



   public static class MyService extends IntentService {
        /**
         * Creates an IntentService.  Invoked by your subclass's constructor.
         *
         * @param name Used to name the worker thread, important only for debugging.
         */


        int x;



       public static final String name="My_Worker_Thread";


        public MyService() {
            super(name);

        }

       /**
        * Creates an IntentService.  Invoked by your subclass's constructor.
        *
        * @param name Used to name the worker thread, important only for debugging.
        */


       @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
       //     Toast.makeText(getApplicationContext(),"Test",Toast.LENGTH_LONG).show();

            if (MainActivity.running)
            {  Toast.makeText(getApplicationContext(),"Run",Toast.LENGTH_LONG).show();

                RequestQueue requestQueue= Volley.newRequestQueue(this);

                JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(Request.Method.POST, url,new Response.Listener<JSONArray>(){
                    public void onResponse(JSONArray jsonArray) {


                      int temp=MainActivity.arrayList.size();

                        if(jsonArray.length()==temp)
                        {
                            //Toast.makeText(getApplicationContext(),"OLD",Toast.LENGTH_LONG).show();
                        }
                        else {
                            if (jsonArray.length() >temp && jsonArray.length() != temp) {

                                for (int i =temp ; i < jsonArray.length(); i++) {
                                    try {
                                        JSONObject jsonObject = jsonArray.getJSONObject(i);

                                        String title=jsonObject.getString("title");


                                        Bitmap icon = BitmapFactory.decodeResource(getResources(),
                                                R.drawable.ic_launcher);
                                        MainActivity.arrayList.add(0, title);

                                        PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getApplicationContext(), MainActivity.class), 0);
                                        // Resources r = getResources();
                                        Notification notification = new NotificationCompat.Builder(getApplicationContext())
                                                .setTicker("CASI")
                                                .setSubText(jsonObject.getString("title"))
                                                .setLargeIcon(icon)
                                                .setContentTitle(jsonObject.getString("title"))
                                                .setContentText(jsonObject.getString("title"))
                                                .setContentIntent(pi)
                                                .setAutoCancel(true)
                                                .setSmallIcon(R.drawable.ic_launcher)
                                                .build();

                                        Random random = new Random();
                                        int m = random.nextInt(9999 - 1000) + 1000;

                                        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                                        notificationManager.notify(m, notification);
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }

                                MainActivity.adapter.notifyDataSetChanged();

                            }

                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e("Error", "Unable to parse json array");
                    }
                });
                // add json array request to the request queue
                requestQueue.add(jsonArrayRequest);


            }

            else{

                Toast.makeText(getApplicationContext(),"OFF",Toast.LENGTH_SHORT).show();

                // Toast.makeText(getApplicationContext(),"Run",Toast.LENGTH_LONG).show();



                RequestQueue requestQueue= Volley.newRequestQueue(this);

                JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(Request.Method.POST, "http://192.168.1.103/test/count.php",new Response.Listener<JSONArray>(){
                    public void onResponse(JSONArray jsonArray) {

                       // Toast.makeText(getApplicationContext(),""+temp,Toast.LENGTH_LONG).show();


                            if (jsonArray.length() >0) {

                                for (int i =0 ; i < jsonArray.length(); i++) {
                                    try {
                                        JSONObject jsonObject = jsonArray.getJSONObject(i);

                                        String title=jsonObject.getString("title");
                                        String sub=jsonObject.getString("sub");



                                       if (Integer.parseInt(title)==Integer.parseInt(sub)){
                                           Toast.makeText(getApplicationContext(),"No Changer",Toast.LENGTH_SHORT).show();}
                                        else
                                           Toast.makeText(getApplicationContext(),"New Data",Toast.LENGTH_SHORT).show();

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

                                // MainActivity.adapter.notifyDataSetChanged();

                            }


                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e("Error", "Unable to parse json array");
                    }
                });
                // add json array request to the request queue
                requestQueue.add(jsonArrayRequest);

              //  Toast.makeText(getApplicationContext(),"Nuber"+x,Toast.LENGTH_SHORT).show();
               // Toast.makeText(getApplicationContext(),"Nuber"+getX(),Toast.LENGTH_SHORT).show();


            }

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

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




        @Override
        protected void onHandleIntent(Intent intent) {

            synchronized (this){


                int count=0;
                while (count<10) {
                    try {
                        wait(150);
                        count++;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }


        }
    }




}

And this is the AlarmReciver class:

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        // For our recurring task, we'll just display a message
       //Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
        Intent intent2=new Intent(context,MainActivity.MyService.class);

        context.startService(intent2);
    }
}

Also this is the Load News Class, I used it to get the values for the list-view and to get the numbers of items in main activity:

public class LoadNews extends AsyncTask<String,Void,String> {

   MainActivity mainActivity;
    Context context;
    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    public LoadNews(MainActivity mainActivity, ProgressDialog progressDialog)
    {
        this.mainActivity=mainActivity;
       context=this.mainActivity.getApplicationContext();
        this.progressDialog=progressDialog;



    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        ArrayList<String> newstitles=new ArrayList<String>();



        try {
            JSONArray students=new JSONArray(s);

            for (int i=0;i<students.length();i++)
            {
                JSONObject student= students.getJSONObject(i);

                String studentname=student.getString("title");


               newstitles.add(studentname);



            }

          // mainActivity.number=newstitles.size();
            mainActivity.Setads(newstitles);

            progressDialog.dismiss();
           // progressDialog.dismiss();
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }


    @Override
    protected String doInBackground(String... params) {

        HttpURLConnection connection=null;
        InputStream inputStream=null;
        ByteArrayOutputStream content=null;
        try {

            URL url=new URL(params[0]);


            connection= (HttpURLConnection) url.openConnection();
            connection.connect();
            if(connection.getResponseCode()!=HttpURLConnection.HTTP_OK)
            {
                Log.d("Server Erppr", connection.getResponseMessage());
                return "Error in Connection to server|";



            }

            Log.d("Connection Error",connection.getResponseMessage());
            inputStream=connection.getInputStream();
            content=new ByteArrayOutputStream();



            byte [] buff=new byte[2048];

            long total=0;
            int count=0;

            while ((count=inputStream.read(buff))!=-1)
            {

                content.write(buff,0,count);
                total=total+count;

            }






        }
        catch (Exception ex){

            ex.printStackTrace();

        }

        finally {
            try {
                inputStream.close();
                connection.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }


        return new String(content.toByteArray());
    }
}

Finally, Mainifest.Xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="subhi.com.myapplication">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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


        <receiver android:name=".AlarmReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <service android:name=".MainActivity$MyService"></service>

    </application>

</manifest>
Dodo Dodo
  • 43
  • 2
  • 10

1 Answers1

1

To get the number of items, you need to establish a communication between the Activity and Service. For this, you need to implement the Messenger.

Messenger allows for the implementation of message-based communication across processes by help of Handlers.

Handler is a that allows you to send and process these messages.

Steps for implementing a Messenger:

  1. Service implements a Handler which receives the callbacks from the Activity

  2. The Handler then creates a Messenger object which further on creates an IBinder that the Service returns to the Activity.

  3. Activity then uses the IBinder to instantiate the Messenger, which the Activity uses to send messages to the Service.

  4. The Service receives the messages in the Handler created in the 1st step.

Lets now understand it with an example:

Create a Handler in the Service like this:

class ServiceHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            default:
                super.handleMessage(msg);
        }
    }
}

Now, add the Messenger object along with onBind() method to the Service as mentioned in 2nd step above:

final Messenger messenger = new Messenger(new ServiceHandler());

@Override
public IBinder onBind(Intent intent) {
    return messenger.getBinder();
}

In the Activity, we will create a ServiceConnection to fetch the iBinder from the Service to instantiate the Messenger object as mentioned in the 3rd step above.

Messenger messenger;
private ServiceConnection serviceConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder iBinder) {
        messenger = new Messenger(iBinder);
    }

    public void onServiceDisconnected(ComponentName className) {
    }
};

Bind the Service to the Activity by help of the ServiceConnection created above:

bindService(new Intent(this, MessengerService.class), serviceConnection,
        Context.BIND_AUTO_CREATE);

To send messages to the Service from the Activity, use the send() method of the Messenger object.

If you want to receive messages from the Service in the Activity, you need to create a Messenger in the Activity along with a Handler and use the replyTo parameter of the Messenger to receive messages to the respective Handler.

Updated Answer:

To send Message via Messenger do this:

  1. Create a Bundle object.

  2. Put data into the Bundle Object.

  3. Add the bundle object to the Message object.

  4. Send Message object to Service by help of Messenger object.

Example:

Bundle bundle = new Bundle();
bundle.putFloat("key", 1.0f);
Message message = Message.obtain();
message.setData(bundle);
messenger.send(message);

For more info, visit the following link:

http://developer.android.com/guide/components/bound-services.html

broschb
  • 4,976
  • 4
  • 35
  • 52
Varun Kumar
  • 1,241
  • 1
  • 9
  • 18
  • Thanks bro I followed the steps. But where to put this statement "bindService(new Intent(this, MessengerService.class), serviceConnection, Context.BIND_AUTO_CREATE);" ? Also, messenger.send() how i will put the integer value in it? – Dodo Dodo Mar 29 '16 at 07:16
  • Wherever you are starting the Service, bind the service with your Activity by the bindServide() method. Do remember, starting service and binding service are not the same. – Varun Kumar Mar 29 '16 at 07:23
  • bindService, binds the service to the Activity. If you want your Service to work in the background even if your App is not currently being used, then use both the techniques of startService and bindService together. – Varun Kumar Mar 29 '16 at 07:26
  • The link I have provided above will help you to achieve it. – Varun Kumar Mar 29 '16 at 07:26
  • messenger.send allows you to send a Message. This Message object can contain a Bundle in it. To add a Bundle to Message use the setData() method of the Message object. – Varun Kumar Mar 29 '16 at 07:28
  • Inside the Bundle, you can put any type of data like int, float, string etc. – Varun Kumar Mar 29 '16 at 07:29
  • I've updated my answer with an example to send data via messenger.send() method. – Varun Kumar Mar 29 '16 at 07:34
  • Please do have a look. – Varun Kumar Mar 29 '16 at 07:35
  • In case you have any questions, feel free to ask. – Varun Kumar Mar 29 '16 at 07:35
  • If your problem has been solved, please accept my answer. – Varun Kumar Mar 29 '16 at 09:20