首先,使用 Asynctask 或 IntentService 创建您的帖子类,如下所示...
public class PostIntentService extends IntentService implements PostTask.Observer {
private int counter = 0;
private int retry = 2;
private Data mData;
public PostIntentService() {
super("PostIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
mData = (Data) intent.getSerializableExtra("data");
// send updating status
Intent i = new Intent();
i.setAction(PostResponseReceiver.ACTION_RESPONSE);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.putExtra("status", "updating");
sendBroadcast(i);
execute();
counter++;
}
@Override
public void onSuccessPost(String result) {
// send success status
Intent i = new Intent();
i.setAction(PostResponseReceiver.ACTION_RESPONSE);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.putExtra("status", "success");
sendBroadcast(i);
}
@Override
public void onFailedPost(String result) {
if (counter < retry) {
execute();
counter++;
}
else {
// send failed status
Intent i = new Intent();
i.setAction(PostResponseReceiver.ACTION_RESPONSE);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.putExtra("status", "failed");
i.putExtra("data", mData);// for reproduct
sendBroadcast(i);
}
}
private void execute() {
PostTask task = new PostTask(this);
task.execute();
}
}
其次,创建您的类(扩展的 BroadcastReceiver),它在帖子完成时接收意图。
public class PostBroadcastReceiver extends BroadcastReceiver {
public static final String ACTION_RESPONSE = "com.example.android.intent.action.POST_PROCESSED";
private static final int POST_REQUEST = 100;
private Observer mObserver;
public PostBroadcastReceiver(Observer observer) {
mObserver = observer;
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getStringExtra("status").equals("updating")) {
}
else if (intent.getStringExtra("status").equals("success")) {
if (mObserver != null) {
mObserver.onPostFinished();
}
}
else if (intent.getStringExtra("status").equals("failed")) {
if (mObserver != null) {
mObserver.onPostFailed();
}
}
}
public interface Observer {
public void onPostFinished();
public void onPostFailed();
}
}
在您的清单文件中注册此服务。
<service android:name=".PostIntentService" />
在主活动的 onCreate 中注册此接收器。
IntentFilter filter = new IntentFilter(PostBroadcastReceiver.ACTION_RESPONSE);
filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new PostResponseReceiver(this);
registerReceiver(receiver, filter);
并在您的主要活动中实施以下方法。
public void onPostFinished() {
Log.d("onPostFinished", "onPostFinished");
}
public void onPostFailed() {
Log.d("onPostFailed", "onPostFailed");
}
不要忘记在主活动的 onDestroy 中取消注册此接收器。
unregisterReceiver(receiver);
最后,在您的登录 Activity 中执行传输。
Intent intent = new Intent(this, PostIntentService.class);
intent.putExtra("data", mData);
startService(intent);