android crash后服务会停止吗,活动崩溃后android停止后台服务

一开始,我想为糟糕的英语道歉.

有我的问题:

我在android中有一个服务,它在活动运行时在后台运行. (此服务使用指定的时间间隔与服务器同步用户数据).

public class CService extends Service

{

private Boolean isDestroyed;

@Override

public int onStartCommand (Intent intent, int flags, int startId)

{

if (intent != null)

{

new Thread(new Runnable()

{

//run new thread to disable flush memory for android and destroy this service

@Override

public void run ()

{

this.isDestroyed = Boolean.FALSE

while(!this.isDestroyed)

{

//loop until service isn't destroyed

}

}

}).start();

}

return Service.START_NOT_STICKY;

}

@Override

public void onDestroy ()

{

//THIS ISNT CALLED FROM uncaughtException IN ACTIVITY BUT from onDestroy method is this called.

//when is service destroyed then onDestroy is called and loop finish

this.isDestroyed = Boolean.TRUE;

}

}

并且是从onCreateMethod中的活动开始的.此活动实现Thread.UncaughtExceptionHandler并在onCreate方法中注册以捕获活动中的所有意外异常.当活动中的某些东西抛出异常方法时,会调用uncaughtException,并且服务应该以stopService(serviceIntent)停止;但onDestoy在服务中没有被调用.但是当调用的活动中的onDestroy方法(用户按下然后返回按钮)服务成功停止并且调用CService中的onDestoroy时.

public class CActivity extends Activity implements Thread.UncaughtExceptionHandler

{

private Thread.UncaughtExceptionHandler defaultUEH;

@Override

protected void onCreate (Bundle savedInstanceState)

{

this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();

// create intent for service

Intent serviceIntent = new Intent(this, CService.class);

// run service

startService(serviceIntent);

//set default handler when application crash

Thread.setDefaultUncaughtExceptionHandler(this);

super.onCreate(savedInstanceState);

}

@Override

public void uncaughtException (Thread thread, Throwable ex)

{

//THIS DOESN'T WORK

//when global exception in activity is throws then this method is called.

Intent serviceIntent = new Intent(this, CService.class);

//method to service stop is called. BUT THIS METHOD DON'T CALL onDestroy in CService

stopService(serviceIntent);

defaultUEH.uncaughtException(thread, ex);

}

@Override

public void onDestroy ()

{

//this work fine

Intent serviceIntent = new Intent(this, CService.class);

stopService(serviceIntent);

super.onDestroy();

}

}

活动崩溃时我需要停止后台服务.当android关闭活动并在堆栈中启动先前的活动(即登录屏幕)时,没有用户现在被记录.

谢谢你的建议.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值