서비스 및 BroadCastReceiver에 대해 배우려고합니다. 아래의 코드는 백그라운드에서 항상 실행되는 서비스입니다. 문제는 배터리 소모에 어떻게 영향을 미치는지 모른다는 것입니다. 항상 실행중인 서비스입니까?
은 배터리를 많이 소모 예정 ...내 목표는 켜거나 화면을 감지하는 것입니다, 그래서 앱이 가깝거나 열려 백그라운드에서 실행중인 서비스를 필요로? 설명해 주시겠습니까?
이 코드 예제에서 당신에게public class MyService extends Service{
private static final String TAG = "MyService";
private BroadcastReceiver mScreenOnOffReceiver;
private BroadcastReceiver OnOffBroadcastReceiver;
private NotificationManager mNotificationManager;
private Notification barNotif;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
// here to show that your service is running foreground
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent bIntent = new Intent(this, WidgetBroadCastReceiver.class);
PendingIntent pbIntent = PendingIntent.getActivity(this, 0 , bIntent, Intent.FLAG_ACTIVITY_CLEAR_TOP);
NotificationCompat.Builder bBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("STICKY")
.setContentText("Sub Title")
.setAutoCancel(true)
.setOngoing(true)
.setContentIntent(pbIntent);
barNotif = bBuilder.build();
this.startForeground(1, barNotif);
// here the body of your service where you can arrange your reminders and send alerts
Thread mThread = new Thread() {
@Override
public void run() {
// Register the ScreenOnOffReceiver.java
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
mScreenOnOffReceiver = new ScreenOnOffReceiver();
registerReceiver(mScreenOnOffReceiver, filter);
// initialize and register mScreenOnOffReceiver (no need the BroadcastReceiver class)
OnOffBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Log.e("", "SERVICE Screen is: " + "turned OFF.....");
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.e("", "SERVICE Screen is: " + "turned ON......");
}
}
};
registerReceiver(OnOffBroadcastReceiver, new IntentFilter(filter));
}
};
mThread.start();
return START_STICKY;
}
@Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "My Service has Started", Toast.LENGTH_SHORT).show();
}
@Override
public void onDestroy() {
Toast.makeText(this, "MyService Stopped", Toast.LENGTH_SHORT).show();
unregisterReceiver(mScreenOnOffReceiver);
unregisterReceiver(OnOffBroadcastReceiver);
stopForeground(true);
}
}
Wilfred Hughes를 편집 해 주셔서 감사합니다. 나는 매우 고마워. – YRTM2014