2
@Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.videoview);


        mVideoView = (VideoView) findViewById(R.id.videoView1);
        scanCode = getIntent().getExtras().getString("ScanCode");


         new GetVideoUrlAsyn().execute();               


        mVideoView.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                // TODO Auto-generated method stub

                startActivity(new Intent(getBaseContext(),
                        PostVideoMenuActivity.class));              
            }
        });
    }   
    private class GetVideoUrlAsyn extends AsyncTask<Void, Void,Void> {

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub          

            String URL = "http://www.storybehindthestore.com/sbtsws/service/saveinfo.asmx/StoryScanHistorySave";

            WebServiceCall webservice = new WebServiceCall();

            nameValuePairs = new ArrayList<NameValuePair>(4);               

            nameValuePairs.add(new BasicNameValuePair("iSiteID","1"));          
            nameValuePairs.add(new BasicNameValuePair("sVideoURL",scanCode));
            Log.e("scancode",""+ scanCode);
            nameValuePairs.add(new BasicNameValuePair("sDeviceID",SplashActivity.deviceId));
            Log.e("sDeviceID",""+ SplashActivity.deviceId);
            nameValuePairs.add(new BasicNameValuePair("sDeviceModel",SplashActivity.deviceModelName));
            Log.e("sDeviceModel",""+ SplashActivity.deviceModelName);

            responce = webservice.callhttppost_numvaluepair(URL, nameValuePairs);
        //  Log.e("Stiryscanstorysave responce", responce);         

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);

            //progressDialog.dismiss();         
            if (responce.contains("InCorrect QR Code !")) {

                AlertDialog adddrug1 = new AlertDialog.Builder(
                        VideoActivity.this)
                        .setTitle("Message")
                        .setMessage("InCorrect QR Code !")
                        .setPositiveButton("Ok",
                                new DialogInterface.OnClickListener() {

                                    public void onClick(DialogInterface dialog,
                                            int whichButton) {                                  

                                        startActivity(new Intent(getBaseContext(),
                                                HomeActivity.class));
                                    }

                                }).create();

                adddrug1.show();     

            }else {     

                StoryScanSaveListGet();                 
                mVideoView.setVideoURI(Uri.parse(scanCode));                      
                mVideoView.setMediaController(new MediaController(VideoActivity.this));
                mVideoView.requestFocus();          
                mVideoView.start(); 

            }
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            /*progressDialog = new ProgressDialog(VideoActivity.this);          
            progressDialog.setCancelable(false);
            progressDialog.show();  */  
        }       


        public void StoryScanSaveListGet() {
            // TODO Auto-generated method stub

            id.clear();
            site_id.clear();
            store_name.clear();
            store_url.clear();
            store_phone.clear();
            video_count.clear();

            try {

                JSONObject jmain = new JSONObject(responce);
                JSONArray jarray = jmain.getJSONArray("tblCustomer");

                JSONObject j_one = (JSONObject) jarray.get(0);

                Log.v("Responce", responce);

                for (int i = 0; i < jarray.length(); i++) {

                    j_one = (JSONObject) jarray.get(i);                         

                    id.add(j_one.get("id").toString());
                    site_id.add(j_one.get("site_id").toString());
                    store_name.add(j_one.get("store_name").toString());
                    store_url.add(j_one.get("store_url").toString());
                    store_phone.add(j_one.get("store_phone").toString());
                    video_count.add(j_one.get("video_count").toString());                                   
                }

                storeurl =j_one.get("store_url").toString();
                storephone = j_one.get("store_phone").toString();
                videocount = j_one.get("video_count").toString();
                storename = j_one.get("store_name").toString();

                Log.i("id", ""+ id);
                Log.i("site_id",  ""+ site_id);     
                Log.i("store_name", ""+ store_name);
                Log.i("store_url",  ""+ store_url);     
                Log.i("store_phone",  ""+ store_phone);
                Log.i("video_count", ""+ video_count);          


            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                responce = null;
            }
        }
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        Log.d("tag", "onPause called");
        super.onPause();
        stopPosition = mVideoView.getCurrentPosition(); // stopPosition is an
                                                        // int
        mVideoView.pause();

    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        Log.d("TAG", "onResume called");

        mVideoView.seekTo(stopPosition);
        mVideoView.start(); // 
    }   

hii i want to open alert if internet is not available and also check if response getting time out..how is it posible??? help me..here is my code of asynctask which is new GetVideoUrlAsyn().execute(); method..

Google
  • 2,183
  • 3
  • 27
  • 48
  • http://stackoverflow.com/questions/12570621/efficient-approach-to-continuously-check-whether-internet-connection-is-availabl – Tamilselvan Kalimuthu Mar 08 '13 at 06:09
  • @Tamilselvan hii i see this link..i think first i have to make broadcast receiver class and then paste that code of upper link right? – Google Mar 08 '13 at 06:15
  • no need; just implenment that broadcast receiver in the activity itself – Tamilselvan Kalimuthu Mar 08 '13 at 06:31
  • possible duplicate of [How can I monitor the network connection status in Android?](http://stackoverflow.com/questions/3307237/how-can-i-monitor-the-network-connection-status-in-android) – SWeko Mar 08 '13 at 10:00

4 Answers4

8

Check network connectivity before executing AsyncTask,

if(isNetworkAvailable(this))
{
new GetVideoUrlAsyn().execute();
}

and this is the method definition,

    public boolean isNetworkAvailable(Context ctx)
{
    ConnectivityManager cm = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()&& cm.getActiveNetworkInfo().isAvailable()&& cm.getActiveNetworkInfo().isConnected()) 
    {
        return true;
    }
    else
    {
        return false;
    }
}

do something like this inside your method callhttppost_numvaluepair(URL, nameValuePairs) of WebServiceCall class,

HttpParams basicparams = new BasicHttpParams();
URI uri = new URI(url);
HttpPost method = new HttpPost(uri);
int timeoutConnection = 60000;//set your timeout period
HttpConnectionParams.setConnectionTimeout(basicparams,
        timeoutConnection);
DefaultHttpClient client = new DefaultHttpClient(basicparams);
    //and then rest of your code

Note: Don't forget to put the permission in manifest file,

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Mehul Joisar
  • 15,348
  • 6
  • 48
  • 57
1

You should use a broadcast receiver as mentioned in other SO answers, but since you have asked how to do this otherwise, here you go:

 * Checks for an existing network connectivity
 * 
 * @param context
 *            The {@link Context} which is needed to tap
 *            {@link Context#CONNECTIVITY_SERVICE}
 * @return True if network connection is available
 */
public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivity = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivity == null) {
        return false;
    } else {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
    }
    return false;
}

Will need additional permission to be specified in the manifest file

Abhishek Nandi
  • 4,265
  • 1
  • 30
  • 43
0

check internet before execute asyncTask

if(checkNetwork)
{
new GetVideoUrlAsyn().execute();    
}
else
{
 // do stuff
}
Sanket Kachhela
  • 10,861
  • 8
  • 50
  • 75
0
if(CheckNetwork){
new GetVideoUrlAsyn().execute();
}else{
// Check internet connection
}

and

private boolean CheckNetwork() {
    ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    if (conMgr.getActiveNetworkInfo() != null
            && conMgr.getActiveNetworkInfo().isAvailable()
            && conMgr.getActiveNetworkInfo().isConnected()) {
        return true;
    } else {
        return false;
    }

}
Preet_Android
  • 2,332
  • 5
  • 25
  • 43