Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/219.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 后台服务Android中的线程_Java_Android_Multithreading_Service_Android Asynctask - Fatal编程技术网

Java 后台服务Android中的线程

Java 后台服务Android中的线程,java,android,multithreading,service,android-asynctask,Java,Android,Multithreading,Service,Android Asynctask,嗨,我第一次尝试使用服务类,一直面临问题。我想要的是一个无限运行的(除非被安卓系统杀死)服务,并有一个活跃的网络连接。我已经编写了在安卓4.3和4.4上运行良好的代码,但当我尝试在安卓2.2上运行时,应用程序崩溃。我的代码如下: public class BackgroundMusicService extends Service { private MediaPlayer mp; private int id; private static class BackgroundAsyncTas

嗨,我第一次尝试使用服务类,一直面临问题。我想要的是一个无限运行的(除非被安卓系统杀死)服务,并有一个活跃的网络连接。我已经编写了在安卓4.3和4.4上运行良好的代码,但当我尝试在安卓2.2上运行时,应用程序崩溃。我的代码如下:

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);
}
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)
公共类背景音乐服务扩展服务{
私人媒体播放器;
私有int-id;
私有静态类BackgroundAsyncTaskClass扩展了AsyncTask{
受保护的Void doInBackground(Void…参数){
v(“异步”,“异步调用”);
/*将在此处创建网络连接*/
返回null;
}
}
私有类ForThread实现Runnable{
公开募捐{
while(true){
试一试{
日志v(“线程休眠”,“5秒”);
BackgroundAsyncTaskClass任务=新建BackgroundAsyncTaskClass();
task.execute();
睡眠(5000);
}捕捉(中断异常e){
}最后{
Log.v(“最终调用”、“最终调用”);
}   
}
}
}
@凌驾
公共IBinder onBind(意向){
返回null;
}
@凌驾
public void onCreate(){
super.onCreate();
}
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId){
v(“调用onStart命令”、“调用onStart命令”);
螺纹t;
ForThread ft=新的ForThread();
t=新螺纹(英尺);
t、 start();
返回开始时间不粘;
}
@凌驾
公共空间{
super.ondestory();
如果(null!=mp){
mp.stop();
mp.release();
Log.v(“已销毁”、“称为onDestroy”);
}
}
公共void onTaskRemoved(Intent rootIntent){
Intent restartServiceIntent=新意图(getApplicationContext(),
这个.getClass());
setPackage(getPackageName());
PendingEvent RestartServicePendingEvent=PendingEvent.getService(
getApplicationContext(),1,重新启动ServiceIntent,
悬挂式帐篷(一杆旗帜);
AlarmManager alarmService=(AlarmManager)getApplicationContext()
.getSystemService(Context.ALARM\u服务);
alarmService.set(AlarmManager.U实时、,
SystemClock.elapsedRealtime()+1000,
restartServicePendingIntent);
super.onTaskRemoved(rootIntent);
}
}

Android 2.2引发的异常如下:

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);
}
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)
04-28 09:51:41.435:W/dalvikvm(280):threadid=7:线程以未捕获异常退出(组=0x4001d800)
04-28 09:51:41.435:E/AndroidRuntime(280):致命异常:线程8
04-28 09:51:41.435:E/AndroidRuntime(280):java.lang.ExceptionInInitializeError
04-28 09:51:41.435:E/AndroidRuntime(280):在com.example.backgroundservicedemo.BackgroundMusicService$ForThread.run(BackgroundMusicService.java:45)
04-28 09:51:41.435:E/AndroidRuntime(280):在java.lang.Thread.run(Thread.java:1096)
04-28 09:51:41.435:E/AndroidRuntime(280):原因:java.lang.RuntimeException:无法在未调用Looper.prepare()的线程内创建处理程序
04-28 09:51:41.435:E/AndroidRuntime(280):在android.os.Handler.(Handler.java:121)
04-28 09:51:41.435:E/AndroidRuntime(280):位于android.os.AsyncTask$InternalHandler。(AsyncTask.java:421)
04-28 09:51:41.435:E/AndroidRuntime(280):位于android.os.AsyncTask$InternalHandler。(AsyncTask.java:421)
04-28 09:51:41.435:E/AndroidRuntime(280):在android.os.AsyncTask.(AsyncTask.java:152)
另外,当我尝试使用handler.post(new Runnable(){….run(){}….})时,UI会挂起,但后台线程会继续运行,并在内存不足后退出

另一件我怀疑的事情是:
当应用程序重新启动时,我希望此活动服务停止,但我如何获得对后台运行的此线程的引用,以及如何停止此操作?如果有人能将我重定向到合适的链接/引用,或者可以帮助我完成代码,我将不胜感激。谢谢您在线程的运行方法中提供了此功能

 BackgroundAsyncTaskClass task = new BackgroundAsyncTaskClass();
 task.execute();
文档中的线程规则

  • 必须在UI线程上加载AsyncTask类。这是从JELLY\u BEAN开始自动完成的

  • 必须在UI线程上创建任务实例。 必须在UI线程上调用execute(参数…)。

  • 不要手动调用onPreExecute()、onPostExecute(结果)、doInBackground(参数…)和onProgressUpdate(进度…)

  • 该任务只能执行一次(如果尝试第二次执行,将引发异常)


  • 这很好。阅读文档总是第一件事。但是它并没有解释为什么要执行()必须在UI线程上调用。@blackbelt right。将找到一个源代码来解释它。@blackbelt文档没有提供关于为什么部分的详细信息。如果您知道,请更新我的帖子。我正在检查源代码,我认为您甚至没有达到execute()。看起来异常来自
    new BackgroundAsyncTaskClass()
    。原因在堆栈跟踪中很清楚:类或其超类中的某些内容正在创建处理程序。很少有理由使用显式线程或
    Thread.sleep()
    在Android中。您通常可以使用适当的处理程序来替换它们。@kjkrum。看起来问题在于在后台线程中调用execute。但我无法回答为什么部分。