我通过固定时间间隔使用服务来发出通知。为了启用通知,我放了复选框。问题是,如果我退出应用程序,则不会保存复选框状态。如果我已选中复选框并退出应用程序,那么如果我重新打开它,则取消选中复选框状态,因此服务将被销毁。请帮助我... Thanx提前...
Alert_notifications.java
public class Alert_notifications extends Activity {
CheckBox enablecheck;
/** Called when the activity is first created. */
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alert_notifications);
getActionBar().setDisplayHomeAsUpEnabled(true);
enablecheck = (CheckBox)findViewById(R.id.checkBox1);
enablecheck.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
if(enablecheck.isChecked()){
// TODO Auto-generated method stub
Intent intent = new Intent(Alert_notifications.this, com.example.gpstracking.NotifyService.class);
Alert_notifications.this.startService(intent);
}
else
{
stopService(new Intent(Alert_notifications.this, NotifyService.class));
}
}
});
}
NotifyService.java (service)
public class NotifyService extends Service {
NotifyServiceReceiver notifyServiceReceiver;
final static String ACTION = "NotifyServiceAction";
final static String STOP_SERVICE = "";
final static int RQS_STOP_SERVICE = 1;
private static final String url_Weather_details1="http://128.251.238.238/Weatherforecast1/";
private static final String TAG_SUCCESS = "success";
private static Timer timer = new Timer();
private Context ctx;
private static final int MY_NOTIFICATION_ID = 1;
private NotificationManager notificationManager;
private Notification myNotification;
// constant
public static final long NOTIFY_INTERVAL = 10 * 1000; // 10 seconds
// run on another Thread to avoid crash
private Handler mHandler = new Handler();
// timer handling
private Timer mTimer = null;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
// cancel if already existed
if(mTimer != null) {
mTimer.cancel();
} else {
// recreate new
mTimer = new Timer();
}
// schedule task
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
}
class TimeDisplayTimerTask extends TimerTask {
@Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
@Override
public void run() {
if(isNetworkAvailable())
{
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
JSONParser jsonParser = new JSONParser();
params.add(new BasicNameValuePair("LAT", "LAT"));
params.add(new BasicNameValuePair("LONGITUDE", "LONG"));
Log.d("params", params.toString());
// getting weather details by making HTTP request
// Note that weather details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(url_Weather_details1,
"GET", params);
// check your log for json response
Log.d("Weather Details", json.toString());
// json success tag
int success = 0;
try {
success = json.getInt(TAG_SUCCESS);
System.out.println("success"+success);
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (success == 2) {
// successfully received weather details
// TODO Auto-generated method stub
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ACTION);
registerReceiver(notifyServiceReceiver, intentFilter);
// Send Notification
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
myNotification = new Notification(R.drawable.heavy_rain,"Heavy rain", System.currentTimeMillis());
Context context = getApplicationContext();
String notificationTitle = "Heavy Rain!";
String notificationText = "";
Intent myIntent=new Intent(context, Alert_activity.class);
//Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myBlog));
PendingIntent pendingIntent = PendingIntent.getActivity(
getBaseContext(), 0, myIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
myNotification.defaults |= Notification.DEFAULT_SOUND;
myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
myNotification.setLatestEventInfo(context, notificationTitle,
notificationText, pendingIntent);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
}
}
}
});
}
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public void onDestroy(){
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
notificationManager.cancel(MY_NOTIFICATION_ID);
super.onDestroy();
}
}
答案 0 :(得分:1)
问题是,如果我从应用程序退出复选框 状态未保存
使用SharedPreferences存储复选框状态,当用户关闭启动应用程序时,从“首选项”获取状态以设置复选框状态。
请参阅以下示例如何使用SharedPreferences: