【问题标题】:Stop App From Running In Background停止应用程序在后台运行
【发布时间】:2014-03-25 21:48:59
【问题描述】:

我现在需要问一个简单的问题,我正在编写一个应该能够流式传输所有已完成的广播电台的应用程序。

我现在需要做的是不允许应用程序在单击停止时在后台运行,此时它只会停止音乐,但我需要它也停止从后台运行而不退出应用程序是停止音乐按钮。

我需要这个,因为我正在使用电话管理器来检测来电等以在用户通话时停止音乐

package com.beanie.samples.streaming;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import com.beanie.samples.streaming.R;
import com.beanie.samples.streaming.MyService;

import android.app.Activity;
import android.app.IntentService;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

;



public class HomeActivity extends Activity implements OnClickListener {
      private static final String TAG = "MyServices";

    private final static String RADIO_STATION_URL = "http://195.154.237.162:8936/";

    private static final String START_STICKY = null;
      Button buttonPlay, buttonStopPlay;



      @Override
      public void onBackPressed() {

          android.os.Process.killProcess(android.os.Process.myPid());
          // This above line close correctly
      }








      public void ring()
                {
       Bundle savedInstanceState = null;
    super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

       TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);     
          // register PhoneStateListener 
            PhoneStateListener callStateListener = new PhoneStateListener() {


           public void onCallStateChanged(int state, String incomingNumber) 
               {


                 // If phone ringing
           if(state==TelephonyManager.CALL_STATE_RINGING)
                    {
               stopPlaying();                                        
                       }
               // If incoming call received or making a call
                  if(state==TelephonyManager.CALL_STATE_OFFHOOK)
                      {
                      Toast.makeText(getApplicationContext(),"Music will keep playing after your call", Toast.LENGTH_LONG).show();
                      stopPlaying();

                         }


                  if(state==TelephonyManager.CALL_STATE_IDLE)
                       {
                     startPlaying();
                 Toast.makeText(getApplicationContext(),"Music Will Now Keep Playing!", Toast.LENGTH_LONG).show();
                     }
                   }
                       };
             telephonyManager.listen(callStateListener,PhoneStateListener.LISTEN_CALL_STATE);







                }




      public void unregister_ring()
                {


       Bundle savedInstanceState = null;
    super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

       TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);     
          // register PhoneStateListener 
            PhoneStateListener callStateListener = new PhoneStateListener() {


           public void onCallStateChanged(int state, String incomingNumber) 
               {



                   }
                       };
             telephonyManager.listen(callStateListener,PhoneStateListener.LISTEN_NONE);







                }





        /** Called when the activity is first created.
         * Keep this here all the application will stop working */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            ring();
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            initializeUIElements();

            initializeMediaPlayer();

            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            buttonPlay = (Button) findViewById(R.id.buttonPlay);
            buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);

            buttonPlay.setOnClickListener(this);
            buttonStopPlay.setOnClickListener(this);


        }





    private ProgressBar playSeekBar;





    private MediaPlayer player;

    private InputStream recordingStream;

    private RecorderThread recorderThread;

    private boolean isRecording = false;







    private void initializeUIElements() {

        playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
        playSeekBar.setMax(100);
        playSeekBar.setVisibility(View.INVISIBLE);

        buttonPlay = (Button) findViewById(R.id.buttonPlay);
        buttonPlay.setOnClickListener(this);

        buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
        buttonStopPlay.setEnabled(false);
        buttonStopPlay.setOnClickListener(this);


    }




    public void startPlaying() {
        buttonStopPlay.setEnabled(true);
        buttonPlay.setEnabled(false);

        playSeekBar.setVisibility(View.VISIBLE);

        player.prepareAsync();

        player.setOnPreparedListener(new OnPreparedListener() {

            public void onPrepared(MediaPlayer mp) {
                player.start();



            }
        });

    }







    private void onBufferingUpdate(MediaPlayer mp, int percent) {

         playSeekBar.setSecondaryProgress(percent);
        Toast.makeText(this, "Buffering ", percent).show();


          Log.i("Buffering", "" + percent);
    }











    public void onClick(View v) {
        if (v == buttonPlay) {

         startPlaying();









  player.setLooping(false); // Set looping










        } else if (v == buttonStopPlay) {

            Log.d(TAG, "onClick: stopping srvice");
            stopPlaying();
            unregister_ring();
            Toast.makeText(getApplicationContext(),"Stopped!", Toast.LENGTH_LONG).show();


        }
    }








    private void stopPlaying() {

            player.pause();
            player.release();
            initializeMediaPlayer();


        buttonPlay.setEnabled(true);
        buttonStopPlay.setEnabled(false);
        playSeekBar.setVisibility(View.INVISIBLE);

        stopRecording();
    }

    private void initializeMediaPlayer() {
        player = new MediaPlayer();
        try {
            player.setDataSource(RADIO_STATION_URL);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    private void startRecording() {

        BufferedOutputStream writer = null;
        try {
            URL url = new URL(RADIO_STATION_URL);
            URLConnection connection = url.openConnection();
            final String FOLDER_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()
                    + File.separator + "Songs";

            File folder = new File(FOLDER_PATH);
            if (!folder.exists()) {
                folder.mkdir();
            }

            writer = new BufferedOutputStream(new FileOutputStream(new File(FOLDER_PATH
                    + File.separator + "sample.mp3")));
            recordingStream = connection.getInputStream();

            final int BUFFER_SIZE = 100;

            byte[] buffer = new byte[BUFFER_SIZE];

            while (recordingStream.read(buffer, 0, BUFFER_SIZE) != -1 && isRecording) {
                writer.write(buffer, 0, BUFFER_SIZE);
                writer.flush();
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                recordingStream.close();
                writer.flush();
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void stopRecording() {

        try {
            isRecording = false;
            if (recordingStream != null) {
                recordingStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private class RecorderThread extends Thread {
        @Override
        public void run() {
            isRecording = true;
            startRecording();
        }

    };
}

谢谢

【问题讨论】:

  • 您是否从服务播放音乐流?这样您就可以与服务交互并使其停止,而无需停止应用程序。
  • 我发布了我正在使用的代码 android.os.Process.killProcess(android.os.Process.myPid());但这只会关闭整个应用程序。
  • 到底出了什么问题?当电话响起时,您似乎正在调用 stopPlaying。稍微偏离主题:改进代码的一些方法:1)对 TelephonyManager 的状态使用 switch 语句 2)您设置 contentView 3 次并调用 super.onCreate() 两次.. 不需要!
  • 谢谢 请记住,我对 java 和 android 才刚接触几天,所以我认为到目前为止我做得很好,我想要的是一旦我按下停止然后停止应用程序在后台运行,这样它不使用电话管理器但不退出应用程序

标签: android background app-store radio


【解决方案1】:

要停止使用 TelephonyManager,您可以“取消注册”监听器:

telephonyManager.listen(callStateListener, PhoneStateListener.LISTEN_NONE);

这样就不需要杀死应用了。

请参阅documentation of TelephonyManagerwww.developer.android.com 也是了解更多信息和查看文档的好地方。

【讨论】:

  • 好的,非常感谢! ;) 你把我引向了正确的方向我已经接受了你的回答如果我添加更多需要被杀死的功能,未来唯一的问题是我只是将这些添加到 buttonStopPlay 中吗?如果它运行良好,我喜欢正确编码,因为我会犯错误,但我想这一切都是为了学习,再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-18
  • 1970-01-01
  • 1970-01-01
  • 2010-11-04
  • 1970-01-01
  • 1970-01-01
  • 2021-12-29
相关资源
最近更新 更多