onkar
onkar

Reputation: 4547

ANR when I am starting a service

I am using a service to download heavy files from the web.but when the files are being downloaded I am unable to interact with the app. What is the best way for this . I am downloading files that are about 10 MB and I want the user to interact with app while the files are downloaded Please find the my service code.

public static class MyService extends Service {
        @Override
        public IBinder onBind(Intent arg0) {
            return null;
        }

        public MyService(){
            super();
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            // Let it continue running until it is stopped.
            System.out.println("service started");
            Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
            //Toast.makeText(Description.this, "Downloading content...", Toast.LENGTH_LONG);

            GetShowsInfo(downloadEpisodeMedia(episode_id));
            RequestDownloads();


            File cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"Folder Name");
            listf(cacheDir,files);
            mediaPlayerflag=true;
            //progressBarLayout.setVisibility(LinearLayout.VISIBLE);

            nowPlayingEpisode=categoryName;
            //NowPlayingEpisode.setText("Now Playing "+episodeArrayList.get(position).getName());

            textView_MediaPlayer.setText(nowPlayingEpisode);
            //textView_EpisodeCount.setText(episodeCount);
            playOnebyOneMedia();

            //  StoreInfo(GetCategories());
            //StoreDescription(GetDescription());
            return START_STICKY;
        }
        @Override
        public void onDestroy() {
            System.out.println("service stopped");
            super.onDestroy();
            Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
        }


    }

Upvotes: 0

Views: 345

Answers (2)

Leonidos
Leonidos

Reputation: 10518

You can use IntentService instead of Service. IntentService uses a separate thread to handle intents. So it wont block your main thread. onStartCommand method of your service runs in main thread and blocks it for too long time and causes ANR.

Upvotes: 1

kalyan pvs
kalyan pvs

Reputation: 14590

I think you are performing very large operations on the UI thread like downloading files..ANR comes when the UI thread perform the long running operations..try to do it with using AsynchTask or threads..then you can avoid ANR..

check this link for download file in AsynchTask example..AsynckTask example

Upvotes: 3

Related Questions