Я столкнулся с той же проблемой и решил после прочтения документации, дюжины переполнений стека и сообщений в блогах. Я создал фоновый сервис и сделал его передним планом, чтобы предотвратить его перезапуск, если приложение (процесс) закрыто или открыто - для предотвращения потери данных из службы. но опять же было произведено постоянное уведомление, которое было нецелесообразным (я его ненавидел). Я хотел удалить это уведомление вместе с запущенным сервисом. затем начал заниматься серфингом при обновлении уведомления, и там я нашел вопрос, который был направлен мне на документацию об обновлении уведомления. Я читал это и обновлял уведомление об обслуживании переднего плана и вола, это работало как шарм. Я даю полный код здесь.
Основная деятельность
public class MainActivity extends AppCompatActivity {
TextView textView;
Context context = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.time);
Intent background = new Intent(context,TimeBroadCast.class);
context.startService(background);
LocalBroadcastManager.getInstance(this).registerReceiver(
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int message = intent.getIntExtra(UpdatTime.timUpdate,0);
textView.setText(String.valueOf(message));
}
}, new IntentFilter(UpdatTime.ACTION_LOCATION_BROADCAST)
);
}
}
Класс обслуживания
public class TimeBroadCast extends Service {
private boolean isRunning;
private Context context;
UpdatTime updatTime;
Timer timer;
@Override
public void onCreate() {
this.context = this;
this.isRunning = false;
timer = new Timer();
updatTime = new UpdatTime(this);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
StartForground();
Notification notification = new NotificationCompat.Builder(this).build();
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns);
nMgr.notify(101,notification);
nMgr.cancel(101);
return START_STICKY;
}
@Override
public void onDestroy() {
StopForgroudn();
super.onDestroy();
}
private void StartForground() {
if(!isRunning) {
isRunning = true;
timer.schedule(updatTime, 0, 1000);
}
Notification notification = new NotificationCompat.Builder(this)
.setOngoing(false)
.setSmallIcon(android.R.color.transparent)
.build();
startForeground(101, notification);
}
private void StopForgroudn()
{
timer.cancel(); // Terminates this timer, discarding any currently scheduled tasks.
timer.purge(); // Removes all cancelled tasks from this timer's task queue.
stopForeground(true);
stopSelf();
}
}
TimerTaks класс
public class UpdatTime extends TimerTask {
static String timUpdate = "timecountdown", ACTION_LOCATION_BROADCAST = TimeBroadCast.class.getName() + "TimeBroadCast";
Context myContext;
int i = 0;
public UpdatTime(Context myContext) {
this.myContext = myContext;
}
@Override
public synchronized void run() {
try {
i += 1;
Log.v("Data1", ""+i);
Intent intent = new Intent(ACTION_LOCATION_BROADCAST);
intent.putExtra(timUpdate,i);
LocalBroadcastManager.getInstance(myContext).sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Хмель это может, помогает. Извините за неправильный формат кода ....
Покажите нам Сервисный код –
@madhan kumar: Я одобрил ваше редактирование. При редактировании, пожалуйста, удалите такие вещи, как «Доброе утро» и «Спасибо». –
ok @ S.L.Barth здесь после того, как я это сделаю. –