2012-02-07 90 views
6

在我的項目中,我需要在android中創建一個服務。我能夠註冊服務是這樣的:在Android中創建後臺服務

<application 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" > 

    <service android:enabled="true" 
    android:name=".ServiceTemplate"/> 
     <activity 
     android:name=".SampleServiceActivity" 
     android:label="@string/app_name" > 
     <intent-filter> 
     <action android:name="android.intent.action.MAIN" /> 
     <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
</application> 

我打電話就像低於活動內此項服務: -

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    Intent service = new Intent(getApplicationContext(), ServiceTemplate.class); 
    this.startService(service); 
} 

但是,如果我殺了當前活動,該服務也被毀壞。我需要此服務始終在後臺運行。 我需要做什麼? 如何註冊該服務? 如何開始服務?

+1

可以請你接受,對於這個問題,工作的答案嗎? – abhinav 2014-12-25 23:33:17

回答

4

但是,如果我殺了目前的活動服務也正在殺害。我需要此服務始終在後臺運行。我需要做什麼?

如果通過「終止當前活動」,您的意思是您正在使用任務殺手或強制停止,那麼您的服務將會停止。對此你無能爲力。用戶表示他們不希望您的應用再運行;請尊重用戶的意願。

如果通過「殺死當前活動」,你的意思是你按了BACK或HOME或其他東西,那麼除非你撥打stopService(),否則該服務應該繼續運行,至少有一段時間。它不會永遠運行--Android將最終擺脫服務,因爲太多開發人員編寫的服務試圖「始終在後臺運行」。和。當然,用戶可以在用戶想要的時候終止服務。

服務只有在積極爲用戶傳遞價值時才應該「運行」。這通常意味着服務不應該「始終在後臺運行」。相反,請使用AlarmManagerIntentService定期進行工作。

+0

我正在用adb shell kill命令查殺當前活動。只是我喜歡創建像報警,短信通知等服務...... – Sathish 2012-02-07 14:25:03

+0

@Sathish:我不知道「adb shell kill命令」是有記錄的,所以我不知道它的特徵是什麼。 – CommonsWare 2012-02-07 17:12:59

1

重寫此方法:

public int onStartCommand(Intent intent, int flags, int startId) { 
    return Service.START_STICKY; 
} 
+0

它會永遠在後臺運行嗎? – 2016-01-10 17:09:09

3

嘗試在單獨的線程啓動該服務,所以,當你將摧毀你的活動的服務將不會受到影響。它會毫無中斷地運行。此外,在服務返回Service.START_STICKYonStartCommand(intent, flags, startId)以確保服務被重新創建,如果它被系統(Android OS)殺死。

4

下面是一個半不同的方式來保持服務永遠。有方法來殺死它的代碼,如果你想

後臺服務:

package com.ex.ample; 

import android.app.Service; 
import android.content.*; 
import android.os.*; 
import android.widget.Toast; 

public class BackgroundService extends Service { 

    public Context context = this; 
    public Handler handler = null; 
    public static Runnable runnable = null; 

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

    @Override 
    public void onCreate() { 
     Toast.makeText(this, "Service created!", Toast.LENGTH_LONG).show(); 

     handler = new Handler(); 
     runnable = new Runnable() { 
      public void run() { 
       Toast.makeText(context, "Service is still running", Toast.LENGTH_LONG).show(); 
       handler.postDelayed(runnable, 10000); 
      } 
     }; 

     handler.postDelayed(runnable, 15000); 
    } 

    @Override 
    public void onDestroy() { 
     /* IF YOU WANT THIS SERVICE KILLED WITH THE APP THEN UNCOMMENT THE FOLLOWING LINE */ 
     //handler.removeCallbacks(runnable); 
     Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show(); 
    } 

    @Override 
    public void onStart(Intent intent, int startid) { 
     Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show(); 
    } 
} 

這裏是你怎麼從你的主要活動啓動它或者你想去的地方:

startService(new Intent(this, BackgroundService.class)); 

onDestroy()將在應用程序關閉或死亡時被調用,但可運行的程序剛剛啓動它。您還需要刪除處理程序回調。

我希望這可以幫助別人。

爲什麼有些人這樣做的原因是因爲企業應用中,在某些情況下,用戶/僱員必須不能阻止某些事情:)

http://i.imgur.com/1vCnYJW.png

4

你可以創建後臺服務並呼籲通過AlarmManager

1 - 你必須創建一個BroadcastReceiver類由 調用AlarmManager

public class AlarmReceiver extends BroadcastReceiver 

{ 
    /** 

    * Triggered by the Alarm periodically (starts the service to run task) 

    * @param context 

    * @param intent 

    */ 

    @Override 

    public void onReceive(Context context, Intent intent) 

    { 

     Intent i = new Intent(context, AlmasService.class); 

     i.putExtra("foo", "AlarmReceiver"); 

     context.startService(i); 

    } 

} 

2,你必須創建一個IntentService類由 調用AlarmReceiver

public class AlmasService extends IntentService 

{ 

    public Context context=null; 

    // Must create a default constructor 
    public AlmasService() { 

     // Used to name the worker thread, important only for debugging. 
     super("test-service"); 

    } 

    @Override 

    public void onCreate() { 

     super.onCreate(); // if you override onCreate(), make sure to call super(). 

    } 


    @Override 
    protected void onHandleIntent(Intent intent) { 

     context=this; 
     try 

     { 

      Thread.sleep(5000); 

     } 

     catch (InterruptedException e) 

     { 

      e.printStackTrace(); 

     } 



     String val = intent.getStringExtra("foo"); 

     // Do the task here 
     Log.i("MyTestService", val); 

    } 

} 

3-你必須AlarmReceiver添加爲接收器和AlmasService作爲艙單

服務
<service 
     android:name=".ServicesManagers.AlmasService" 
     android:exported="false"/> 

    <receiver 
     android:name=".ServicesManagers.AlmasAlarmReceiver" 
     android:process=":remote" > 
    </receiver> 

4,現在你就可以開始和呼叫AlarmManager在MainActivity

public class MainActivity extends AppCompatActivity 
{ 
    public static final int REQUEST_CODE = (int) new Date().getTime(); 

    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     scheduleAlarm(); 
    } 

    public void scheduleAlarm() 
    { 
     // Construct an intent that will execute the AlarmReceiver 
     Intent intent = new Intent(getApplicationContext(), AlmasAlarmReceiver.class); 
     // Create a PendingIntent to be triggered when the alarm goes off 
     final PendingIntent pIntent = PendingIntent.getBroadcast(
       this, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT); 
     // Setup periodic alarm every every half hour from this point onwards 
     long firstMillis = System.currentTimeMillis(); // alarm is set right away 
     AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); 
     // First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP 
     // Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY 
     alarm.setRepeating(AlarmManager.RTC_WAKEUP, firstMillis, (long) (1000 * 60), pIntent); 



    } 
}