java.lang.RuntimeException:无法恢复活动

时间:2012-12-05 09:02:34

标签: android radio

完整代码:

public class RadioApp extends Activity implements OnClickListener,
        OnSeekBarChangeListener, OnDrawerOpenListener, OnDrawerCloseListener {

    public static final String MHYH_RADIO_LOG_TAG = "GrupoGPR";



    private static int maxVolume = 0;
    private static int currentVolume = 0;

    private final String as = Context.AUDIO_SERVICE;
    private final String ps = Context.TELEPHONY_SERVICE;
    private final String ws = Context.WINDOW_SERVICE;

    private AudioManager audioManager;
    private TelephonyManager telephonyManager;
    private WindowManager windowManager;

    private Display display;

    private ImageButton playButton;
    private static TextView outputView;

    private SeekBar volumeSeekBar;
    private ImageView imageView, radioImage;
    private TextView title;
    private Bitmap defaultBitmap;
    private CacheImageDownloader downloader;
    // private ImageView volumeImageView;

    private String nowPlaying = "";
    private String previousPlaying = "";
    private boolean inCall = false;
    public static boolean wasPlaying = false;
    private static boolean inBackground = false;

    private final Handler handler = new Handler();
    private final Handler inithandler = new Handler();

    @SuppressWarnings("unused")
    private SharedPreferences preferences;

    private static RadioApp instance = null;

    /**
     * @return the instance
     */
    public static RadioApp getInstance() {
        return RadioApp.instance;
    }

    /*********************************************************************************************
     *** APP ***
     *********************************************************************************************/

    private static Context con;

    // private WebView web;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try{
        windowManager = (WindowManager) getSystemService(ws);

        audioManager = (AudioManager) getSystemService(as);
        telephonyManager = (TelephonyManager) getSystemService(ps);
        telephonyManager.listen(new RadioPhoneStateListener(),
                PhoneStateListener.LISTEN_CALL_STATE);
        // UI
        display = windowManager.getDefaultDisplay();
        display.getOrientation();

        RadioApp.con = this;
        RadioApp.instance = this;
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.fradioapp);




