2014-01-14 33 views
0

我在android中使用Service来使用MediaPlayer播放音乐。我在Nexus中使用该应用程序。但手机在10-15分钟内变慢。 30分钟后,手机超慢。服务代码有什么问题吗?任何帮助将不胜感激。设备变慢,然后挂起android

代码:

public class PPlayService extends Service { 
public static final int NOTIFICATION_NUMBER = 0; 
Context conte; 
MediaPlayer playHandler; 
BroadcastReceiver broadcaster; 
IncomingHandler mServiceHandler; 
String online = "", link = "", name = ""; 
boolean playing = false; 
Runnable runnable; 
String[] uris, names; 
int send; 
SharedPreferences pre; 
NotificationManager notificationManager; 
NotificationCompat.Builder mBuilder; 

// ........ 
PhoneStateListener phoneStateListener; 
TelephonyManager mgr; 
boolean notFromTelephone = false; 
RemoteViews contentView; 
BroadcastReceiver stopFromNoti, forwardFromNoti, backwardFromNoti; 

public void handleMessage(Message msg) { 
    try { 
     System.gc(); 
     if (online.equals("0")) { 
      contentView = new RemoteViews(getPackageName(), 
        R.layout.offline_notification_layout); 
      PendingIntent pit = PendingIntent.getBroadcast(conte, 0, 
        new Intent("stopfromnoti"), 
        PendingIntent.FLAG_UPDATE_CURRENT); 
      contentView.setOnClickPendingIntent(R.id.play_or_pause_noti, 
        pit); 
      PendingIntent backSong = PendingIntent.getBroadcast(conte, 0, 
        new Intent("backwardFromNoti"), 
        PendingIntent.FLAG_UPDATE_CURRENT); 
      contentView.setOnClickPendingIntent(R.id.backward_noti, 
        backSong); 
      PendingIntent frontSong = PendingIntent.getBroadcast(conte, 0, 
        new Intent("forwardFromNoti"), 
        PendingIntent.FLAG_UPDATE_CURRENT); 
      contentView.setOnClickPendingIntent(R.id.forward_noti, 
        frontSong); 
     } else { 
      contentView = new RemoteViews(getPackageName(), 
        R.layout.online_notification_layout); 
      PendingIntent pit = PendingIntent.getBroadcast(conte, 0, 
        new Intent("stopfromnoti"), 
        PendingIntent.FLAG_UPDATE_CURRENT); 
      contentView.setOnClickPendingIntent(R.id.play_or_pause_noti, 
        pit); 
     } 
     Intent intt = new Intent(getBaseContext(), MainActivity.class); 
     PendingIntent pi = PendingIntent.getActivity(getBaseContext(), 0, 
       intt, 0); 
     mBuilder = new NotificationCompat.Builder(conte) 
       .setSmallIcon(R.drawable.icon).setContent(contentView) 
       .setContentIntent(pi).setAutoCancel(false); 
     notificationManager.notify(55, mBuilder.build()); 
     Intent in = new Intent(Mp3Constants.NOTIFICATION); 
     in.putExtra("download", "0"); 
     in.putExtra("online", online); 
     in.putExtra("name", name); 
     in.putExtra("status", Mp3Constants.LOADING); 
     in.putExtra("currentTime", 0); 
     in.putExtra("totalTime", 0); 
     conte.sendBroadcast(in); 
     if (playHandler != null) { 
      playing = false; 
      playHandler.reset(); 
     } else { 
      playHandler = new MediaPlayer(); 
     } 
     if (online.equals("1")) { 
      // Online Stream 
      playHandler.setAudioStreamType(AudioManager.STREAM_MUSIC); 

      try { 
       playHandler.setDataSource(link); 
       playHandler.setOnPreparedListener(new OnPreparedListener() { 

        @Override 
        public void onPrepared(MediaPlayer arg0) { 
         if (playHandler != null) { 
          if (!playHandler.isPlaying()) { 
           playSongNow(); 
          } 
         } 
        } 
       }); 
       playHandler.prepareAsync(); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } else { 
      // Offline Stream 
      playHandler = MediaPlayer.create(conte, Uri.parse(link)); 
      playSongNow(); 
     } 
    } catch (Exception e) { 
    } 
} 

@Override 
public void onCreate() { 
    conte = this; 
    forwardFromNoti = new BroadcastReceiver() { 

     @Override 
     public void onReceive(Context arg0, Intent arg1) { 
      if (playHandler != null) { 
       playHandler.reset(); 
       playing = false; 
      } 
      getSD(); 
      int i = 0; 
      for (i = 0; i < send; i++) { 
       if (link.equalsIgnoreCase(uris[i])) { 
        break; 
       } 
      } 
      if (i >= send - 1) { 
       if (send > 0) { 
        name = names[0]; 
        link = uris[0]; 
        pre.edit().putString("name", name); 
        pre.edit().putString("online", online); 
        pre.edit().putString("link", link); 
        Message msg = mServiceHandler.obtainMessage(); 
        msg.arg1 = 1; 
        mServiceHandler.sendMessage(msg); 
       } 
      } else { 
       name = names[i + 1]; 
       link = uris[i + 1]; 
       pre.edit().putString("name", name); 
       pre.edit().putString("online", online); 
       pre.edit().putString("link", link); 
       Message msg = mServiceHandler.obtainMessage(); 
       msg.arg1 = 1; 
       mServiceHandler.sendMessage(msg); 
      } 
     } 
    }; 
    backwardFromNoti = new BroadcastReceiver() { 

     @Override 
     public void onReceive(Context arg0, Intent arg1) { 
      if (playHandler != null) { 
       playHandler.reset(); 
       playing = false; 
      } 
      getSD(); 
      int i = 0; 
      for (i = 0; i < send; i++) { 
       if (link.equalsIgnoreCase(uris[i])) { 
        break; 
       } 
      } 
      if (i == send || i == 0) { 
       if (send > 0) { 
        name = names[send - 1]; 
        link = uris[send - 1]; 
        pre.edit().putString("name", name); 
        pre.edit().putString("online", online); 
        pre.edit().putString("link", link); 
        Message msg = mServiceHandler.obtainMessage(); 
        msg.arg1 = 1; 
        mServiceHandler.sendMessage(msg); 
       } 
      } else { 
       name = names[i - 1]; 
       link = uris[i - 1]; 
       pre.edit().putString("name", name); 
       pre.edit().putString("online", online); 
       pre.edit().putString("link", link); 
       Message msg = mServiceHandler.obtainMessage(); 
       msg.arg1 = 1; 
       mServiceHandler.sendMessage(msg); 
      } 
     } 
    }; 
    stopFromNoti = new BroadcastReceiver() { 

     @Override 
     public void onReceive(Context arg0, Intent arg1) { 
      if (playHandler != null) { 
       playing = false; 
       Intent in = new Intent(Mp3Constants.NOTIFICATION); 
       in.putExtra("download", "0"); 
       in.putExtra("online", online); 
       in.putExtra("status", Mp3Constants.COMPLETED); 
       in.putExtra("name", name); 
       in.putExtra("currentTime", 
         playHandler.getCurrentPosition()/1000); 
       in.putExtra("totalTime", playHandler.getDuration()/1000); 
       conte.sendBroadcast(in); 
       playHandler.reset(); 
       stopSelf(); 
      } 
      stopSelf(); 
     } 
    }; 
    phoneStateListener = new PhoneStateListener() { 
     @Override 
     public void onCallStateChanged(int state, String incomingNumber) { 
      if (state == TelephonyManager.CALL_STATE_RINGING) { 
       if (playHandler != null) 
        if (playHandler.isPlaying()) { 
         playing = false; 
         playHandler.pause(); 
        } 
      } else if (state == TelephonyManager.CALL_STATE_IDLE) { 
       if (!notFromTelephone) { 
        notFromTelephone = false; 
        if (playHandler != null) 
         if (!playHandler.isPlaying()) { 
          playSongNow(); 
         } 
       } 
      } else if (state == TelephonyManager.CALL_STATE_OFFHOOK) { 
       if (playHandler.isPlaying()) { 
        playing = false; 
        playHandler.pause(); 
       } 
      } 
      super.onCallStateChanged(state, incomingNumber); 
     } 
    }; 
    mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); 
    if (mgr != null) { 
     mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); 
    } 
    pre = getSharedPreferences("download", 0); 
    online = pre.getString("online", "0"); 
    link = pre.getString("link", ""); 
    name = pre.getString("name", ""); 
    contentView = new RemoteViews(getPackageName(), 
      R.layout.online_notification_layout); 
    PendingIntent pit = PendingIntent.getBroadcast(conte, 0, new Intent(
      "stopfromnoti"), PendingIntent.FLAG_UPDATE_CURRENT); 
    contentView.setOnClickPendingIntent(R.id.play_or_pause_noti, pit); 
    notificationManager = (NotificationManager) conte 
      .getSystemService(Context.NOTIFICATION_SERVICE); 
    mBuilder = new NotificationCompat.Builder(conte) 
      .setSmallIcon(R.drawable.icon).setContent(contentView) 
      .setAutoCancel(false); 
    startForeground(55, mBuilder.build()); 
    broadcaster = new BroadcastReceiver() { 

     @Override 
     public void onReceive(Context arg0, Intent arg1) { 
      if (arg1.getExtras().getInt("action") == Mp3Constants.PAUSE) { 
       if (playHandler != null) 
        if (playHandler.isPlaying()) { 
         playing = false; 
         notFromTelephone = true; 
         playHandler.pause(); 
        } 
      } else if (arg1.getExtras().getInt("action") == Mp3Constants.PLAY) { 
       if (playHandler != null) 
        if (!playHandler.isPlaying()) { 
         playSongNow(); 
        } 
      } else if (arg1.getExtras().getInt("action") == Mp3Constants.STOP) { 
       if (playHandler != null) { 
        playHandler.reset(); 
        playing = false; 
       } 
       stopSelf(); 
      } else if (arg1.getExtras().getInt("action") == Mp3Constants.SEEK) { 
       if (playHandler != null) { 
        { 
         playHandler.seekTo(arg1.getExtras() 
           .getInt("seekto") * 1000); 
        } 
       } 
      } else if (arg1.getExtras().getInt("action") == Mp3Constants.FORWARD) { 
       if (playHandler != null) { 
        playHandler.reset(); 
        playing = false; 
       } 
       getSD(); 
       int i = 0; 
       for (i = 0; i < send; i++) { 
        if (link.equalsIgnoreCase(uris[i])) { 
         break; 
        } 
       } 
       if (i >= send - 1) { 
        if (send > 0) { 
         name = names[0]; 
         link = uris[0]; 
         pre.edit().putString("name", name); 
         pre.edit().putString("online", online); 
         pre.edit().putString("link", link); 
         Message msg = mServiceHandler.obtainMessage(); 
         msg.arg1 = 1; 
         mServiceHandler.sendMessage(msg); 
        } 
       } else { 
        name = names[i + 1]; 
        link = uris[i + 1]; 
        pre.edit().putString("name", name); 
        pre.edit().putString("online", online); 
        pre.edit().putString("link", link); 
        Message msg = mServiceHandler.obtainMessage(); 
        msg.arg1 = 1; 
        mServiceHandler.sendMessage(msg); 
       } 

      } else if (arg1.getExtras().getInt("action") == Mp3Constants.BACKWARD) { 
       if (playHandler != null) { 
        playHandler.reset(); 
        playing = false; 
       } 
       getSD(); 
       int i = 0; 
       for (i = 0; i < send; i++) { 
        if (link.equalsIgnoreCase(uris[i])) { 
         break; 
        } 
       } 
       if (i == send || i == 0) { 
        if (send > 0) { 
         name = names[send - 1]; 
         link = uris[send - 1]; 
         pre.edit().putString("name", name); 
         pre.edit().putString("online", online); 
         pre.edit().putString("link", link); 
         Message msg = mServiceHandler.obtainMessage(); 
         msg.arg1 = 1; 
         mServiceHandler.sendMessage(msg); 
        } 
       } else { 
        name = names[i - 1]; 
        link = uris[i - 1]; 
        pre.edit().putString("name", name); 
        pre.edit().putString("online", online); 
        pre.edit().putString("link", link); 
        Message msg = mServiceHandler.obtainMessage(); 
        msg.arg1 = 1; 
        mServiceHandler.sendMessage(msg); 
       } 
      } 
     } 
    }; 
    registerReceiver(broadcaster, new IntentFilter(
      "com.codebrew.bestmp3downloader.PPlayService")); 
    registerReceiver(stopFromNoti, new IntentFilter("stopfromnoti")); 
    registerReceiver(forwardFromNoti, new IntentFilter("forwardFromNoti")); 
    registerReceiver(backwardFromNoti, new IntentFilter("backwardFromNoti")); 
    HandlerThread thread = new HandlerThread("ServiceStartArguments", 0); 

