코딩(Coding)
[Android/안드로이드] Background(백그라운드) Service Thread 설정
Ghomdori
2020. 3. 12. 13:14
Android Background Service(Thread) 설정해주기.
따로 gradle에 설정해줄 것이 하나 없이 코드만 입력해주시면 끝납니다!
ServiceThread.java
import android.os.Handler;
public class ServiceThread extends Thread {
Handler handler;
boolean isRun = true;
public ServiceThread(Handler handler) {
this.handler = handler;
}
public void stopForever() {
synchronized (this) {
this.isRun = false;
}
}
public void run() {
//반복적으로 수행할 작업을 한다.
while (isRun) {
handler.sendEmptyMessage( 0 );//쓰레드에 있는 핸들러에게 메세지를 보냄
try {
Thread.sleep(3000000); //30분씩 돈다. 1000=1초
} catch (Exception e) {
}
}
}
}
MyService.java
public class MyService extends Service {
NotificationManager Notifi_M;
ServiceThread thread;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Notifi_M = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE );
myServiceHandler handler = new myServiceHandler();
thread = new ServiceThread( handler );
thread.stopForever();
return START_STICKY;
}
//서비스가 종료될 때 할 작업
public void onDestroy() {
myServiceHandler handler = new myServiceHandler();
thread = new ServiceThread( handler );
thread.start();
}
public class myServiceHandler extends Handler {
@Override
public void handleMessage(android.os.Message msg) {
NotificationManager notificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE );
Intent intent = new Intent( MyService.this, MainActivity.class );
intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP );
PendingIntent pendingIntent = PendingIntent.getActivity( MyService.this, 0, intent, PendingIntent.FLAG_ONE_SHOT );
Uri soundUri = RingtoneManager.getDefaultUri( RingtoneManager.TYPE_NOTIFICATION );
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
@SuppressLint("WrongConstant")
NotificationChannel notificationChannel = new NotificationChannel( "my_notification", "n_channel", NotificationManager.IMPORTANCE_MAX );
notificationChannel.setDescription( "description" );
notificationChannel.setName( "Channel Name" );
assert notificationManager != null;
notificationManager.createNotificationChannel( notificationChannel );
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder( MyService.this )
.setSmallIcon( R.drawable.drawable )
.setLargeIcon( BitmapFactory.decodeResource( getResources(), R.drawable.drawable ) )
.setContentTitle( "Notification Title" )
.setContentText( "Notification Message" )
.setAutoCancel( true )
.setSound( soundUri )
.setContentIntent( pendingIntent )
.setDefaults( Notification.DEFAULT_ALL )
.setOnlyAlertOnce( true )
.setChannelId( "my_notification" )
.setColor( Color.parseColor( "#ffffff" ) );
//.setProgress(100,50,false);
assert notificationManager != null;
int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
Calendar cal = Calendar.getInstance();
int hour = cal.get( Calendar.HOUR_OF_DAY );
if (hour == 07) {
notificationManager.notify( m, notificationBuilder.build() );
} else if (hour == 18) {
notificationManager.notify( m, notificationBuilder.build() );
}
}
}
}
MyService.java에서
저같은 경우는 Calendar를 사용해서
오전 7시 혹은 오후 6시(18시)일 때 Notification 주도록 해주었습니다!
이러면 앱을 끈 상태여도 Background Service로 Thread가 돌아서 Notification이 오게됩니다!
Firebase push를 사용해도 좋지만, static한 정해진 Notification은 이런게 좋을 것 같습니다!~