[英]Calling an Activity from a Service
我有一個包含服務方法的警報服務的服務類。 激活警報服務時會調用這些方法。 我想要做的是在服務類中調用這些方法之一(當警報響起時)調用另一個類的意圖。 它只是在調用intent時標記錯誤。 這僅發生在激活警報服務時調用的方法(服務類中的方法)。 這是因為該類extends Service
而不extends Activity
嗎? 我不確定,還有什么想法?
(下面是我的服務類,當在onStart
方法中調用另一個活動的意圖時,app force關閉。)
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-24 01:11:36.857:E / AndroidRuntime(10805):java.lang.RuntimeException:無法使用Intent {flg = 0x4 cmp = com.exercise.AndroidAlarmService /啟動服務com.exercise.AndroidAlarmService.MyAlarmService@412f23f8。 MyAlarmService(有附加內容)}:android.util.AndroidRuntimeException:從Activity上下文外部調用startActivity()需要FLAG_ACTIVITY_NEW_TASK標志。 這真的是你想要的嗎?
您是否嘗試過錯誤日志建議的內容?
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
您可以使用服務的onStart()
來調用Activity .....
@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);
...
}
你可以通過啟用其他人建議的標志來實現。 默認情況下阻止它的原因是因為服務很容易在后台由系統自動重啟。 如果您在onStart服務期間啟動活動,則無論用戶執行什么操作,此活動都會啟動。 這將是糟糕的用戶體驗。 請記住這個警告,並為此方案解決。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.