android 實現後台服務及源碼下載

來源:互聯網
上載者:User

標籤:android後台服   後台進程   系統廣播   服務service   receiver   

android APP後台服務可以長期與伺服器進行長期的互動,保證資料的即時性,這個小項目主要實現的是在app退出之後依然可以運行服務。使用系統的Intent.ACTION_TIME_TICK進行實現,這個系統的廣播每隔一分鐘就進行廣播一次,可以在程式中接收該廣播訊息,接收到之後檢測app中的service服務是否在運行,如果在運行,則不處理,如果沒有運行,則重新啟動該service服務。
值得注意的是,雖然本樣本可以實現後台運行服務的功能,但是當使用者按home鍵進行清楚記憶體的時候依然可以把app清楚記憶體。app清楚記憶體之後,不再運行,當然也就不能實現什麼功能(如接收訊息推送),就是達不到像QQ、那樣,清楚記憶體之後,QQ和依然在後台運行。
下面開始講述本項目的實現過程。
我們知道,註冊廣播接收者有兩種方式,一種是在設定檔中進行配置,另一種是在代碼中進行註冊。該廣播需要在代碼中進行註冊。這裡需要注意的是註冊廣播接收者可以在Activity中進行註冊,但是如果在Activity中進行註冊,必須在onDestory的時候進行登出廣播接收者,如果不登出,會出現Error錯誤。有因為希望該廣播接收者在app退出之後,依然能夠接收到系統廣播訊息,所以此處註冊系統的廣播接受者應該在Application類中完成。
代碼如下:

public class MyApplication extends Application {    private static MyApplication myApplication;    public MyApplication() {    }    public static MyApplication getInstance(){        if (myApplication == null) {            myApplication = new MyApplication();        }        return myApplication;    }    @Override    public void onCreate() {        super.onCreate();        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_TIME_TICK);        MyReceiver myReceiver = new MyReceiver();        registerReceiver(myReceiver, intentFilter);    }}

在接收到系統廣播的訊息之後,利用自訂的廣播接受者MyReceiver進行處理,在onReceive方法中檢測要啟動的Service類是否已經在後台運行,如果在後台運行,則不處理,如果沒有在後台運行,則啟動該服務。代碼如下:

public class MyReceiver extends BroadcastReceiver {    private final String TAG = MyReceiver.class.getSimpleName();    public MyReceiver() {    }    @Override    public void onReceive(Context context, Intent intent) {        if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {            Log.i(TAG, "監聽到開機啟動getAction");        }else if(intent.getAction().equals(Intent.ACTION_TIME_TICK)){            Log.i(TAG, "監聽到TIME_TICK");            boolean isServiceRunning = false;             ActivityManager manager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);             for (RunningServiceInfo service :manager.getRunningServices(Integer.MAX_VALUE)) {             if("com.yin.service.MyService".equals(service.service.getClassName()))                        //Service的全類名                 {                     isServiceRunning = true;                     Log.i(TAG, "已經啟動");                }             }             if (!isServiceRunning) {                 Intent i = new Intent(context, MyService.class);                 context.startService(i);                 Log.i(TAG, "沒有啟動,現在啟動");            }        }else {            Log.i(TAG, "監聽到其他");        }    }}

下面給出MyService類的代碼,該代碼並不完成什麼功能

public class MyService extends Service {    private final String TAG = MyService.class.getSimpleName();    public MyService() {    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        flags = START_STICKY;        //使用這樣的標誌因為該值會讓系統在該service停止之後在進行啟動,但是在清除記憶體之後是無效的        return super.onStartCommand(intent,flags,startId);    }    @Override    public void onCreate() {        super.onCreate();        Notification notification = new Notification();        startForeground(-1, notification);        Log.i(TAG, "Myservice類的oncreate方法");    }    @Override    public IBinder onBind(Intent intent) {        return null;    }    @Override    public void onDestroy() {        super.onDestroy();        Intent service = new Intent(this, MyService.class);        startService(service);//這裡是一個取巧的方法,在該service銷毀是在進行啟動,但是清楚該app記憶體之後依然不能起作用    }}

下面給出設定檔代碼:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.yin.servicetest"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="11"        android:targetSdkVersion="20" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme"        android:persistent="true"        android:name="com.yin.application.MyApplication" >        <activity            android:name=".MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <receiver             android:name="com.yin.servicetest.MyReceiver">        </receiver>        <service android:name="com.yin.service.MyService">        </service>    </application></manifest>

結果:

值得注意的是,雖然那可以達到後台啟動並執行目的,但是如果在使用者清楚記憶體之後這樣的方法就不起作用了。如果大家有誰知道QQ或者如何?在清楚記憶體之後如何?依然在後台運行進程和服務的,請不吝賜教!【握手】

源碼下載

android 實現後台服務及源碼下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.