gpt4 book ai didi

java - Android 后台服务中的线程

转载 作者:行者123 更新时间:2023-12-02 05:53:23 25 4
gpt4 key购买 nike

您好,我第一次尝试使用服务类,但遇到了问题。我想要的是一个具有 Activity 网络连接的无限运行(除非被 Android 系统杀死)的服务。我编写的代码在 Android 4.3 和 4.4 上运行良好,但当我尝试在 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);
}

}

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)

此外,当我尝试使用 handler.post(new Runnable(){.... run(){}....} UI 挂起但后台线程继续运行并在内存不足后退出.

我还有一个疑问是:当应用程序重新启动时,我希望停止此 Activity 服务,但如何获取对此在后台运行的线程的引用以及如何停止它?如果有人可以将我重定向到合适的链接/引用或可以帮助我解决代码,我将不胜感激。谢谢

最佳答案

你可以在线程的 run 方法中使用它

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

文档中的线程规则

  1. AsyncTask 类必须在 UI 线程上加载。从 JELLY_BEAN 开始,这是自动完成的。

  2. 任务实例必须在 UI 线程上创建。必须在 UI 线程上调用execute(Params...)。

  3. 不要手动调用 onPreExecute()、onPostExecute(Result)、doInBackground(Params...)、onProgressUpdate(Progress...)。

  4. 该任务只能执行一次(如果尝试第二次执行,则会抛出异常。)

关于java - Android 后台服务中的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23338203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com