Android服务没有在后台运行?

时间:2015-06-05 07:50:39

标签: android android-service

当我按下主页按钮或后退按钮时服务运行但是当应用程序关闭时服务没有在后台运行。此外,该服务在某些(LG Nexus 5)手机的后台运行,但在大多数手机(三星,Xioami)服务未关闭应用程序时运行。当我转到设置>应用>正在运行,它始终显示为app运行并显示1个服务1个线程。我从MainActivity.java调用服务

即使应用已关闭,我希望该服务始终在后台运行。任何帮助将不胜感激。

以下是服务TimeService.java的代码

In app/autocomplete_light_registry.py

from django.utils.encoding import force_text

class ItemAutocomplete(autocomplete_light.AutocompleteModelBase):
search_fields = ['serial_number']
model = Item
choices = Item.objects.all()

def choice_label(self, choice):
    """
    Return the human-readable representation of a choice. 
    """

    barcode = Item.objects.get(pk=self.choice_value(choice)).barcode
    return force_text(barcode)

autocomplete_light.register(ItemAutocomplete)

MainActivity.java

public class TimeService extends Service implements
        ConnectionCallbacks, OnConnectionFailedListener {
    // constant
    public static final long NOTIFY_INTERVAL =  30 * 60 * 1000; // 30 minutes

// run on another Thread to avoid crash
private Handler mHandler = new Handler();
// timer handling
private Timer mTimer = null;

@Override
public void onCreate() {
    // cancel if already existed
    if (mTimer != null) {
        mTimer.cancel();
    } else {
        // recreate new
        mTimer = new Timer();
    }
    // schedule task
    mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
}

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


class TimeDisplayTimerTask extends TimerTask {


    @Override
    public void run() {
        // run on another thread
        mHandler.post(new Runnable() {

            @Override
            public void run() {
                // Send message in background

               sendSMS(number,msg)

                               }
                         });
                 }
             }

Android清单

public class MainActivity extends Activity
{
    Button btnIn;
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    btnIn = (Button) findViewById(R.id.btnIn);

    btnIn.setOnClickListener(new View.OnClickListener() {

        boolean enable = true;
        @Override
        public void onClick(View v) {

                Intent intent = new Intent(MainActivity.this, TimeService.class);
                   startService(intent);
}
}
}

2 个答案:

答案 0 :(得分:0)

如果您希望保持服务,则应使用前台服务。

要做到这一点,你必须在前台运行服务

private void runForeground(){
//... Pending intent if you want attach it to the notification


Notification notification=new NotificationCompat.Builder(this)
                            .setSmallIcon(R.drawable.ic_launcher)
                            .setContentText(getString(R.string.string))
                            .setContentIntent(pendingIntent).build();

startForeground(NOTIFICATION_ID, notification);

}

NOTIFICATION_ID是用于识别它的号码,返回粘贴服务。

答案 1 :(得分:0)

我在一个单独的线程中运行后台任务,而它应该在主线程中,这就是应用程序在某些手机中没有在后台运行的原因。

class TimeDisplayTimerTask extends TimerTask {
@Override
public void run() {       
            // Send message in background
           sendSMS(number,msg);
             }
}