0
我正在編寫一個應用程序,其中包含一個PrePreceActivity,其中包含一個SwitchPreference,用於在用戶打開或關閉它時啓動或停止服務,並保存切換到SharedPreference的狀態。 然後在MainActivity中我註冊了一個SharedPreferenceChangeListener,它讀取交換機的狀態,然後根據它啓動或停止服務。如何在後臺運行服務並由SharedPreferences管理設置
// This is the code in MainATY:
preferences= getPreferences(Activity.MODE_PRIVATE);
editor= preferences.edit();
preferences.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
boolean pushNotification= sharedPreferences.getBoolean(MyPreferences.pushNotificationKey,true);
if (pushNotification)
{
if (!NotificationService.isRunning){
Intent i = new Intent(MainActivity.this, NotificationService.class);
bindService(i,MainActivity.this,Context.BIND_AUTO_CREATE);
}
}
else{
if (NotificationService.isRunning){
unbindService(MainActivity.this);
}
}
}
});
,這是PreferenceATY代碼:
pushNotification.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
pushNotification= (SwitchPreference) preference;
editor.putBoolean(pushNotificationKey,pushNotification.isChecked());
if (!editor.commit())
{
Toast.makeText(MyPreferences.this, R.string.changes_saved,Toast.LENGTH_SHORT).show();
}
return true;
}
});
但它不工作,你能幫幫我嗎? 最後一件事,我如何使用多行內容做出通知? 這是我的通知功能:
String thingsToDo=new String();
while (c.moveToNext())
{
thingsToDo+=String.format("%s: %s: %s "
,c.getString(c.getColumnIndex("subject"))
,c.getString(c.getColumnIndex("typeOfEvent"))
,c.getString(c.getColumnIndex("what"))
);
thingsToDo+="/n";
}
thingsToDo.substring(0,4);
NotificationCompat.Builder mBuilder=new NotificationCompat.Builder(MainActivity.this)
.setSmallIcon(R.drawable.small_icon_diary)
.setContentTitle(getString(R.string.homework_for_tomorrow))
.setContentText(thingsToDo);
mBuilder.setShowWhen(true);
Intent i= new Intent(MainActivity.this,NotificationViewActivity.class);
Bundle b= new Bundle();
b.putString("time",time);
i.putExtra("b",b);
i.putExtra("time",time);
mBuilder.addAction(R.drawable.small_icon_diary,"Open",PendingIntent.getActivity(MainActivity.this,0,i,0));