[英]How to show nottification when (andorid) home button is pressed (background)
我有在每個Chrono.change中發送通知的應用程序(目前用於測試)。 我在開發該功能的MainActivity上運行時效果很好。 但是它不能用於任何其他活動或按HOME鍵時。 如果按下電源按鈕,則應用程序將在后台運行,並且可以正常運行(如果在MainActivity上按下電源按鈕)。
任何想法如何解決這兩個問題:
1)如果我在其他活動上也發送通知
2)更重要-即使按下HOME按鈕並且當前不在應用程序中,也會發送通知。
eventL istener:
stopWatch.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
@Override
public void onChronometerTick(Chronometer chronometer) {
turnedOnOff = prefs.getBoolean("notification",false);
if (turnedOnOff)
throwNotification();
}
});
通知:
public void throwNotification()
{
// Prepare intent which is triggered if the
// notification is selected
Intent intent = new Intent(this, MainActivity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
intent, 0);
// Build notification
// Actions are just fake
Notification noti = new Notification.Builder(this)
.setContentTitle("Finish!")
.setContentText("Its done").setSmallIcon(R.mipmap.notif)
.setContentIntent(pendingIntent)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// hide the notification after its selected
noti.flags |= Notification.FLAG_AUTO_CANCEL;
noti.defaults |= Notification.DEFAULT_SOUND;
noti.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, noti);
}
謝謝你!
@Raghunandan的回答
這不可能。
除非您將應用設為主屏幕,否則無法攔截Android上的主屏幕按鈕。 這是出於安全原因,因此惡意應用無法通過覆蓋所有可以退出的按鈕來接管您的設備。
如果要處理HOME按鈕,請實現主屏幕。
但我建議您重新考慮您的設計。 將注銷選項留給用戶。
http://developer.android.com/training/design-navigation/index.html
查看gmail應用。 當您按下主頁按鈕時,它不會注銷。
@Override
protected void onUserLeaveHint()
{
super.onUserLeaveHint();
Toast.makeText(this, "You pressed the home button!", Toast.LENGTH_LONG).show();
Log.i("Home button Pressed!", "Yes");
finish();
}
您可以使用onUserLeaveHint
受保護的void onUserLeaveHint()
在API級別3中添加
當活動由於用戶選擇而要進入后台時,稱為活動生命周期的一部分。 例如,當用戶按下Home鍵時,將調用onUserLeaveHint(),但是當來電導致通話中的Activity自動進入前台時,不會在活動中斷時調用onUserLeaveHint() 。 如果被調用,則在活動的onPause()回調之前立即調用此方法。
該回調和onUserInteraction()旨在幫助活動智能地管理狀態欄通知。 具體來說,是為了幫助活動確定取消通知的適當時間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.