从Android中的非Activity类调用方法

时间:2017-07-28 13:13:33

标签: java android call

我有一个弹出窗口(非活动类),它有一些按钮。其中一个(btn_audio),播放或暂停声音,它就像一个魅力 现在,我想在我的HomeActivity中调用两个方法play()pause(),并在我的所有活动中调用onStop()方法内部。它不起作用,在其他活动中调用play()pause()会发生NullPointException。

public class Popup_Menu extends Activity implements OnClickListener {
  Button btn_audio;
  public static MediaPlayer player;     String play_or_pause;
  int num_ply, tim_pos; int [] resID;// Audio
  SharedPreferences sp;
void showPopup(final Activity context) {

  this.context=context;
  LinearLayout viewGroup = (LinearLayout) context.findViewById(R.id.popup);
       LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       layout = layoutInflater.inflate(R.layout.popup_layout_menu, viewGroup);
  sp = context.getSharedPreferences("text", MODE_PRIVATE);
       btn_audio = (Button) layout.findViewById(R.id.btn_audio);    // audio
        layout.findViewById(R.id.btn_audio).setOnClickListener(this);


        @Override
        public void onClick(View whichButtonIsClicked) {
  switch (whichButtonIsClicked.getId())  {
  case R.id.btn_audio:                      
    if (play_or_pause.equals("play")) { 
      pause();
  } else {
      play(context);
  }
  sp.edit().putString("play_or_pause", play_or_pause).commit();   // save current stat
}   ////// close of showPopup()

          //define play and pause methods   
public void pause() {
  player.pause();
  btn_audio.setBackgroundResource(R.drawable.icon_audio_pause);
  play_or_pause="pause"; // current state is 'pause'
            }

public void play(final Context context) {
  if(num_ply==9){num_ply=0; }
  resID = new int []{ R.raw.tarane,R.raw.toofan,R.raw.shane,R.raw.kharazmi,R.raw.golhaye_khofte,R.raw.rang,R.raw.naghmeh,R.raw.dar_rahe_to,R.raw.emperor};
  player=MediaPlayer.create(context,resID[num_ply]);
  player.seekTo(tim_pos);           
  player.start();
  btn_audio.setBackgroundResource(R.drawable.icon_audio_play);
  play_or_pause="play";      // current state is 'play'
  player.setOnCompletionListener(new OnCompletionListener() {
  public void onCompletion(MediaPlayer player) {
  tim_pos=0;            num_ply++;      play(context);
          }
      });
  } 
 }

和我的HomeActivity:

public class HomeActivity extends Activity implements OnClickListener {
 Popup_Menu ppp;
 @Override
protected void onCreate..............
 ppp = new Popup_Menu();
 SharedPreferences sp = getSharedPreferences("text", MODE_PRIVATE);

 if(sp.getString("play_or_pause", "play").equals("pause")){
   ppp.play(getApplicationContext());                 // ERROR
    }    // audio

}  /// close of onCreate

@Override
public void onStop() {
  super.onStop();                               
  if(play_or_pause.equals("play")){
  ppp.tim_pos= ppp.player.getCurrentP

好的,我决定使用服务来解决这个问题,它适用于play()。但是在播放时,我仍然无法从SoundService调用pause()方法,因为播放器对象为空。我认为通过从SoundService类(Popup_Menu类中的ss)创建一个对象,默认构造函数将播放器值设置为null(播放时播放器和播放器对象不为空)。并调用player.pause发生错误。 我怎么能暂停这个one_week_friend !!!

public class SoundService extends Service {

    MediaPlayer player;     int num_ply, tim_pos;   int [] resID;


public int onStartCommand(Intent intent, int flags, int startId) {

    resID = new int []{ R.raw.tarane,R.raw.toofan,R.raw.shane,R.raw.kharazmi,
            R.raw.golhaye_khofte,R.raw.rang,R.raw.naghmeh,R.raw.dar_rahe_to,R.raw.emperor     };
        player=MediaPlayer.create(this,resID[num_ply]);

        play();
        return Service.START_FLAG_REDELIVERY;
 }

public void play() {
    if(num_ply==9){num_ply=0; }
    player.seekTo(tim_pos);         
    player.start();
    player.setOnCompletionListener(new OnCompletionListener() {         
    public void onCompletion(MediaPlayer player) {
        tim_pos=0;          num_ply++;      play();
    }
    });
}

    public void resume(){
    player.seekTo(tim_pos);         
    player.start();
}

public void pause() {
    tim_pos= player.getCurrentPosition();          ////// ERROR
    player.pause();          ////// ERROR
    num_ply++;
}


public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
  }
}

我的Popup_Menu课程:

@Override
public void onClick(View whichButtonIsClicked) {
    switch (whichButtonIsClicked.getId())  {

    case R.id.btn_audio:
    if (play_or_pause.equals("play")) {
        btn_audio.setBackgroundResource(R.drawable.icon_audio_pause);
        play_or_pause="pause";       // current state is 'pause'
        SoundService ss = new SoundService();
        ss.pause();          ////// ERROR
    } else {
        btn_audio.setBackgroundResource(R.drawable.icon_audio_play);
        play_or_pause="play";        // current state is 'play'
        Intent sound_Intent = new Intent(context , SoundService.class);     // start service
        context.startService(sound_Intent);
    }
        sp.edit().putString("play_or_pause", play_or_pause).commit();   // save current state
    break;

logcat的:

08-05 01:03:31.440: E/AndroidRuntime(25356): FATAL EXCEPTION: main
08-05 01:03:31.440: E/AndroidRuntime(25356): java.lang.NullPointerException
08-05 01:03:31.440: E/AndroidRuntime(25356):    at com.codegostarNiloo.negar.SoundService.pause(SoundService.java:47)
08-05 01:03:31.440: E/AndroidRuntime(25356):    at com.codegostarNiloo.negar.Popup_Menu.onClick(Popup_Menu.java:234)
08-05 01:03:31.440: E/AndroidRuntime(25356):    at android.view.View.performClick(View.java:4209)
08-05 01:03:31.440: E/AndroidRuntime(25356):    at android.view.View$PerformClick.run(View.java:17457)
08-05 01:03:31.440: E/AndroidRuntime(25356):    at android.os.Handler.handleCallback(Handler.java:725)
08-05 01:03:31.440: E/AndroidRuntime(25356):    at android.os.Handler.dispatchMessage(Handler.java:92)
08-05 01:03:31.440: E/AndroidRuntime(25356):    at android.os.Looper.loop(Looper.java:153)
08-05 01:03:31.440: E/AndroidRuntime(25356):    at android.app.ActivityThread.main(ActivityThread.java:5341)
08-05 01:03:31.440: E/AndroidRuntime(25356):    at java.lang.reflect.Method.invokeNative(Native Method)
08-05 01:03:31.440: E/AndroidRuntime(25356):    at java.lang.reflect.Method.invoke(Method.java:511)
08-05 01:03:31.440: E/AndroidRuntime(25356):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:929)
08-05 01:03:31.440: E/AndroidRuntime(25356):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
08-05 01:03:31.440: E/AndroidRuntime(25356):    at dalvik.system.NativeStart.main(Native Method)
08-05 01:03:32.066: D/dalvikvm(25356): threadid=11: interp stack at 0x5f1c9000

2 个答案:

答案 0 :(得分:2)

首先,关闭,如果它是非活动,请不要扩展活动,如您声明的那样,然后传递上下文优先于活动

其次,有一个名为DialogFragment的类,用作弹出对话框

我认为您正在寻找类似以下的内容,但

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
    <div class="input" id="a">
        <input class="col-sm-3 col-xs-3 input-co" type="text"  value="#ffffff">
    </div>
    <div class="input" id="b">
        <input class="col-sm-3 col-xs-3 input-co" type="text"  value="#ffffff">
    </div>
</body>
</html>

您现在可以创建public class Popup_Menu implements OnClickListener { Button btn_audio; public MediaPlayer player; String play_or_pause; int num_ply, tim_pos; int [] resID;// Audio SharedPreferences sp; Context context ; public Popup_Menu(final Context context) { this.context= context; sp = this.context.getSharedPreferences("text", Context.MODE_PRIVATE); // LinearLayout viewGroup = (LinearLayout) view.findViewById(R.id.popup); LayoutInflater layoutInflater = LayoutInflater.from(this.context); layout = layoutInflater.inflate(R.layout.popup_layout_menu, viewGroup); btn_audio = (Button) layout.findViewById(R.id.btn_audio); // audio btn_audio.setOnClickListener(this); }

答案 1 :(得分:-1)

呀...!完成。它现在正在工作。它不需要创建新对象。我必须将(对象)播放器的modifire和pause()方法及其中的所有内容更改为STATIC。所以现在我可以访问所有对象和变量。 谢谢cricket_007 ......