如何从自动查杀的应用程序停止的Andr​​oid? [英] How do I stop Android from auto-killing an app?

查看:150
本文介绍了如何从自动查杀的应用程序停止的Andr​​oid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从自动查杀的应用程序停止的Andr​​oid? 我的电台应用程序自动杀死5:15分钟后。我需要我的电台播放器所有的工作时间,而不是被杀死。 我使用 startForegroundCompat 但不工作的好仍可自动杀死15后:20分

 包com.test.test;

进口java.io.IOException异常;

进口android.app.Notification;
进口android.app.NotificationManager;
进口android.app.PendingIntent;
进口android.app.Service;
进口android.content.Context;
进口android.content.Intent;
进口android.content.Shared preferences;
进口android.media.AudioManager;
进口android.media.AudioManager.OnAudioFocusChangeListener;
进口android.media.MediaPlayer;
进口android.os.IBinder;
。进口的Andr​​oid preference preferenceManager。
进口android.util.Log;

公共类StreamService延伸服务{
    私有静态最后字符串变量=StreamService;
    MediaPlayer的熔点;
    布尔IsPlaying模块;
    意图MainActivity;

    共享preferences preFS;
    共享preferences.Editor编辑;
    通知N;
    NotificationManager notificationManager;

    //改变这个INT一些数专门为这个应用程序
    INT notifId = 85;

     私人OnAudioFocusChangeListener focusChangeListener =
              新OnAudioFocusChangeListener(){
                      公共无效onAudioFocusChange(INT focusChange){
                        开关(focusChange){

                               案例(AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK):
                               //降低音量,同时回避。
                               mp.setVolume(0.2F,0.2F);
                               打破;
                               案例(AudioManager.AUDIOFOCUS_LOSS_TRANSIENT):
                               mp.pause();
                               打破;

                               案例(AudioManager.AUDIOFOCUS_LOSS):
                               mp.stop();

                               打破;

                               案例(AudioManager.AUDIOFOCUS_GAIN):
                               //返回体积正常,如果继续暂停。
                               mp.setVolume(1F,1F);
                               mp.start();
                               打破;
                               默认值:打破;
    }
    }
    };

    @覆盖
    公众的IBinder onBind(意向为arg0){
        // TODO自动生成方法存根
        返回null;
    }

    @燮pressWarnings(德precation)
    @覆盖
    公共无效的onCreate(){
        super.onCreate();
        Log.d(TAG的onCreate);

        //初始化共享preferences和编辑器
        preFS = preferenceManager.getDefaultShared preferences(getApplicationContext());
        编辑= prefs.edit();

        //设置缓冲通知
        notificationManager =(NotificationManager)getApplicationContext()
                .getSystemService(NOTIFICATION_SERVICE);
        上下文的背景下= getApplicationContext();

        字符串notifTitle = context.getResources()的getString(R.string.app_name)。
        。字符串notifMessage = context.getResources()的getString(R.string.buffering);

        N =新的通知();
        n.icon = R.drawable.ic_launcher;
        n.tickerText =缓冲;
        n.when = System.currentTimeMillis的();

        意图nIntent =新的意图(背景下,MainActivity.class);
        nIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent pIntent = PendingIntent.getActivity(上下文,0,nIntent,0);

        n.setLatestEventInfo(背景下,notifTitle,notifMessage,pIntent);

        notificationManager.notify(notifId,N);

        //这是非常重要的,你把你的Shoutcast的流的IP / URL这里

        字符串URL =htt​​p://90.121.123.129:8272;
        熔点为新的MediaPlayer();
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);

        尝试 {
            mp.setDataSource(URL);
            MP prepare()。
            熔点:prepareAsync();
            mp.setOnErrorListener(空);
        }赶上(抛出:IllegalArgumentException E){
            // TODO自动生成的catch块
            e.printStackTrace();
        }赶上(SecurityException异常E){
            // TODO自动生成的catch块
            Log.e(TAG,SecurityException异常);
        }赶上(IllegalStateException异常E){
            // TODO自动生成的catch块
            Log.e(TAG,IllegalStateException异常);
        }赶上(IOException异常E){
            // TODO自动生成的catch块
            Log.e(TAG,IOException异常);
        }
    }

    @燮pressWarnings(德precation)
    @覆盖
    公共无效ONSTART(意向意图,诠释startId){
        Log.d(TAG,ONSTART);
        mp.start();

        //设置IsPlaying模块preference为真
        editor.putBoolean(IsPlaying模块,真正的);
        editor.commit();

        上下文的背景下= getApplicationContext();
        字符串notifTitle = context.getResources()的getString(R.string.app_name)。
        。字符串notifMessage = context.getResources()的getString(R.string.now_playing);

        n.icon = R.drawable.ic_launcher;
        n.tickerText = notifMessage;
        n.flags = Notification.FLAG_NO_CLEAR;
        n.when = System.currentTimeMillis的();

        意图nIntent =新的意图(背景下,MainActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(上下文,0,nIntent,0);

        n.setLatestEventInfo(背景下,notifTitle,notifMessage,pIntent);
        //改变5315的一些诺特尔数
        notificationManager.notify(notifId,N);
    / *
        AudioManager上午=(AudioManager)getSystemService(Context.AUDIO_SERVICE);

        //请求音频焦点回放
        INT结果= am.requestAudioFocus(focusChangeListener,
        //使用音乐流。
        AudioManager.STREAM_MUSIC,
        //请求持久焦点。
        AudioManager.AUDIOFOCUS_GAIN);


        如果(结果== AudioManager.AUDIOFOCUS_REQUEST_GRANTED){
        //其他应用程序已经停止正在播放的歌曲,你还是你现在能做的ü的东西。

        }
        * /

            }

    @燮pressWarnings(德precation)
    @覆盖
    公众诠释onStartCommand(意向意图,诠释标志,诠释startId){
        //我们希望这项服务继续运行,直到它被明确
        //停止,因此返回粘​​。
        mp.start();
        //设置IsPlaying模块preference为真
                editor.putBoolean(IsPlaying模块,真正的);
                editor.commit();

                上下文的背景下= getApplicationContext();
                字符串notifTitle = context.getResources()的getString(R.string.app_name)。
                。字符串notifMessage = context.getResources()的getString(R.string.now_playing);

                n.icon = R.drawable.ic_launcher;
                n.tickerText = notifMessage;
                n.flags = Notification.FLAG_NO_CLEAR;
                n.when = System.currentTimeMillis的();

                意图nIntent =新的意图(背景下,MainActivity.class);
                PendingIntent pIntent = PendingIntent.getActivity(上下文,0,nIntent,0);

                n.setLatestEventInfo(背景下,notifTitle,notifMessage,pIntent);
                //改变5315的一些诺特尔数
                notificationManager.notify(notifId,N);
                AudioManager上午=(AudioManager)getSystemService(Context.AUDIO_SERVICE);

                //请求音频焦点回放
                INT结果= am.requestAudioFocus(focusChangeListener,
                //使用音乐流。
                AudioManager.STREAM_MUSIC,
                //请求持久焦点。
                AudioManager.AUDIOFOCUS_GAIN);


                如果(结果== AudioManager.AUDIOFOCUS_REQUEST_GRANTED){
                //其他应用程序已经停止正在播放的歌曲,你还是你现在能做的ü的东西。

                }



        返回START_STICKY;
    }
    无效startForegroundCompat(INT ID,通知通告){
        //如果我们有新的startForeground API,然后使用它。

            mp.start();

            返回;

        }
    @覆盖
    公共无效的onDestroy(){
        Log.d(TAG的onDestroy);
        mp.stop();
        mp.release();
        熔点=无效;
        editor.putBoolean(IsPlaying模块,假);
        editor.commit();
        notificationManager.cancel(notifId);
        AudioManager上午=(AudioManager)getSystemService(Context.AUDIO_SERVICE);

        am.abandonAudioFocus(focusChangeListener);


    }

}
 

