应用程序杀死onBackPressed android

时间:2015-01-21 08:08:35

标签: android back-button

我从一个从服务获取消息并在对话框中显示的活动启动服务。当我点击后退或主页按钮时,应用程序被杀死。在多任务处理区域找不到应用程序。我没有在onBackPressed()上编写任何代码。我该如何纠正这个问题?服务代码。

public class BleepService extends Service{
String gotAlert;
Context context;
String drAlert=null;
public static boolean status = false;

public static final String TAG = BleepService.class.getSimpleName();
int counter = 0;    
static final int UPDATE_INTERVAL = 5000;
private Timer timer = new Timer();
String resServer;

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("SERVICE", "COMES TO THE ON STARTCOMMAND");   
    doRepeat();     
    //return super.onStartCommand(intent, flags, startId);
    return START_STICKY; 
}

private void doRepeat() {
    Log.i("SERVICE", "COMES TO THE DOREPEAT METHOD");
    timer.scheduleAtFixedRate(new TimerTask() {
    public void run() { 

    new GetStatus().execute();      

    }
    }, 1000, UPDATE_INTERVAL);
}

class GetStatus extends  AsyncTask<Void, Void, String>
{
    @Override
    protected String doInBackground(Void... params) {           
        ServiceHandler sh = new ServiceHandler();
        resServer = sh.makeServiceCall(Urllist.urlGetPagerStatus, ServiceHandler.GET);
        while(resServer.equals("1"))
        {
        status = true;
        resServer = sh.makeServiceCall(Urllist.urlGetMsg, ServiceHandler.GET);              
        }
        return resServer;
    }
    @Override
    protected void onPostExecute(String result) {

        Log.i("SERVICE", "COMES TO THE GetStatus AsyncTask Class");
        super.onPostExecute(result);        
        if(!result.equals("0"))
        {       

            Intent i = new Intent("com.bleep.DR_ALERT_MESSAGE");
            i.putExtra("msg", result);
            sendBroadcast(i);

        }else{
            Toast.makeText(getApplicationContext(), "No New Message", Toast.LENGTH_SHORT).show();
        }
    }       
}


@Override
public void onDestroy() {
    //timer.cancel();
    //super.onDestroy();
    /*if (timer != null){
        timer.cancel();
    }*/
}
}

1 个答案:

答案 0 :(得分:0)

确保Service在其START_STICKY中返回onStartCommand。这样,如果它被杀死,操作系统将重启它。

当应用程序在后台时,应用程序被Android杀死是合法的。

但是,操作系统很少会杀死Services。你确定你自己也不会以某种方式杀死它吗?