2012-06-24 38 views
0

我有一個包含服務方法的警報服務的服務類。這些方法在警報服務激活時被調用。我想要做的是在服務類中調用的其中一個方法中調用另一個類的意圖(當鬧鐘響起時)。它所做的只是在調用意圖時標記錯誤。這隻發生在警報服務被激活時調用的方法中(服務類中的方法)。這是因爲類extends Service而不是extends Activity?我不確定,任何ides?從服務中調用活動

(下面是我的服務類,當意圖另一個活動是所謂的onStart方法的應用強行關閉。)

public class MyAlarmService extends Service { 
    @Override 
    public void onCreate() { 
     // TODO Auto-generated method stub 
     Toast.makeText(this, "MyAlarmService.onCreate()", Toast.LENGTH_LONG).show(); 
    } 

    @Override 
    public IBinder onBind(Intent intent) { 
     // TODO Auto-generated method stub 
     Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show(); 
     return null; 
    } 

    @Override 
    public void onDestroy() { 
     // TODO Auto-generated method stub 
     super.onDestroy(); 
     Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG).show(); 
    } 

    @Override 
    public void onStart(Intent intent, int startId) { 
     // TODO Auto-generated method stub 
     super.onStart(intent, startId); 

     Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show(); 

     ////////////////////////////////////////////////////////////////////////////////// 

     Intent i = new Intent("com.exercise.AndroidAlarmService.HELLO"); 
     startActivity(i); 

     The intent that is send to open another class, an activity. 
     ** 

     ///////////////////////////////////////////////////////////////////////////////// 
    } 

    @Override 
    public boolean onUnbind(Intent intent) { 
     // TODO Auto-generated method stub 
     Toast.makeText(this, "MyAlarmService.onUnbind()", Toast.LENGTH_LONG).show(); 
     return super.onUnbind(intent); 
    } 
} 

一個在logcat的這些錯誤是:

06:01:11:36.857:E/AndroidRuntime(10805):java.lang.RuntimeException:無法啓動服務[email protected] Intent {flg = 0x4 cmp = com.exercise.AndroidAlarmService/.MyAlarmService(有額外)}:android.util.AndroidRuntimeException:調用startActi來自Activity上下文之外的vity()需要FLAG_ACTIVITY_NEW_TASK標誌。這真的是你想要的嗎?

回答

2

您是否嘗試過錯誤日誌的建議?

i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
0

你可以叫使用您的服務的onStart()的活動.....

@Override 
public void onStart(Intent intent, int startId) { 
    ... 
    Log.i("Service", "onStart() is called"); 
    Intent callIntent = new Intent(Intent.ACTION_CALL); 
    callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    callIntent.setClass(<Set your package name and class name here>); 
    startActivity(callIntent); 
    ... 

} 
0

您可以通過啓用標誌被別人的建議去做。它被默認阻止的原因是因爲服務在後臺容易被系統自動重啓。如果您在服務的onStart期間開始活動,則無論用戶在做什麼,該活動都會啓動。這將是不好的用戶體驗。請記住這個警告,併爲此情況解決。