2015-06-05 224 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