我在启动宽度上启动服务广播接收器:
public class Autostart extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent arg1) {
Intent intent = new Intent(context, MyService.class);
MyService.setContext(context);
context.startService(intent);
}
}
这有效,当我启动手机时,服务正在后台运行。 然后我想从我的GUI停止/启动/重启服务:
Intent intent = new Intent(MyService.getContext(), MyService.class);
getActivity().stopService(intent);
但它不会杀死任务。 我认为当Context相同时,这必须工作,所以我制作了一个静态内容持有者,但它不起作用。
请注意,我可以启动该服务,并从该代码轻松停止已启动的服务。
如何停止自动启动/后台服务?
答案 0 :(得分:1)
用于调用任何Android后台服务执行以下操作
首先添加create a fetch服务类然后调用它
public class FetchUnreadMailService extends Service {
private NotificationManager mNotificationManager;
private int SIMPLE_NOTFICATION_ID;
private Timer myTimer;
Session mySession;
int unread_count = 0;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
super.onCreate();
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
@Override
public void run() {
mySession = new Session();
if(mySession.getStatus()){
APIHelper api = new APIHelper();
unread_count = (Integer) api.getMailBoxNotification(mySession.getUserId());
}
if(unread_count>0){
mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent notifyIntent = new Intent(FetchUnreadMailService.this,MailBox.class);
Context context = getApplicationContext();
CharSequence contentTitle = "New Mail";
CharSequence contentText = "You Have ("+ unread_count +") unread mails";
PendingIntent intent = PendingIntent.getActivity(FetchUnreadMailService.this, 0,notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
final Notification notifyDetails = new Notification(R.drawable.youtube,"New Alert, Click Me!",System.currentTimeMillis());
notifyDetails.setLatestEventInfo(context, contentTitle, contentText, intent);
notifyDetails.flags= Notification.FLAG_AUTO_CANCEL;//for auto cancel notification
mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);
}
}
}, 0, 30000);
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show();
}
}
创建此类后,请通过以下
调用它startService(new Intent(Home.this,FetchUnreadMailService.class));
有关详细信息,请查看以下链接http://grabcodes.blogspot.com