Android后台服务及自动运行

1、修改AndroidManifest.xml文件

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<application ...>
        <service
            android:name="com.neohope.android.service.NService"
            android:enabled="true"
            android:exported="true" >
        </service>

        <receiver android:name="com.neohope.android.receiver.NBroadcastReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
</application>

2、新增服务类

package com.neohope.android.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;

public class NService extends Service {

    public NService() {
        
    }

    @Override
    public void onCreate() {
        mainThread = new WorkThread ();
        mainThread.start();
    }

    @Override
    public void onDestroy() {
        mainThread.bEnd = true;
    }

    class WorkThread extends Thread
    {
        private int nInterval = 1000*60;
        private boolean bEnd = false;

        public JsonReaderThread()
        {
        }

        @Override
        public void run()
        {
            while(!bEnd)
            {
                DoSomething();

                try {
                    Thread.sleep(nInterval);
                } catch (InterruptedException e) {
                    Log.w("", "");
                }
            }
        }

        private void DoSomething()
        {
        }

}

3、新增广播处理类

package com.neohope.android.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.neohope.android.service.NService;

public class NBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent startServiceIntent = new Intent(context, NService.class);
        context.startService(startServiceIntent);
    }
}

4、在Activity中添加启动代码

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

    public void doStartService() {
        Context context = getApplicationContext();
        Intent startServiceIntent = new Intent(context, NService.class);
        context.startService(startServiceIntent);
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

*