    // //.................. 
    // notificationManager = (NotificationManager) conte 
    // .getSystemService(Context.NOTIFICATION_SERVICE); 
    // mBuilder = new NotificationCompat.Builder(conte); 
    // RemoteViews remoteViews = new RemoteViews(getPackageName(), 
    // R.layout.notification_layout); 
    // try { 
    // mBuilder.setSmallIcon(R.drawable.icon); 
    // mBuilder.setAutoCancel(false).setOngoing(true) 
    // .setContent(remoteViews); 
    // Uri uri = RingtoneManager 
    // .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
    // mBuilder.setSound(uri); 
    // notificationManager.notify(Mp3Constants.NOTIFICATION_NUMBER, 
    // mBuilder.build()); 
    // } catch (Exception e) { 
    // e.printStackTrace(); 
    // } 
    // //................... 

    thread.start(); 
    mServiceHandler = new IncomingHandler(PPlayService.this); 
} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    // online = intent.getExtras().getString("online"); 
    // link = intent.getExtras().getString("link"); 
    // name = intent.getExtras().getString("name"); 
    online = pre.getString("online", "0"); 
    link = pre.getString("link", ""); 
    name = pre.getString("name", ""); 
    Message msg = mServiceHandler.obtainMessage(); 
    msg.arg1 = startId; 
    mServiceHandler.sendMessage(msg); 
    return START_NOT_STICKY; 
} 

