public
interface
RetrofitInterface
{
// asinxron callback
@GET
(
"/api/user_foydalanuvchi"
)
User
getUser
(
@Query
(
"user_id"
)
int
userId
,
Callback
<
User
>
callback
);
// sinxron post metodi
@POST
(
"/api/user/register"
)
User
registerUser
(
@Body
User user
);
}
// misol
RetrofitInterface retrofitInterface
=
new
RestAdapter
.
Builder
()
.
setEndpoint
(
API
.
API_URL
).
build
().
create
(
RetrofitInterface
.
class
);
// 2048-id orqali foydalanuvchi malumotlarini olish
retrofitInterface
.
getUser
(
2048
,
new
Callback
<
User
>()
{
@Override
public
void
success
(
User user
,
Response response
)
{
}
@Override
public
void
failure
(
RetrofitError retrofitError
)
{
}
});
Retrofit odatda Gson formatida malumotlarni qaytaradi. Shuning uchun,
unga alohida o’zgartirilgan metodlar orqali amalga oshirish shart emas.
3.
EventBus
EventBus kutubxonasi turli xil ilovalar o'rtasidagi aloqa va xabar
almashishlarni oddiy va sodda usulda amalga oshirish imkonini beradi. Masalan,
Activity dan turib ishlab turgan servisga biror malumot yuborish, yoki fragmentlar
o'rtasida oson munosabatlarni yo'lga qo'yish (interaction). Quyidagi misolda,
Internet bilan aloqa uzilganda qanday qilib activityni ogohlantirishda ishlatiladigan
kod keltirilgan:
public class NetworkStateReceiver extends BroadcastReceiver {
//
internet bilan aloqa yo’qolganda post qiluvchi hodisa
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if(intent.getExtras()!=null) {
NetworkInfo ni=(NetworkInfo)
intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
// there is Internet connection
} else if(intent
.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
// no Internet connection,
tarmoq holati o’zgarganini
yuborish
EventBus.getDefault().post(new NetworkStateChanged(false));
}
}
// hodisa
public class NetworkStateChanged {
private mIsInternetConnected;
public NetworkStateChanged(boolean isInternetConnected) {
this.mIsInternetConnected = isInternetConnected;
}
public boolean isInternetConnected() {
return this.mIsInternetConnected;
}
}
public class HomeActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getDefault().register(this); // register EventBus
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this); // unregister EventBus
}
// method that will be called when someone posts an event
NetworkStateChanged
public void onEventMainThread(NetworkStateChanged event) {
if (!event.isInternetConnected()) {
Toast.makeText(this, "Aloqa uzilgan!",
Toast.LENGTH_SHORT).show();
}
} }
|