[英]android app does not respond after start service
我想創建一個android服務,它將使用json檢查我的網站中是否有新項目:),所以我的第一步是測試服務是否會很好:)我這樣創建了我的服務
public class NotifyService extends Service {
public static boolean ServiceIsRun=false;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int i = 1;
while (ServiceIsRun){
i++;
Log.i("broadService","hello from Service"+i);
try{
Thread.sleep(20000);
}catch (Exception e){
}
}
return START_STICKY;
}
}
和我的接收器:
public class NotifyBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
if (intent.getAction().equalsIgnoreCase("com.latestBabiaNews")){
Log.i("broadReceiver","hello from Broadcast");
}
}
}
ps:我在我的fragmenet中有asynctask,可以從服務器加載數據,並且我這樣調用服務(在onPostExecute()中
if(NotifyService.ServiceIsRun==false){
NotifyService.ServiceIsRun=true;
Intent intent = new Intent(getContext(),NotifyService.class);
getActivity().startService(intent);
}
..我的xml清單:
<service
android:name=".NotifyService">
</service>
<receiver android:name=".NotifyBroadcast">
<intent-filter>
<action android:name="com.latestBabiaNews">
</action>
</intent-filter>
另外,當我使用IntentService時,它對我來說很好,但是使用Service時,不是嗎? multiThreading問題還是什么?
服務與應用程序的其余部分在同一線程中運行。 如果阻止該服務,則將阻止整個應用程序。
如果要執行阻止操作,請在服務器中啟動一個新線程。 只要確保您正確地執行了此操作即可(例如,在服務的生命周期中onStartCommand
可能會多次調用)。
另外,您可以對其進行設置,以便您的服務異步執行所有操作並且不會阻塞。 是否更容易,取決於服務最終會做什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.