我正在尋找執行簡單任務的最有效方法。作爲一名新的android開發人員,我不太清楚哪些策略對於我的應用程序在內存效率方面最適合。我想象其中的一些方法可能會導致我不知道的線程問題。Sleep VS alarmManager.set VS alarmManager.setRepeat VS Handler
所有這三種解決方案當前的行爲都符合要求。
這是一個非常簡單的應用程序。這個想法是,我的MainActivity啓動一個IntentService,它將在應用程序打開後在後臺運行。我現在需要的所有功能都是爲了在一天中以相隔一小時的間隔隨機創建通知,無限期地進行,直到用戶停止。該通知以簡單的無效方法進行,將通知顯示爲文字並振動手機一次。
我的MainActivity啓動IntentService:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, NotificationService.class);
startService(intent);
}
}
我IntentService是非常簡單的。它被稱爲NotificationService,擴展了IntentService,並且只覆蓋了onHandleIntent方法。除了super(「Service」)之外,構造函數是空的。問題在於如何使通知以最有效的方式在後臺全天彈出。在我的實現中,這三個方法都是在onHandleIntent方法中完成的。
方法一:
@Override
protected void onHandleIntent(Intent intent) {
makeNotification();
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
PendingIntent pintent = PendingIntent.getService(
getApplicationContext(), 0, intent, 0);
alarm.cancel(pintent);
alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()
+ 60000 * 60, pintent);
}
注意這一點,用戶必須卸載該應用獲取通知停下來,這是不可取的(雖然我覺得我可以只添加一個按鈕什麼的將取消的意圖)
方法二:
protected void onHandleIntent(Intent intent) {
makeNotification();
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
PendingIntent pintent = PendingIntent.getService(
getApplicationContext(), 0, intent, 0);
alarm.cancel(pintent);
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()
+ 60*1000, 60000*60 ,pintent);
}
方法三:
@Override
protected void onHandleIntent(Intent intent) {
makeNotification();
try {
sleep(60000 * 60);
startService(intent);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
有人可以幫我決定這三種方法的優缺點嗎?我不知道我理解哪一個是理想的,儘管他們三個都給了我適當的功能。作爲一個側面說明,在我的研究中,我注意到了一個「Handler」類,它在這裏也可能很有用。
感謝您澄清我使用IntentService的可憐的措辭,並且還提供了一些關於setRepeating/set的正確用法的進一步見解。這非常有幫助! – Jaked222