即使应用关闭,也要保持服务正常运行

时间:2014-06-13 16:39:41

标签: android service

我正在实施用于在Android设备中接收推送通知的服务。当应用处于前台时,会成功收到通知。关闭应用程序并从任务管理器清除其实例时,不会收到通知。

我希望服务始终保持运行,即使从任务管理器中清除了应用程序,它也不会停止。

我通过点击按钮从我的活动中启动服务。当我点击按钮时,我的服务启动,它每隔一分钟给我一次Toast通知,但如果我按下后退按钮,那么我的服务也在运行,但是,一旦我从最近的活动列表清除我的应用程序,这在长按主页按钮我的服务是停止的,如果我再次启动我的应用程序并检查服务的状态,但它没有运行。

即使我的应用已关闭,我也希望我的服务能够投放。

这是我的活动课

package com.example.hello;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;

public class MainActivity extends Activity {

    Button btnSer;
    int Pointer=0;
    ListView lv;
    ArrayList<String> alist=new ArrayList<String>();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnSer=(Button) findViewById(R.id.btnstart);
        btnSer.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                //start  the service when the button is clicked
                Log.e("","status of service : "+isMyServiceRunning(MyService.class));
                //if(!isMyServiceRunning(MyService.class))
                    startService(new Intent(getApplicationContext(), MyService.class));
            }
        });

    }

    //check if the service is running
    private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }


}

这是我的服务类。

 package com.example.hello;

import java.util.Calendar;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service{

    private Handler handlerList = new Handler(); 
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
      public int onStartCommand(Intent intent, int flags, int startId) {
        //TODO do something useful
        Toast.makeText(getApplicationContext(), "On start command called", Toast.LENGTH_LONG).show();
         return Service.START_STICKY;
    }
    public void updateLists(){
        handlerList.postDelayed(mUpdateListTask, 1000*60);
    }
    private Runnable mUpdateListTask = new Runnable() {
        public void run() {  //will make a toast notification every 1 minute.
            Calendar cal = Calendar.getInstance();

            Log.e("","Thread executed at "+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE)+":"+cal.get(Calendar.SECOND)+":");
            Toast.makeText(getApplicationContext(), "Thread executed at "+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE)+":"+cal.get(Calendar.SECOND)+":", Toast.LENGTH_LONG).show();
           handlerList.postDelayed(this, 1000*60);
        }};
    @Override
    public void onCreate() {

        updateLists();
        Toast.makeText(this, "Congrats! MyService Created", Toast.LENGTH_LONG).show();
        Log.d("", "onCreate in service");
    }

    @Override
    public void onStart(Intent intent, int startId) {
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Log.d("", "onStart in service");    
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
        Log.d("", "onDestroy in service");
    }
}

还在清单文件中添加了权限

<uses-permission android:name="android.permission.WAKE_LOCK" />

1 个答案:

答案 0 :(得分:0)

在活动使用startforeground(intent name)中将其作为前台服务启动,并在服务onstartCommand()方法中将其作为粘性返回。