我想在特定事件發生時打開一個屏幕,而不管我現在在哪個屏幕上,我該怎麼做?Android:從任何屏幕開始意向
Intent Iatualizar = new Intent(this, Atualizar.class);
startActivity(Iatualizar);
上面的代碼工程,如果我與屏幕打開程序,但沒有工作,當屏幕在後臺。如何使它工作?謝謝
我想在特定事件發生時打開一個屏幕,而不管我現在在哪個屏幕上,我該怎麼做?Android:從任何屏幕開始意向
Intent Iatualizar = new Intent(this, Atualizar.class);
startActivity(Iatualizar);
上面的代碼工程,如果我與屏幕打開程序,但沒有工作,當屏幕在後臺。如何使它工作?謝謝
將FLAG_ACTIVITY_NEW_TASK添加到您的意圖。如果你檢查日誌貓,它也會告訴你這一點。
試試這個,你也可以使用下面
Intent Iatualizar = new Intent(this, Atualizar.class);
Iatualizar.addFlags(FLAG_ACTIVITY_NEW_TASK);
startActivity(Iatualizar);
的代碼你應該只創建加載你的活動時,該事件發生時一個服務啓動服務。
爲此,您可以在加載應用程序時啓動該服務,並將您的事件接收器放入服務類中。這樣,即使其他應用程序正在運行且您的應用程序不在前臺(顯示在屏幕上),您仍然可以觸發該事件。
如果Android垃圾收集器不在前臺並且開始資源不足,Android垃圾收集器將嘗試關閉您的活動。
如果您想更進一步,使服務成爲前臺服務,那麼理論上它將是Android在內存不足時最終殺死的最後一件事。讓我知道你是否需要一個代碼示例。
希望這可以幫助你! 乾杯
- 編輯 -
下面是一個代碼示例,讓您開始。
在您的活動onCreate調用一些類似於您上面啓動您的服務的代碼。 即:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent IatualizarService = new Intent(this, AtualizarService.class);
startService(Iatualizar);
}
如果你願意,也可以有這樣的在你的onResume,(或從一個按鈕來啓動它,或者無論你想啓動此服務)。
然後創建一個服務類,像這樣:
public class AtualizarService extends Service {
private final IBinder mBinder = new MyBinder();
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public void onCreate() {
// In here you can make your service a foreground service to help prevent garbage collection from occurring.
makeforeground();
}
private boolean makeforeground() {
String msg = "Turning on foreground service";
ErrorLog.i(getApplicationContext(), TAG, msg);
try {
Notification notification = new Notification(
R.drawable.ic_dialog_info,
getText(R.string.notification_text),
System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent activityIntent = new Intent(this, YourMainActivity.class);
activityIntent.setAction(Intent.ACTION_MAIN);
activityIntent.addCategory(Intent.CATEGORY_LAUNCHER);
activityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
activityIntent, 0);
notification.setLatestEventInfo(this,
getText(R.string.notification_title),
getText(R.string.notification_text), pendingIntent);
startForeground(1234567890, notification); // random id
return true;
} catch (Exception e) {
String error = "displayNotification Error Message: "
+ e.getMessage() + " Cause: " + e.getCause();
ErrorLog.e(GlobalParameters.getContext(),
TAG + " Notification Foreground Service", error);
return false;
}
}
@Override
public void onDestroy() {
}
@Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
public class MyBinder extends Binder {
AtualizarService getService() {
return AtualizarService .this;
}
}
}
然後,此服務類中,您可以在可以在任何你想要的事件觸發廣播接收器添加。然後加載你的活動,如果你想要。
乾杯
我是初學者,你能舉個例子嗎?謝謝! –
Add:'Iactualizer.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);' – xandy
即使添加我提供的代碼仍然無效,有什麼想法? –