Skip to content

Instantly share code, notes, and snippets.

@doyle-flutter
Last active February 19, 2021 04:54
Show Gist options
  • Save doyle-flutter/790957b34b9da9146342601866d952fd to your computer and use it in GitHub Desktop.
Save doyle-flutter/790957b34b9da9146342601866d952fd to your computer and use it in GitHub Desktop.
#07 포그라운드 - 안드로이드 : 서비스
// ... import 생략
// Permission - Manifest.xml : <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
public class MyService extends Service {
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if("startForeground".equals(intent.getAction())){
Log.d("DOY", "시작");
startForegroundService();
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.d("DOY", "DESTROY");
super.onDestroy();
}
private void startForegroundService() {
Intent notificationIntent = new Intent(this, MainActivity3.class);
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification =
new Notification.Builder(this, "default")
.setContentTitle("포그라운드")
.setContentText("with Flutter")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentIntent(pendingIntent)
.setTicker("tickerTxt")
.build();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(
new NotificationChannel("default","기본", NotificationManager.IMPORTANCE_DEFAULT)
);
}
startForeground(1, notification);
Timer m = new Timer();
TimerTask mt = new TimerTask() {
@Override
public void run() {
stopSer();
}
};
m.schedule(mt,10000);
}
void stopSer(){
this.stopSelf();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment