2015-06-05 139 views
0

当我按下主页按钮或返回按钮时服务运行,但当应用程序关闭时服务未在后台运行。此外,该服务在某些(LG Nexus 5)手机中以后台运行,但在大多数手机(Samsung,Xioami)服务在应用程序关闭时未运行。当我转到设置>应用程序>运行时,它总是显示为应用程序运行并显示1个服务1线程。我打电话来自MainActivity.java的服务Android服务未在后台运行?

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

这里是服务TimeService.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) 

           } 
         }); 
       } 
      } 

MainActivity.java

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); 
} 
} 
} 

Android清单

<service android:name=".TimeService" /> 
+0

“app is closed”是什么意思?按回来键或杀死进程? – shhp

+0

杀死过程即。从多任务中删除 – Jitin

+0

您如何知道服务未运行? – shhp

回答

0

我在一个单独的线程中运行后台任务,而它应该在主线程中,这是应用程序未在某些电话的后台运行的原因。

class TimeDisplayTimerTask extends TimerTask { 
@Override 
public void run() {  
      // Send message in background 
      sendSMS(number,msg); 
      } 
} 
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是确定一个数字,返回粘服务。

+0

我应该在哪里调用? – Jitin

+0

你应该调用它onCreate – Ivan

+0

我不希望应用程序在运行时显示通知,所以我没有使用此代码.. Thx反正 – Jitin