Android 运行过程中internet连接丢失时取消异步任务

Android 运行过程中internet连接丢失时取消异步任务,android,networking,android-asynctask,broadcastreceiver,Android,Networking,Android Asynctask,Broadcastreceiver,我正在开发一个执行异步任务的新闻应用程序,但是在异步任务运行期间,如果互联网连接丢失,应用程序就会崩溃。我试图通过使用广播接收器来解决这个问题,并在连接丢失时取消异步任务,但问题仍然存在。下面是我的完整活动源代码 public class News extends AppCompatActivity{ // Declare Variables JSONObject jsonobject; JSONArray jsonarray; GridView gridvie

我正在开发一个执行异步任务的新闻应用程序,但是在异步任务运行期间,如果互联网连接丢失,应用程序就会崩溃。我试图通过使用广播接收器来解决这个问题,并在连接丢失时取消异步任务,但问题仍然存在。下面是我的完整活动源代码

public class News extends AppCompatActivity{

    // Declare Variables
    JSONObject jsonobject;
    JSONArray jsonarray;
    GridView gridview;
    GridViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;

    Toolbar mToolbar;

    static String NEWS = "news";
    static String ID = "id";
    static String PROFILE_PIC = "news_pic";


    DownloadNews downloader;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news);

        IntentFilter filter = new    IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);        
        registerReceiver(networkStateReceiver, filter);


        mToolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        gridview = (GridView) findViewById(R.id.discoverGrid);

         downloader = new DownloadNews();



        ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
        if (!cd.isConnectingToInternet()) {

            Toast.makeText(getApplicationContext(),"Couldn't refresh",Toast.LENGTH_SHORT).show();


            }
        else
        {

            downloader.execute();
            Handler handler = new Handler();
            handler.postDelayed(new Runnable()
            {
              @Override
              public void run() {
                  if ( downloader.getStatus() == AsyncTask.Status.RUNNING ){
                      downloader.cancel(true);
                  linlaHeaderProgress.setVisibility(View.GONE);
                  Toast.makeText(getApplicationContext(),"Internet Connection is Down",Toast.LENGTH_SHORT).show();

              }
                  else if(downloader.getStatus() == AsyncTask.Status.FINISHED){
                  linlaHeaderProgress.setVisibility(View.GONE);

                  }

              }
            }, 15000 );
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
         getMenuInflater().inflate(R.menu.news, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        int id = item.getItemId();
        if (id == R.id.action_search) {
            return true;
        }


        else if (id == android.R.id.home) {
            onBackPressed();
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private class DownloadNews extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog.show();

        }

        @Override
        protected Void doInBackground(Void... params) {

            while(true){

                  if (isCancelled())  
                     break;
             }

            arraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address
            try {
                try {
                    jsonobject = JSONfunctions
                           .getJSONfromURL("http://www.example.com/app/news.php");
                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } catch (ConnectTimeoutException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (SocketTimeoutException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }   


            try {
                // Locate the array name in JSON
                jsonarray = jsonobject.getJSONArray("news");

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

                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrieve JSON Objects
                    map.put("id", jsonobject.getString("id"));
                    map.put("profile_pic", jsonobject.getString("news_pic"));
                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }

            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }




            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            adapter = new GridViewAdapter(News.this, arraylist);
            gridview.setAdapter(adapter);
            mProgressDialog.dismiss();

        }

        @Override
        protected void onCancelled(){
            downloader.cancel(true);

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    BroadcastReceiver networkStateReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);

            if(!noConnectivity) {
                    onConnectionFound();
            } else {
                    onConnectionLost();
            }
        }
    };


    public void onConnectionLost() {
        Toast.makeText(this, "Connection lost", Toast.LENGTH_LONG).show();
        downloader.cancel(true);

    }

    public void onConnectionFound() {
        Toast.makeText(this, "Connection found", Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(networkStateReceiver);
    }

}
公共类新闻扩展了AppCompative活动{
//声明变量
JSONObject JSONObject;
JSONArray JSONArray;
GridView;
GridViewAdapter;
进程对话框;
ArrayList ArrayList;
工具栏工具栏;
静态字符串NEWS=“NEWS”;
静态字符串ID=“ID”;
静态字符串配置文件\u PIC=“新闻\u PIC”;
下载新闻下载器;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.news);
IntentFilter筛选器=新的IntentFilter(ConnectionManager.CONNECTIVITY_操作);
registerReceiver(网络状态接收器、过滤器);
mToolbar=(工具栏)findviewbyd(R.id.Toolbar);
设置支持操作栏(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
gridview=(gridview)findViewById(R.id.discoverGrid);
downloader=新的DownloadNews();
ConnectionDetector cd=新的ConnectionDetector(getApplicationContext());
如果(!cd.isConnectingToInternet()){
Toast.makeText(getApplicationContext(),“无法刷新”,Toast.LENGTH\u SHORT.show();
}
其他的
{
downloader.execute();
Handler=newhandler();
handler.postDelayed(新的Runnable()
{
@凌驾
公开募捐{
if(downloader.getStatus()==AsyncTask.Status.RUNNING){
downloader.cancel(true);
linlaHeaderProgress.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(),“Internet连接已断开”,Toast.LENGTH\u SHORT.show();
}
else if(downloader.getStatus()==AsyncTask.Status.FINISHED){
linlaHeaderProgress.setVisibility(View.GONE);
}
}
}, 15000 );
}
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(R.menu.news,menu);
返回true;
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
//处理操作栏项目单击此处。操作栏将
int id=item.getItemId();
if(id==R.id.action\u search){
返回true;
}
else if(id==android.R.id.home){
onBackPressed();
完成();
返回true;
}
返回super.onOptionsItemSelected(项目);
}
私有类DownloadNews扩展异步任务{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
mProgressDialog.show();
}
@凌驾
受保护的Void doInBackground(Void…参数){
while(true){
如果(isCancelled())
打破
}
arraylist=新的arraylist();
//从给定的URL地址检索JSON对象
试一试{
试一试{
jsonobject=JSONfunctions
.getJSONfromURL(“http://www.example.com/app/news.php");
}捕获(未知后异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}捕获(ConnectTimeoutException e1){
//TODO自动生成的捕捉块
e1.printStackTrace();
}捕获(SocketTimeoutException e1){
//TODO自动生成的捕捉块
e1.printStackTrace();
}   
试一试{
//在JSON中找到数组名称
jsonarray=jsonobject.getJSONArray(“新闻”);
for(int i=0;i