@Override 
public IBinder onBind(Intent intent) { 
    return null; 
} 

@Override 
public void onDestroy() { 
    unregisterReceiver(broadcaster); 
    unregisterReceiver(stopFromNoti); 
    unregisterReceiver(forwardFromNoti); 
    unregisterReceiver(backwardFromNoti); 
    if (playHandler != null) { 
     if (playHandler.isPlaying()) { 
      playHandler.stop(); 
     } 
     playHandler = null; 
    } 
    if (mgr != null) { 
     mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE); 
    } 
    super.onDestroy(); 
    notificationManager.cancel(55); 
} 

public void playSongNow() { 
    try { 
     playing = true; 
     playHandler.start(); 
     runnable = new Runnable() { 
      public void run() { 
       while (playing) { 
        try { 
         Thread.sleep(1000); 
        } catch (InterruptedException e) { 
         e.printStackTrace(); 
        } 
        if (playing) { 
         System.gc(); 
         Intent in = new Intent(Mp3Constants.NOTIFICATION); 
         in.putExtra("download", "0"); 
         in.putExtra("online", online); 
         in.putExtra("name", name); 
         in.putExtra("status", Mp3Constants.PLAYING); 
         in.putExtra("currentTime", 
           playHandler.getCurrentPosition()/1000); 
         in.putExtra("totalTime", 
           playHandler.getDuration()/1000); 
         contentView.setTextViewText(R.id.current_time_, 
           getDurationString(playHandler 
             .getCurrentPosition()/1000)); 
         contentView.setTextViewText(R.id.name_of_the_song, 
           name); 
         contentView 
           .setTextViewText(R.id.total_time_, 
             getDurationString(playHandler 
               .getDuration()/1000)); 
         try { 
          notificationManager.notify(55, mBuilder 
            .setContent(contentView).build()); 
         } catch (Exception e) { 
          e.printStackTrace(); 
         } 
         conte.sendBroadcast(in); 
        } 
       } 
      } 
     }; 
     new Thread(runnable).start(); 
     playHandler.setOnCompletionListener(new OnCompletionListener() { 

      @Override 
      public void onCompletion(MediaPlayer mp) { 
       playing = false; 
       Intent in = new Intent(Mp3Constants.NOTIFICATION); 
       in.putExtra("download", "0"); 
       in.putExtra("online", online); 
       in.putExtra("status", Mp3Constants.COMPLETED); 
       in.putExtra("name", name); 
       try { 
        in.putExtra("currentTime", 
          playHandler.getCurrentPosition()/1000); 
        in.putExtra("totalTime", 
          playHandler.getDuration()/1000); 
       } catch (Exception e) { 
        in.putExtra("currentTime", 0); 
        in.putExtra("totalTime", 0); 
       } 
       conte.sendBroadcast(in); 
       if (online.equals("0")) { 
        if (pre.getBoolean("repeat", false)) { 
         pre.edit().putString("name", name); 
         pre.edit().putString("online", online); 
         pre.edit().putString("link", link); 
         Message msg = mServiceHandler.obtainMessage(); 
         msg.arg1 = 1; 
         mServiceHandler.sendMessage(msg); 
        } else { 
         getSD(); 
         if (pre.getBoolean("shuffle", false)) { 
          Random r = new Random(); 
          int x = r.nextInt(send); 
          link = uris[x]; 
          name = names[x]; 
          pre.edit().putString("name", name); 
          pre.edit().putString("online", online); 
          pre.edit().putString("link", link); 
          Message msg = mServiceHandler.obtainMessage(); 
          msg.arg1 = 1; 
          mServiceHandler.sendMessage(msg); 
         } else { 
          for (int i = 0; i < send - 1; i++) { 
           if (link.equalsIgnoreCase(uris[i])) { 
            link = uris[i + 1]; 
            name = names[i + 1]; 
            pre.edit().putString("name", name); 
            pre.edit().putString("online", online); 
            pre.edit().putString("link", link); 
            Message msg = mServiceHandler 
              .obtainMessage(); 
            msg.arg1 = 1; 
            mServiceHandler.sendMessage(msg); 
            break; 
           } 
          } 
         } 
        } 
       } 
       if (online.equals("1")) { 
        stopSelf(); 
       } 
      } 
     }); 
    } catch (Exception e) { 
     playing = false; 
     Intent in = new Intent(Mp3Constants.NOTIFICATION); 
     in.putExtra("download", "0"); 
     in.putExtra("online", online); 
     in.putExtra("name", name); 
     in.putExtra("status", Mp3Constants.FAILED); 
     in.putExtra("currentTime", 0); 
     in.putExtra("totalTime", 0); 
     conte.sendBroadcast(in); 
     Toast.makeText(
       getBaseContext(), 
       "Error playing: " 
         + name 
         + "\nFile broken or deleted! Please try another song", 
       Toast.LENGTH_SHORT).show(); 
     stopSelf(); 
    } 
} 

