0

我有一项服务和一项活动。在服务中,我广播从网络收到的消息,并在活动中显示这些消息。这很好用。但是当活动在后台时,所有消息都会丢失。

如何在 onResume(或 onCreate)活动中从服务器获取最后一条消息(如果存在)?

编辑: 服务中:

public class server extends Service implements Runnable
{
    @Override
    public void onCreate()
    {

    }

    @Override
    public IBinder onBind(Intent arg0)
    {
        return null;
    }

    @Override
    public void onStart(Intent intent, int startID)
    {   
        //initializing socket and begining listen
        new Thread(this).start();
    }

    public void run()
    {
        String readed;
        while (true)
        {
            if(reader == null) continue;
            try
            {
                if ((readed = reader.readLine()) != null)
                {
                    Intent intent = new Intent(SEND_DATA_INTENT);
                    intent.putExtra("type", "message");
                    intent.putExtra("content", readed.substring(1));
                    sendBroadcast(intent);
                    Thread.sleep(100);
                }
            }
            catch (Exception ee) { }
        }
    }
}

并在活动中:

public class menhaj extends Activity
{
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    @Override
    protected void onResume()
    {
        if (dataUpdateReceiver == null) dataUpdateReceiver = new DataReciver();
        IntentFilter intentFilter = new IntentFilter(server.SEND_DATA_INTENT);
        registerReceiver(dataUpdateReceiver, intentFilter);
        super.onResume();
    };

    @Override
    protected void onPause()
    {
        if (dataUpdateReceiver != null) unregisterReceiver(dataUpdateReceiver);
        super.onPause();
    };

    private class DataReciver extends BroadcastReceiver
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            if (intent.getAction().equals(server.SEND_DATA_INTENT))
            {
                Bundle bdl = intent.getExtras();
                String type = bdl.getString("type");
                if (type.equals("message"))
                {
                    String message = bdl.getString("content");
                    db.addMessage(message);
                    showMessage(message);
                }
            }
        }
    }
}
4

2 回答 2

1

If that activity is in the background, the user probably doesn't want to see messages from it. Show notifications from your services instead. Generally, an activity should de-register itself onPause() and register again onResume() when it comes back to the foreground.

于 2012-12-27T15:16:00.957 回答
0

I would declare BroadcastReceivers , those can receive messages and bring back to from your avtivity / app

于 2012-12-27T15:13:30.160 回答