当我的绑定服务更改其状态时刷新主要活动

时间:2018-01-15 10:26:04

标签: android interface notifydatasetchanged main-activity bindservice

Main Activity更改其状态时,我需要刷新Bind Service。我MainActivity的代码:

    public class MainActivity extends AppCompatActivity
        implements UDPService.OnHeadlineSelectedListener{
      protected void onStart() {
         super.onStart();
         Intent intent = new Intent(this, UDPService.class);
         bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
         //startService(intent);
     }
      private ServiceConnection myConnection = new ServiceConnection() {
            public void onServiceConnected(ComponentName className, IBinder service) {
                // This is called when the connection with the service has been
                // established, giving us the object we can use to
                // interact with the service.  We are communicating with the
                // service using a Messenger, so here we get a client-side
                // representation of that from the raw IBinder object.
                UDPService.MyLocalBinder binder = (UDPService.MyLocalBinder) service;
                myService = binder.getService();
            }
            public void onServiceDisconnected(ComponentName className) {
                // This is called when the connection with the service has been
                // unexpectedly disconnected -- that is, its process crashed.
                myService = null;
            }
        };

       protected void onCreate(Bundle savedInstanceState) {
         ... //In this part i have initialized BaseAdaptater
       }

       public static Context getContextOfApplication() {
        return contextOfApplication;
    }



       @Override
       public void onArticleSelected(int position) {
        baseAdapter.notifyDataSetChanged();
       }
}

虽然服务是:

public class UDPService extends Service  {
    private final IBinder myBinder = new MyLocalBinder();
    LampManager lm = LampManager.getInstance();
    int port = 4096;
    public String URL;
    private DatagramSocket udpSocket;
    private DatagramPacket packet;
    String text;
    static boolean bol =false;
    OnHeadlineSelectedListener mCallback;
    int i=2;
    private void listenAndWaitAndThrowIntent() throws Exception {
        byte[] message = new byte[5120];
        if(udpSocket == null || udpSocket.isClosed()){
            udpSocket = new DatagramSocket(port);
        }
        packet = new DatagramPacket(message, message.length);
        //Thread.sleep(5000);
        Log.i("UDP client: ", "about to wait to receive");
        udpSocket.receive(packet);
        String text = new String(message, 0, packet.getLength());
        this.text = text;
        Log.d("Received data", text);
        packet.getPort();
        URL = packet.getAddress().toString().replace("/", "");
        Log.d("Address", String.valueOf(packet.getAddress()));
        Log.d("Port", String.valueOf(packet.getPort()));
        udpSocket.close();
    }

    Thread UDPBroadcastThread;

    void startListenForUDPBroadcast(){
        UDPBroadcastThread = new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                while (true) {
                    try {
                        listenAndWaitAndThrowIntent();
                         bol = lm.addLamp(URL,text);
                        mCallback = (OnHeadlineSelectedListener) MainActivity.getContextOfApplication();
                        mCallback.onArticleSelected(i);
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        Log.i("UDP", e.getMessage());
                    }
                }
            }
        });
        UDPBroadcastThread.start();
    }

    private void stopListen() {
        udpSocket.close();
    }




    @Override
    public void onDestroy() {
        stopListen();
    }

    /*public int onStartCommand(Intent intent, int flags, int startId){
        startListenForUDPBroadcast();
        Log.i("UDP", "Service Started");
        return START_STICKY;
    }*/
    @Override
    public void onCreate(){
        super.onCreate();
        startListenForUDPBroadcast();
    }
    @Override
    public IBinder onBind(Intent intent) {
        // We don't provide binding, so return null
        Log.i("UDP", "Service Started");
        return myBinder;
    }

    public interface OnHeadlineSelectedListener {
        void onArticleSelected(int position);
    }

    public class MyLocalBinder extends Binder {
        UDPService getService() {
            return UDPService.this;
        }
        }
}

ActivityListview,方法addLamp(URL,text)Lamp添加到列表中。我需要刷新主要活动,当bol返回true时,我调用notifyDataSetChanged()来刷新listView。该代码有效,因为在主活动中调用包含onCreate()的{​​{1}}时,使用notifyDataSetChanged()创建的lamp刷新列表。我的问题是addLamp并非来自Servicelooper的代码是:

addLamp

public class LampManager extends AppCompatActivity { private static final LampManager ourInstance = new LampManager(); private List<Lamp> lista = new ArrayList(); Context applicationContext = MainActivity.getContextOfApplication(); public boolean addLamp(String URL, String name) throws InterruptedException{ String ip = URL.replace("/", ""); Log.i("UDP", "Messagio ricevuto!"); boolean b = true; System.out.println(getLamps().size()); Lamp l =null; try { for(int i=0; i<getLamps().size();i++) { System.out.println(getLamp(i).getURL()); System.out.println(getLamp(i).getURL()); char c = name.charAt(name.length()-1); Thread.sleep(5000); if (lista.get(i).getName().equals(name)) { b = false; }else if(c>='0' && c<='9' && name.contains("LAMP_")) b=true; else b=false; } if(b){ System.out.println("Thread.sleep(5000)"); l = new Lamp(URL, name); new TcpClient(l, applicationContext).execute(); lista.add(l); return b; } }catch (Exception e){ Log.d("ERR",e.getMessage()); } return b; } } 的代码是:

lamp

1 个答案:

答案 0 :(得分:0)

使用界面

首先,在Service类上定义一个接口:

    // Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
    public void onArticleSelected(int position);
}

现在,片段可以通过使用OnHeadlineSelectedListener接口的mCallback实例调用onArticleSelected()方法(或接口中的其他方法)来向活动传递消息。

然后,在活动:

public static class MainActivity extends Activity
    implements HeadlinesFragment.OnHeadlineSelectedListener{
...

public void onArticleSelected(int position) {
    // The user selected the headline of an article from the HeadlinesFragment
    // Do something here to display that article
}

}

成功:D