private void getSD() { 
    File f = new File(Environment.getExternalStorageDirectory().toString() 
      + "/Music"); 
    File[] files = f.listFiles(); 
    if (files == null) { 
     return; 
    } 
    Arrays.sort(files, new Comparator<Object>() { 
     public int compare(Object o1, Object o2) { 

      if (((File) o1).lastModified() > ((File) o2).lastModified()) { 
       return +1; 
      } else if (((File) o1).lastModified() < ((File) o2) 
        .lastModified()) { 
       return -1; 
      } else { 
       return 0; 
      } 
     } 
    }); 
    send = files.length; 
    uris = new String[send]; 
    names = new String[send]; 
    for (int i = 0; i < send; i++) { 
     File file = files[i]; 
     // take the file name only 
     double size = file.length(); 
     size = size/(1024 * 1024); 
     String myfile = file 
       .getPath() 
       .substring(file.getPath().lastIndexOf("/") + 1, 
         file.getPath().length()).toLowerCase(); 
     uris[send - 1 - i] = file.getPath(); 
     names[send - 1 - i] = myfile; 
    } 
} 

private String getDurationString(int seconds) { 

    int hours = seconds/3600; 
    int minutes = (seconds % 3600)/60; 
    seconds = seconds % 60; 

    if (hours == 0) 
     return twoDigitString(minutes) + ":" + twoDigitString(seconds); 
    else 
     return twoDigitString(hours) + ":" + twoDigitString(minutes) + ":" 
       + twoDigitString(seconds); 
} 

