2017-09-25 98 views
-1

我打電話給IntentService上傳圖片api,在後臺運行,並將圖片上傳到服務器。如何上傳圖片,即使應用程序在Android中死亡

IntentService,onHandleEvent方法被調用並在後臺運行,我所瞭解的是IntentService會執行任務並調用stopSelf()方法。

在我的應用程序上傳時,當我殺了我的應用程序,上傳被終止,IntentService停止完成上傳任務。

我怎樣才能讓我的IntentService即使該應用程序被終止運行?

編輯1:我試着用粘性的服務,當我殺死服務重新啓動應用程序,並傳遞給onStartCommand方法意圖數據爲空

+0

使用粘滯服務 –

回答

0

你可以試試這個下面的代碼。首先你需要在清單文件中添加服務的性質

<service 
     android:name=".service.Service" 
     android:enabled="true" 
     android:icon="@drawable/ic_launcher" 
     android:isolatedProcess="true"> 

    </service> 

而且也是你的服務添加START_STICKY的。

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    return START_STICKY; 
} 
0

如在下面的步驟中提到保持運行所有的時間

1)在服務onStartCommand方法的返回START_STICKY的服務,您可以創建一個服務。

public int onStartCommand(Intent intent, int flags, int startId) { 
return START_STICKY; 
} 

2)使用startService(則將MyService),使其始終保持活躍,無論綁定的客戶端的數量在後臺啓動該服務。

Intent intent = new Intent(this, PowerMeterService.class); 
startService(intent); 

3)創建活頁夾。

public class MyBinder extends Binder { 
public MyService getService() { 
     return MyService.this; 
} 
} 

4)定義一個服務連接。

private ServiceConnection m_serviceConnection = new ServiceConnection() { 
public void onServiceConnected(ComponentName className, IBinder service) { 
     m_service = ((MyService.MyBinder)service).getService(); 
} 

public void onServiceDisconnected(ComponentName className) { 
     m_service = null; 
} 
}; 

5)使用bindService綁定到服務。

Intent intent = new Intent(this, MyService.class); 
bindService(intent, m_serviceConnection, BIND_AUTO_CREATE); 
+0

開始粘滯,它會發送意圖數據服務一旦我殺了應用程序?它將如何重新啓動服務? – Praneeth

相關問題