Context trick

1
2
3
4
5
6
7
8
9
10
public class MyApplication extends Application {
private static Context context;
@Override
public void onCreate() {
context = getApplicationContext();
}
public static Context getContext() {
return context;
}
}

Changes in AndroidManifest.xml

1
2
3
4
5
6
7
8
9
10
11
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.networktest"
android:versionCode="1"
android:versionName="1.0" >

……
<application
android:name="com.example.networktest.MyApplication"
…… >

……
</application>
</manifest>

Access context wherever you needed, for example:

1
2
3
4
5
6
7
8
9
10
11
public static void sendHttpRequest(final String address,
final HttpCallbackListener listener)
{

…… //do something
if (!isNetworkAvailable()) {
Toast.makeText(MyApplication.getContext()
, "network is unavailable"
,Toast.LENGTH_SHORT).show();
return;
}
…… //do something
}