private String twoDigitString(int number) { 

    if (number == 0) { 
     return "00"; 
    } 

    if (number/10 == 0) { 
     return "0" + number; 
    } 

    return String.valueOf(number); 
} 

static class IncomingHandler extends Handler { 
    private final WeakReference<PPlayService> mService; 

    IncomingHandler(PPlayService service) { 
     mService = new WeakReference<PPlayService>(service); 
    } 

    @Override 
    public void handleMessage(Message msg) { 
     PPlayService service = mService.get(); 
     if (service != null) { 
      service.handleMessage(msg); 
     } 
    } 
} 

}

+0

tl; dr,对不起。在询问之前,你需要缩小一点。尝试删除不必要的部分,直到您有100条左右的线条,但仍然重现该问题。 – njzk2

+0

将代码粘贴到您的问题中,而不是使用第三方网站 – Benoit

+0

@ njzk2我找不出代码中的问题所在,因此我发布了整个代码。 – berserk

回答

0

没有,没有任何已知的错误,使服务于长时间使用后色拉了你的设备。代码中可能有一个错误。尝试使用DDMS tool来分析您的应用程序并发现泄漏。

+0

这是一些内存泄漏问题吗? – berserk

+0

@berserk听起来很像。 –

+0

我有一个问题。我每秒更新通知中的远程视图。这是问题的原因吗? – berserk