본문 바로가기

프로그래밍/Android

Battery Consume Analysis


Live wallpaer의 베터리 소모분석을 위해서 battey 소모량을 측정할 수 있는 유틸을 만들었다.
http://rhymestar.tistory.com/80


안드로이드의 베터리 정보는 어플리케이션 레벨에서는 100단위로 확인할 수 있다.

소모량 측정을 위해서는 베터리 레벨이 감소하는 시간계산 또는 시간당 소모량 측정이 필요하다.
또한 liva wallpaper가 활성화 될 수 있도록 backgroud로 동작할 필요가 있다.


1. Service 어플리케이션
2. Battery 리스너
3. 그래프(커스텀뷰)



[Service 어플리케이션]
1. 우선은 평범한 프로젝트를 만듭니다.

2. superclass를 android.app.Service로 하는 Java Class를 신규로 추가합니다.
아래의 함수를 override하고 필요한 동작을 코딩합니다.
@Override
public void onCreate()
{
    super.onCreate();
}
@Override
public void onDestroy()
{
    super.onDestroy();
}
@Override
public void onStart(Intent intent, int startId)
{
    super.onStart(intent, startId);
}
@Override
public IBinder onBind(Intent intent)
{
    return null;
}

3. AndroidManifast의 </activity>구문 다음에 <service android:name="BackgroundService"/>를 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest
        xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.rhymestar.batteryconsume"
        android:versionCode="100"
        android:versionName="1.0.0">

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name="BackgroundService" />
    </application>
    <uses-sdk android:minSdkVersion="7" />
</manifest>

4. Status bar에 Notification 표시하기
private NotificationManager notificationMgr;

@Override
public void onCreate()
{
    super.onCreate();
    notificationMgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
}
@Override
public void onDestroy()
{
    clearNotificationMessage();
    super.onDestroy();
}
@Override
public void onStart(Intent intent, int startId)
{
    super.onStart(intent, startId);
    displayNotificationMessage("service begin");
}
private void displayNotificationMessage(String message)
{
    Notification notification = new Notification(nGetIconId(), message, System.currentTimeMillis());
    notification.flags |= Notification.FLAG_ONGOING_EVENT;
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
    notification.setLatestEventInfo(this, getText(R.string.ServiceTitle), message, contentIntent);
    notificationMgr.notify(R.id.app_notification_id, notification);
}



[Battery Receiver]
1. AndroidManifast.xml에 베터리권한을 추가합니다.
<uses-permission android:name="android.permission.BATTERY_STATS" />

2. 베터리 리스너를 등록합니다. 리스너에서 정보를 얻어 Status bar에 표시합니다.
@Override
public void onCreate()
{
    super.onCreate();
    registerReceiver(battStatusReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    notificationMgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
}
@Override
public void onDestroy()
{
    clearNotificationMessage();
    unregisterReceiver(battStatusReceiver);
    super.onDestroy();
}
private BroadcastReceiver battStatusReceiver = new BroadcastReceiver()
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        if (0 < intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0))
        {
            displayNotificationMessage("CHARGING");
        }
        else
        {
            displayNotificationMessage("Battery Level : " + intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0));
        }
    }
}



[Graph 그리기]
안드로이드에서 제공하는 view item과 canvas에 직접 그리는 view를 함께사용하는 것이 목표입니다.


1. res/layout/main.xml 작업
  a. res/layout/main.xml 에 그래프를 제외한 화면구성을 완료합니다.
  b. 화면구성이 끝난 레이아웃의 view들을 LinearLayout으로 한번 묶어줍니다.
  c. 그래프가 표시될 레이아웃에 LinearLayout을 추가하고 id를 지정합니다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

    <!-- (b) LinearLayout으로 묶어줍니다 -->
    <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" >
        <Button android:text="Start" ...
        <Button android:text="Stop" ...
        <Button android:text="Refresh" ...
        <Button android:text="Result" ...
    </LinearLayout>

    <!-- (c) 그래프가 표시될 LinearLayout을 추가합니다 -->
    <LinearLayout android:id="@+id/graphLayout" android:layout_width="fill_parent" android:layout_height="fill_parent">
    </LinearLayout>

</LinearLayout>

2. MainActivity에서 Graph View를 추가합니다.
public class MainActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        LinearLayout layout = (LinearLayout)findViewById(R.id.graphLayout);
        GraphView graphView = new GraphView(this);
        layout.addView(graphView);
    }
    private class GraphView extends View
    {
        public GraphView(Context context)
        {
            super(context);
        }
        @Override
        public void onDraw(Canvas canvas)
        {
            //TODO: Draw Graph
        }
    }
}