2016-08-29 51 views
1

創建服務,並從MainActivity.class與放串額外給意圖調用,但是當我在onStartCommand稱之爲getStringExtra,它返回NullPointerException異常獲取意圖的服務回報NullPointerException異常

這裏是我的代碼:

MainService.class:

public class MainService extends Service { 
private WindowManager wm; 
private WindowManager.LayoutParams params; 
@Override 
public IBinder onBind(Intent i) {  
    return null; 
} 
@Override 
public void onCreate() { 
    super.onCreate();  
} 
@Override 
public void onDestroy() { 
    super.onDestroy(); 
    if (mView != null) { 
     WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE); 
     wm.removeView(mView); 
    } 
} 
@Override 
public void onStart(Intent intent, int startId) { 
    super.onStart(intent, startId);  
} 
@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    final String quote = intent.getStringExtra("quote"); 
    Log.d("datastring",quote); 
    return super.onStartCommand(intent, flags, startId); 
} 
} 

在MainActivity.class我叫:

Intent i=new Intent(MainActivity.this, MainService.class); 
i.putExtra("quote", "dataquote"); 
stopService(i); 

如何從MainActivity獲取字符串在MainService中?

+0

我們無法從'stopService'獲取'intent'。這也被問過昨天,在這裏檢查:http://stackoverflow.com/questions/39191968/get-intent-passed-to-stopserviceintent-in-service/39192026#39192026 – Shaishav

+0

@Shaishav我如何能得到意圖在服務? –

+0

您是否嘗試在'MainActivity.class'中使用'startService(i)',而不是'stopService(i)'? –

回答

0

如果你想提供更多的數據,你Service你需要使用類似:

Intent intent = new Intent(MainActivity.this, MainService.class); 
intent.putExtra("quote", "dataquote"); 
startService(intent); 

這將啓動該服務,你應該能夠得到在onStartCommand()數據intent。如果Service已在運行,則onStartCommand()仍將與新的intent一起調用。這是因爲Service組件本質上是單身的,所以一次只能運行一個特定服務的實例。

就你而言,你通過stopService(intent)提供數據。不僅不可能得到這,您的Service也將停止此聲明後,因此,即使您可以讀取它,你也不能真正做太多的數據。

如果您仍然需要停止Service並同時傳遞數據,您應該檢查this post

相關問題