//      title = (TextView) findViewById(R.id.radioTitle);
//      title.setText(AllConstant.stationName + "");
//      radioImage = (ImageView) findViewById(R.id.radioImagePlaying);
//      if (AllConstant.imageUrl.length() == 0) {
//          radioImage.setImageBitmap(defaultBitmap);
//      } else {
//          downloader.download(AllConstant.imageUrl.replaceAll(" ", "%20"),
//                  radioImage);
//      }
//      playSongNow();





        downloader = new CacheImageDownloader();

        defaultBitmap = BitmapFactory.decodeResource(getResources(),
                R.drawable.midbanner);

        playButton = (ImageButton) findViewById(R.id.playButton);
        playButton.setBackgroundColor(Color.TRANSPARENT);

        RadioApp.outputView = (TextView) findViewById(R.id.outputViewrr);





        volumeSeekBar = (SeekBar) findViewById(R.id.VolumeSeekBar);
        // volumeImageView = (ImageView) findViewById(R.id.VolumeImageView);

        playButton.setOnClickListener(this);
        playButton.setImageResource(R.drawable.playbutton);
        RadioApp.maxVolume = audioManager
                .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        RadioApp.currentVolume = audioManager
                .getStreamVolume(AudioManager.STREAM_MUSIC);


        // try {
        // if (RadioApp.currentVolume == 0) {
        // volumeImageView
        // .setImageResource(android.R.drawable.ic_lock_silent_mode);
        // } else {
        // volumeImageView
        // .setImageResource(android.R.drawable.ic_lock_silent_mode_off);
        // }8
        // } catch (Exception e) {
        // // TODO: handle exception
        // }

        volumeSeekBar.setMax(RadioApp.maxVolume);
        volumeSeekBar.setProgress(RadioApp.currentVolume);
        volumeSeekBar.setOnSeekBarChangeListener(this);
        // Retrieve preferences
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        // Setup the Nagare service

        if (MyService.getService() == null) {

            MyService.startService(RadioApp.con);

            runRefresh.run();
        } else {
            Log.w("Nagare service is not null at oncreate", "yes");
            runRefresh.run();
        }

        final Intent intent = getIntent();
        if (intent.getAction() != null
                && intent.getAction().equals(Intent.ACTION_VIEW)) {
            final PlayListFile playListFile = PlayListFactory.create(
                    intent.getType(), intent.getData());
            if (playListFile == null) {
                RadioApp.outputView.setText("Not sure what to do with: "
                        + intent.getAction() + ":" + intent.getDataString()
                        + ":" + intent.getType());
            } else {
                playListFile.parse();
                if (playListFile.errors() != "") {
                    RadioApp.outputView.setText(playListFile.errors());
                } else {
                    RadioApp.outputView
                            .setText(playListFile.play_list().m_entries
                                    .getFirst().m_url_string);
                }
            }
        }
        }catch (Exception e) {
            // TODO: handle exception
        }



        inithandler.postDelayed(mPendingLauncherRunnable, 500);

        /*
         * 
         * admob portion
         */

        // AdManager.setTestDevices(new String[] { AdManager.TEST_EMULATOR,
        // "D81E0EFAB674357C2895265D9C5C13D5" });

        //
        // final AdRequest adRequest = new AdRequest();
        // adRequest.addTestDevice("35C88DD1A9110D5D3BA2A9602A5421E3");

    }


    @Override
    protected void onResume() {
        // TODO Auto-generated method stub


        super.onResume();

        title = (TextView) findViewById(R.id.radioTitle);
        title.setText(AllConstant.stationName + "");
        radioImage = (ImageView) findViewById(R.id.radioImagePlaying);
        if (AllConstant.imageUrl.length() == 0) {
            radioImage.setImageBitmap(defaultBitmap);
        } else {
            downloader.download(AllConstant.imageUrl.replaceAll(" ", "%20"),
                    radioImage);
        }




        playSongNow();


    }



    public void goBackToInfoPopup(View v) {
        chooseSharingOption();

    }

    protected void chooseSharingOption() {
        // TODO Auto-generated method stub

        final Dialog d = new Dialog(RadioApp.this);
        d.setTitle("Info:");
        d.setContentView(R.layout.infopopup);
        final Button cancel = (Button) d
                .findViewById(R.id.infodialoguebtncancle);
        cancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                d.cancel();
            }

        });
        d.show();

    }

    private final Runnable mPendingLauncherRunnable = new Runnable() {
        @Override

        public void run() {

            /*
             * 
             * play radio now
             */



            playSongNow();




        }

    };



    @Override
    protected void onDestroy() {
        // This informs other applications that access media on the SD card that
        // our audio file no longer exists.

        super.onDestroy();
    }

    @Override
    protected void onRestart() {
        RadioApp.inBackground = false;
        MyService.stopNotification();

        super.onRestart();

    }

    @Override
    protected void onStop() {
        if (!isFinishing()) {
            RadioApp.inBackground = true;

            MyService.startNotification();

        }

        super.onStop();
    }

    // @Override
    // protected void onResume() {
    // // TODO Auto-generated method stub
    //
    // /*
    // *
    // * refresh add
    // */
    //
    // // loadWebView();
    //
    // super.onResume();
    //
    // }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.playButton:
            playSongNow();

            break;

        }

    }

    private void playSongNow() {
        // TODO Auto-generated method stub

        if (MyService.getService() == null) {
            RadioApp.outputView.setText("No service available!");
            Log.w(RadioApp.MHYH_RADIO_LOG_TAG, "Nagare service is NULL");
            return;
        }
        try {

            final int state = MyService.getService().state();
            if (state == NagareService.STOPPED && !inCall) {

                MyService.getService().download(AllConstant.radioURL.trim());
                Log.e("current url is ", AllConstant.radioURL);
                Log.e("Search Image : ",
                        AllConstant.imageUrl);


            } else if (state == NagareService.STOPPED && inCall) {
                handleNagareErrors("inCall");

            } else {
                MyService.getService().stop();
            }
        } catch (final RemoteException e) {
            RadioApp.outputView.setText("Error connecting to Nagare service: "
                    + e.toString() + "\n");
            Log.e(RadioApp.MHYH_RADIO_LOG_TAG,
                    "Caught RemoteException: " + e.getMessage());
        }

    }

    /*********************************************************************************************
     *** TELEPHONY ***
     *********************************************************************************************/

    private class RadioPhoneStateListener extends PhoneStateListener {

        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);
            switch (state) {
            case TelephonyManager.CALL_STATE_IDLE:
                inCall = false;
                try {
                    if (MyService.getService() != null && RadioApp.wasPlaying) {
                        Log.e("current url is ", ALLURL.selectedUrl);




                        MyService.getService().download(
                                ALLURL.selectedUrl.trim());
                    }
                } catch (final RemoteException e) {
                    Log.e(RadioApp.MHYH_RADIO_LOG_TAG,
                            "Caught RemoteException: " + e.getMessage());
                } catch (final Exception e) {
                    Log.e(RadioApp.MHYH_RADIO_LOG_TAG,
                            "Caught RemoteException: " + e.getMessage());
                }

                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:
            case TelephonyManager.CALL_STATE_RINGING:
                try {
                    if (!inCall) {
                        if (MyService.getService() != null) {
                            if (MyService.getService().state() != NagareService.STOPPED) {
                                RadioApp.wasPlaying = true;
                            } else {
                                RadioApp.wasPlaying = false;
                            }
                        }
                    }
                    inCall = true;
                } catch (final RemoteException e1) {
                    Log.e(RadioApp.MHYH_RADIO_LOG_TAG,
                            "Caught RemoteException: " + e1.getMessage());
                }
                try {
                    if (MyService.getService() != null) {
                        MyService.getService().stop();
                    }
                } catch (final RemoteException e2) {
                    Log.e(RadioApp.MHYH_RADIO_LOG_TAG,
                            "Caught RemoteException: " + e2.getMessage());
                }
                break;
            default:
                Log.w(RadioApp.MHYH_RADIO_LOG_TAG,
                        "Found un-handled call state: " + state);
            }
        }

    }

    /*********************************************************************************************
     *** AUDIO ***
     *********************************************************************************************/

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress,
            boolean fromUser) {
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress,
                AudioManager.FLAG_SHOW_UI);
        // if (progress == 0) {
        // volumeImageView
        // .setImageResource(android.R.drawable.ic_lock_silent_mode);
        // } else {
        // volumeImageView
        // .setImageResource(android.R.drawable.ic_lock_silent_mode_off);
        // }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    }

    @Override
    public void onDrawerOpened() {
        imageView
                .setImageBitmap(rotateImage(android.R.drawable.ic_menu_more, 0));
    }

    @Override
    public void onDrawerClosed() {
        imageView.setImageBitmap(rotateImage(android.R.drawable.ic_menu_more,
                180));
    }

    /*********************************************************************************************
     *** MENUS ***
     *********************************************************************************************/

    // @Override
    // public boolean onCreateOptionsMenu(Menu menu) {
    // MenuInflater inflater = getMenuInflater();
    // inflater.inflate(R.menu.main_menu, menu);
    // return true;
    // }
    //
    // @Override
    // public boolean onOptionsItemSelected(MenuItem item) {
    // switch (item.getItemId()) {
    // case R.id.ExitMenuItem:
    // onDestroy();
    // System.exit(0);
    // return true;
    // /*
    // * case R.id.SettingsMenuItem: Intent i = new Intent(RadioApp.this,
    // * Preferences.class); startActivity(i); return true;
    // */
    // default:
    // return super.onOptionsItemSelected(item);
    // }
    // }

    /*********************************************************************************************
     *** UTILITIES ***
     *********************************************************************************************/

    private Bitmap rotateImage(int id, float degrees) {
        final Bitmap bitmap = BitmapFactory.decodeResource(getResources(), id);
        final Matrix mat = new Matrix();
        mat.postRotate(degrees);
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                bitmap.getHeight(), mat, true);
    }

    /*
     * back button (non-Javadoc)
     * 
     * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
     */

    public void goBack(View v) {

        RadioApp.this.finish();
        //
        // final Intent aaa = new Intent(RadioApp.this, GPRActivity.class);
        // aaa.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        // startActivity(aaa);

    }

    //
    // /*
    // * open Facebook
    // */
    //
    // public void openFB(View v) {
    // openURL(ALLURL.URLfacebook.trim());
    //
    // }
    //
    // /*
    // * open twitter
    // */
    //
    // public void openTwitter(View v) {
    // openURL(ALLURL.URLtwitter.trim());
    //
    // }

    @Override
    public boolean onKeyDown(final int keyCode, final KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            final int index = volumeSeekBar.getProgress();
            volumeSeekBar.setProgress(index + 1);
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
            final int index = volumeSeekBar.getProgress();
            volumeSeekBar.setProgress(index - 1);
            return true;
        }

        else if (keyCode == KeyEvent.KEYCODE_BACK) {

            // final Intent aaa = new Intent(con, SecondScreenActivity.class);

            onStopRecording();

            return true;
        }

        return super.onKeyDown(keyCode, event);

        // return false;
    }

    public void onStopRecording() {
        final CharSequence[] items = { "Stay in app.", "Exit." };
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Exit app?");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                switch (item) {
                case 0:

                    return;

                case 1:

                    RadioApp.this.finish();
                    break;

                default:

                    return;
                }

                // Toast.makeText(getApplicationContext(), items[item],
                // Toast.LENGTH_SHORT).show();
            }
        });
        builder.show();
        builder.create();

    }

    public void openURL(String url) {
        final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        startActivity(intent);
    }

    /*********************************************************************************************
     *** Nagare Serivce ***
     *********************************************************************************************/

    private final Runnable runRefresh = new Runnable() {

        @Override
        public void run() {
            refresh();
            handler.postDelayed(this, 1000);
        }
    };

    public void refresh() {
        if (MyService.getService() == null) {
            return;
        }
        try {
            final int state = MyService.getService().state();
            if (state == NagareService.STOPPED) {
                playButton.setImageResource(R.drawable.playbutton);
                previousPlaying = nowPlaying;
                nowPlaying = "No show information available";
                RadioApp.outputView.setText(nowPlaying);
                if (!MyService.getService().errors().equals("")) {
                    final String errors = MyService.getService().errors();
                    handleNagareErrors(errors);
                }
            } else {
                playButton.setImageResource(R.drawable.stopbutton);
                if (MyService.getService().errors().equals("")) {
                    previousPlaying = nowPlaying;
                    nowPlaying = "Now playing: "
                            + MyService.getService().show_name();
                    RadioApp.outputView.setText(nowPlaying);
                } else {
                    previousPlaying = nowPlaying;
                    nowPlaying = "No information available";
                    RadioApp.outputView.setText(nowPlaying);
                    final String errors = MyService.getService().errors();
                    handleNagareErrors(errors);
                    MyService.getService().stop();

                }
            }
            if (MyService.notification != null
                    && !nowPlaying.equals(previousPlaying)
                    && RadioApp.inBackground) {
                MyService.startNotification();
            }
        } catch (final RemoteException e) {
            Log.e(RadioApp.MHYH_RADIO_LOG_TAG,
                    "Caught RemoteException: " + e.getMessage());
        }
    }

    private void handleNagareErrors(String errors) {

        /*
         * cancel timer
         */

        try {
            handler.removeCallbacks(runRefresh);
        } catch (final Exception e) {
            // TODO: handle exception
        }


    }

它正在安静地使用2.1或2.3+版本。但是,当我想用​​2.2+ htc android设备测试时,它显示以下错误。

W/dalvikvm(9704): threadid=1: thread exiting with uncaught exception (group=0x40028a00)
 E/AndroidRuntime(9704): java.lang.RuntimeException: Unable to resume activity {com.droidbd.newradio/com.newradio.android.RadioApp}: java.lang.NullPointerException
 E/AndroidRuntime(9704):    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3325)  Caused by Java null pointer exception.

然后当我在logcat中单击错误选项时,它会以这种方法带给我。

 @Override
    protected void onResume() {
        // TODO Auto-generated method stub

        super.onResume();

        title = (TextView) findViewById(R.id.radioTitle);
        title.setText(AllConstant.stationName + "");
        radioImage = (ImageView) findViewById(R.id.radioImagePlaying);
        if (AllConstant.imageUrl.length() == 0) {
            radioImage.setImageBitmap(defaultBitmap);
        } else {
            downloader.download(AllConstant.imageUrl.replaceAll(" ", "%20"),
                        radioImage);
        }

        playSongNow();

    }

0 个答案:

没有答案