解决方案

您不能做到这一点,你不应该这样做。它的Andr​​oid谁决定哪些应用程序应该运行,什么人都被杀害。您必须设计应用程序来处理这种情况,并保存敏感数据的

How do I stop Android from auto-killing an app? My radio app auto-killed after 5:15 minutes. I need my radio player work all time and Not be killed . i use startForegroundCompat but not work good and still auto-killed after 15 : 20 minutes

package com.test.test;

import java.io.IOException;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;

public class StreamService extends Service {
    private static final String TAG = "StreamService";
    MediaPlayer mp;
    boolean isPlaying;
    Intent MainActivity;

    SharedPreferences prefs;
    SharedPreferences.Editor editor;
    Notification n;
    NotificationManager notificationManager;

    // Change this int to some number specifically for this app
    int notifId = 85;

     private OnAudioFocusChangeListener focusChangeListener =
              new OnAudioFocusChangeListener() {
                      public void onAudioFocusChange(int focusChange) {
                        switch (focusChange) {

                               case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) :
                               // Lower the volume while ducking.
                               mp.setVolume(0.2f, 0.2f);
                               break;
                               case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) :
                               mp.pause();
                               break;

                               case (AudioManager.AUDIOFOCUS_LOSS) :
                               mp.stop();

                               break;

                               case (AudioManager.AUDIOFOCUS_GAIN) :
                               // Return the volume to normal and resume if paused.
                               mp.setVolume(1f, 1f);
                               mp.start();
                               break;
                               default: break;
    }
    }
    };

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

    @SuppressWarnings("deprecation")
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate");

        // Init the SharedPreferences and Editor
        prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        editor = prefs.edit();

        // Set up the buffering notification
        notificationManager = (NotificationManager) getApplicationContext()
                .getSystemService(NOTIFICATION_SERVICE);
        Context context = getApplicationContext();

        String notifTitle = context.getResources().getString(R.string.app_name);
        String notifMessage = context.getResources().getString(R.string.buffering);

        n = new Notification();
        n.icon = R.drawable.ic_launcher;
        n.tickerText = "Buffering";
        n.when = System.currentTimeMillis();

        Intent nIntent = new Intent(context, MainActivity.class);
        nIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent pIntent = PendingIntent.getActivity(context, 0, nIntent, 0);

        n.setLatestEventInfo(context, notifTitle, notifMessage, pIntent);

        notificationManager.notify(notifId, n);

        // It's very important that you put the IP/URL of your ShoutCast stream here

        String url = "http://90.121.123.129:8272";
        mp = new MediaPlayer();
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);

        try {
            mp.setDataSource(url);
            mp.prepare();
            mp.prepareAsync();
            mp.setOnErrorListener(null);
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            Log.e(TAG, "SecurityException");
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            Log.e(TAG, "IllegalStateException");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.e(TAG, "IOException");
        }   
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onStart(Intent intent, int startId) {
        Log.d(TAG, "onStart");
        mp.start();

        // Set the isPlaying preference to true
        editor.putBoolean("isPlaying", true);
        editor.commit();

        Context context = getApplicationContext();
        String notifTitle = context.getResources().getString(R.string.app_name);
        String notifMessage = context.getResources().getString(R.string.now_playing);

        n.icon = R.drawable.ic_launcher;
        n.tickerText = notifMessage;
        n.flags = Notification.FLAG_NO_CLEAR;
        n.when = System.currentTimeMillis();

        Intent nIntent = new Intent(context, MainActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(context, 0, nIntent, 0);

        n.setLatestEventInfo(context, notifTitle, notifMessage, pIntent);
        // Change 5315 to some nother number
        notificationManager.notify(notifId, n);
    /*
        AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

        // Request audio focus for playback
        int result = am.requestAudioFocus(focusChangeListener,
        // Use the music stream.
        AudioManager.STREAM_MUSIC,
        // Request permanent focus.
        AudioManager.AUDIOFOCUS_GAIN);


        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        // other app had stopped playing song now , so u can do u stuff now .

        }
        */

            }

    @SuppressWarnings("deprecation")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        mp.start();
        // Set the isPlaying preference to true
                editor.putBoolean("isPlaying", true);
                editor.commit();

                Context context = getApplicationContext();
                String notifTitle = context.getResources().getString(R.string.app_name);
                String notifMessage = context.getResources().getString(R.string.now_playing);

                n.icon = R.drawable.ic_launcher;
                n.tickerText = notifMessage;
                n.flags = Notification.FLAG_NO_CLEAR;
                n.when = System.currentTimeMillis();

                Intent nIntent = new Intent(context, MainActivity.class);
                PendingIntent pIntent = PendingIntent.getActivity(context, 0, nIntent, 0);

                n.setLatestEventInfo(context, notifTitle, notifMessage, pIntent);
                // Change 5315 to some nother number
                notificationManager.notify(notifId, n);
                AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

                // Request audio focus for playback
                int result = am.requestAudioFocus(focusChangeListener,
                // Use the music stream.
                AudioManager.STREAM_MUSIC,
                // Request permanent focus.
                AudioManager.AUDIOFOCUS_GAIN);


                if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                // other app had stopped playing song now , so u can do u stuff now .

                }



        return START_STICKY;
    }
    void startForegroundCompat(int id, Notification notification) {
        // If we have the new startForeground API, then use it.

            mp.start();

            return;

        }
    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy");
        mp.stop();
        mp.release();
        mp = null;
        editor.putBoolean("isPlaying", false);
        editor.commit();
        notificationManager.cancel(notifId);
        AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

        am.abandonAudioFocus(focusChangeListener);


    }

}

解决方案

You cannot do this, and you should never do this. It's Android who decides what app should be running, and what should be killed. You must design your application to handle such situations and save sensitive data

这篇关于如何从自动查杀的应用程序停止的Andr​​oid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