简体   繁体   English

Android后台服务中的主题

[英]Threads in Background Service Android

Hi I am trying to use the service class for first time and have been facing problems. 嗨,我第一次尝试使用服务类,并一直面临问题。 What I want is an infinitely running (unless killed by Android System) service with an active Network connection. 我想要的是一个无限运行(除非被Android系统杀死)具有活动网络连接的服务。 I have written the code which works fine on Android 4.3 and 4.4 but the application crashes when I try running on Android 2.2. 我编写的代码在Android 4.3和4.4上工作正常但是当我尝试在Android 2.2上运行时应用程序崩溃了。 My code is as follows: 我的代码如下:

public class BackgroundMusicService extends Service {

private MediaPlayer mp;
private int id;

private static class BackgroundAsyncTaskClass extends AsyncTask<Void, Void, Void>{
    protected Void doInBackground(Void... params) {
        Log.v("Async","Async Called");

                    /*Network connection will be created here*/

        return null;
    }
}

private class ForThread implements Runnable{
    public void run() {
        while (true) {
            try {
                Log.v("ThreadSleeping","5 sec");
                BackgroundAsyncTaskClass task = new BackgroundAsyncTaskClass();
                task.execute();
                Thread.sleep(5000);
            } catch (InterruptedException e) {
            }finally{
                Log.v("Finally called","Finally called");
            }   
        }
    }
}

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

@Override
public void onCreate() {
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.v("onStartCommand Called","onStart Command Called");

    Thread t;
    ForThread ft = new ForThread();
    t = new Thread(ft);
    t.start();

    return START_NOT_STICKY;
}


@Override
public void onDestroy() {
    super.onDestroy();
    if(null != mp){
        mp.stop();
        mp.release();
        Log.v("Destroyed","onDestroy Called");
    }
}

public void onTaskRemoved(Intent rootIntent) {

    Intent restartServiceIntent = new Intent(getApplicationContext(),
            this.getClass());
    restartServiceIntent.setPackage(getPackageName());

    PendingIntent restartServicePendingIntent = PendingIntent.getService(
            getApplicationContext(), 1, restartServiceIntent,
            PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmService = (AlarmManager) getApplicationContext()
            .getSystemService(Context.ALARM_SERVICE);
    alarmService.set(AlarmManager.ELAPSED_REALTIME,
            SystemClock.elapsedRealtime() + 1000,
            restartServicePendingIntent);

    super.onTaskRemoved(rootIntent);
}

} }

and the exception thrown by Android 2.2 is as follows: Android 2.2抛出的异常如下:

04-28 09:51:41.435: W/dalvikvm(280): threadid=7: thread exiting with uncaught exception (group=0x4001d800)
04-28 09:51:41.435: E/AndroidRuntime(280): FATAL EXCEPTION: Thread-8
04-28 09:51:41.435: E/AndroidRuntime(280): java.lang.ExceptionInInitializerError
04-28 09:51:41.435: E/AndroidRuntime(280):  at com.example.backgroundservicedemo.BackgroundMusicService$ForThread.run(BackgroundMusicService.java:45)
04-28 09:51:41.435: E/AndroidRuntime(280):  at java.lang.Thread.run(Thread.java:1096)
04-28 09:51:41.435: E/AndroidRuntime(280): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
04-28 09:51:41.435: E/AndroidRuntime(280):  at android.os.Handler.<init>(Handler.java:121)
04-28 09:51:41.435: E/AndroidRuntime(280):  at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
04-28 09:51:41.435: E/AndroidRuntime(280):  at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
04-28 09:51:41.435: E/AndroidRuntime(280):  at android.os.AsyncTask.<clinit>(AsyncTask.java:152)

Also, when I try using handler.post(new Runnable(){.... run(){}....} The UI hangs up but the background thread continues running and exits after it becomes out of memory. 此外,当我尝试使用handler.post(new Runnable(){.... run(){} ....} UI挂断但后台线程继续运行并在内存不足后退出。

Another thing that I have doubts about is: When the application restarts, I want this active Service to stop, but how do I get a reference to this thread running in Background and how do I stop this? 我怀疑的另一件事是:当应用程序重新启动时,我希望此活动服务停止,但是如何获取对在Background中运行的此线程的引用以及如何阻止它? I would appreciate if anyone can redirect me to a suitable link/reference or could help me out with the code. 如果有人可以将我重定向到合适的链接/参考或者可以帮助我解决代码,我将不胜感激。 Thanks 谢谢

You have this inside a thread's run method 你在一个线程的run方法中有这个

 BackgroundAsyncTaskClass task = new BackgroundAsyncTaskClass();
 task.execute();

Threading rules from the docs 来自文档的线程规则

  1. The AsyncTask class must be loaded on the UI thread . 必须在UI线程上加载AsyncTask类 This is done automatically as of JELLY_BEAN. 这是从JELLY_BEAN开始自动完成的。

  2. The task instance must be created on the UI thread. 必须在UI线程上创建任务实例。 execute(Params...) must be invoked on the UI thread. 必须在UI线程上调用execute(Params ...)。

  3. Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually. 不要手动调用onPreExecute(),onPostExecute(Result),doInBackground(Params ...),onProgressUpdate(Progress ...)。

  4. The task can be executed only once (an exception will be thrown if a second execution is attempted.) 该任务只能执行一次(如果尝试第二次执行,则会抛出异常。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM