将数据从活动发送到服务UPDATED

时间:2016-03-29 06:18:55

标签: android android-activity service android-service android-notifications

我尝试开发一个应用程序来实现来自服务器的轮询通知。我只是编写了一个应用程序,用于检查服务器中的新数据。当我启动应用程序时,它会运行一个定期检查服务器的服务。有两种情况:Main活动正在运行且应用程序正常运行。但是当我摧毁主要活动时我遇到的问题。因为当我检查旧数据和新数据之间的差异是基于主活动数组列表(数组列表用于列表视图,它的值来自服务器)。因此,如果有人可以帮助我,我有一个问题。

我的问题是:如何在主要活动被销毁时获取数组列表项的数量?即实施民意调查通知。

已更新

首先:这是Main活动类,它还包含运行的服务:

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

                }
            }


        }
    }




}

这是AlarmReciver类:

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

这也是Load News Class,我用它来获取list-view的值并获取主要活动中的项目数:

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

最后,Mainifest.Xml文件:

<?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>

1 个答案:

答案 0 :(得分:1)

要获取项目数,您需要在活动和服务之间建立通信。为此,您需要实现Messenger。

Messenger允许在Handler的帮助下跨进程实现基于消息的通信。

处理程序允许您发送和处理这些消息。

实施Messenger的步骤:

  1. Service实现一个Handler,它接收来自Activity

  2. 的回调
  3. Handler然后创建一个Messenger对象,进一步创建一个IBinder,服务返回到Activity。

  4. Activity然后使用IBinder实例化Messenger,Activity用于向服务发送消息。

  5. 服务接收第1步中创建的处理程序中的消息。

  6. 现在让我们用一个例子来理解它:

    在服务中创建一个处理程序,如下所示:

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

    现在,将Messenger对象和onBind()方法添加到服务中,如上面第2步所述:

    final Messenger messenger = new Messenger(new ServiceHandler());
    
    @Override
    public IBinder onBind(Intent intent) {
        return messenger.getBinder();
    }
    

    在Activity中,我们将创建一个ServiceConnection来从服务中获取iBinder以实例化Messenger对象,如上面第3步所述。

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

    借助上面创建的ServiceConnection将服务绑定到活动:

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

    要从Activity向服务发送消息,请使用Messenger对象的send()方法。

    如果要在活动中接收来自服务的消息,您需要在活动中创建一个Messenger以及一个处理程序,并使用Messenger的replyTo参数接收发送给相应处理程序的消息。

    更新答案:

    通过Messenger发送消息执行此操作:

    1. 创建一个Bundle对象。

    2. 将数据放入Bundle对象。

    3. 将捆绑对象添加到Message对象。

    4. 通过Messenger对象的帮助将Message对象发送到Service。

    5. 示例:

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

      有关详细信息,请访问以下链接:

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