无法销毁 android 中的服务
Unable to destroy service in android
在我的应用程序中,我根据服务器响应给出了大雨通知。但我无法破坏服务并停止 notifications.I 已停止取消选中复选框的通知。在我的代码中调用 onDestroy 方法并显示 toast 消息但服务没有停止。我怎样才能做到这一点。提前致谢
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();
}
}
In my code onDestroy method is called and toast message is displayed but service is not stopped
是的,是的。 没有停止的是你的Timer
和TimerTask
。 你 开始了——你 需要在 onDestroy()
中停止它,可能是通过在 [=10] 上调用 cancel()
=].
在我的应用程序中,我根据服务器响应给出了大雨通知。但我无法破坏服务并停止 notifications.I 已停止取消选中复选框的通知。在我的代码中调用 onDestroy 方法并显示 toast 消息但服务没有停止。我怎样才能做到这一点。提前致谢
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();
}
}
In my code onDestroy method is called and toast message is displayed but service is not stopped
是的,是的。 没有停止的是你的Timer
和TimerTask
。 你 开始了——你 需要在 onDestroy()
中停止它,可能是通过在 [=10] 上调用 cancel()
=].