我有服务和活动。在服务中我广播从网络接收的消息,并在活动中显示这些消息。这很好用。但是当活动在后台时,所有消息都将丢失。
如何从服务器,活动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);
}
}
}
}
}
答案 0 :(得分:1)
如果该活动在后台,则用户可能不希望看到来自该活动的消息。显示来自您服务的通知。通常,活动应该取消注册自己onPause()
并在它返回前台时再次注册onResume()
。
答案 1 :(得分:0)
我会声明BroadcastReceivers,那些可以接收消息并从你的avtivity / app带回来