
在按钮上单击我创建新线程然后启动服务.
Thread t = new Thread(){ public voID run(){ mIntent= new Intent(MainActivity.this,ConnectonService.class); mIntent.putExtra("KEY1","Value used by the service"); context.startService(mIntent); } };t.start(); 然后在服务上,我尝试打开套接字并与服务器连接
@OverrIDepublic int onStartCommand(Intent intent,int flags,int startID) { //Todo do something useful try { InetAddress serverAddr = InetAddress.getByname(SERVER_IP); socket = new Socket(serverAddr,SERVERPORT); Scanner scanner = new Scanner(socket.getinputStream()); message = scanner.nextline(); } catch (IOException e) { e.printstacktrace(); } return Service.START_NOT_STICKY;} 但是当我打电话给我时,我有错误
08-30 08:56:49.268: E/AndroIDRuntime(3751): java.lang.RuntimeException: Unable to start service com.example.testofconnection.ConnectonService@40ef02a8 with Intent { cmp=com.example.testofconnection/.ConnectonService (has extras) }: androID.os.networkonmainthreadException* 我认为问题是服务在主线程上,但是我找不到如何在新的(独立)线程上启动服务以保持连接活动?
解决方法 您可以使用IntentService.只需使用主线程中的Intent正常启动它. onHandleIntent()方法在后台线程中执行.把你的套接字代码放在那里.这是一个示例代码.public class MyIntentService extends IntentService { public MyIntentService() { super("MyIntentService"); } @OverrIDe protected voID onHandleIntent(Intent intent) { // this method is called in background thread } @OverrIDe public IBinder onBind(Intent intent) { return null; }} 在您的活动中,您将按以下方式启动服务.
startService(new Intent(this,MyIntentService.class));
如果您需要持久的服务,您可以创建一个正常的服务并在那里启动一个线程.这是一个例子.确保将其作为“前台”服务启动.这将使服务运行更长时间而不会被AndroID杀死.
public class MyAsyncService extends Service { private Runnable runnable = new Runnable() { @OverrIDe public voID run() { while(true) { // put your socket-code here ... } } } @OverrIDe public voID onCreate() { // start new thread and you your work there new Thread(runnable).start(); // prepare a notification for user and start service foreground Notification notification = ... // this will ensure your service won't be killed by AndroID startForeground(R.ID.notification,notification); }} 总结 以上是内存溢出为你收集整理的android – 如何在主线程上运行服务?全部内容,希望文章能够帮你解决android – 如何在主线程上运行服务?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)