DIY‎ > ‎

Android: Night Clock

Night Clock: Donate problems:

I've had people with some (random, intermittent) problems when it comes to turning the button lights off on the their phones after they install Night Clock: Donate. Here are the steps you should try to resolve this:

1) Make sure the free version is uninstalled so you're sure you're launching the right Night Clock.
2) Try turning off (or on) auto brightness in the android settings. This sometimes messes with when I try to change the brightness.
3) After you tap the screen to dim/turn the lights off, press the button that makes the screen turn off and press it again to turn the screen back on.
4) Reboot the phone and try the above steps again.

If it still doesn't work, you can try contacting me and we can try to figure out why, but I believe that some models of phones (Droid 2 in particular) just don't allow 3rd party apps (such as Night Clock) to change the button brightness. Sorry!




(Note: I've gotten pretty lazy about updating the code breakdown on this page. Also lazy about having any kind of good style in the code. I'll try to keep updating the full source so you can download that. If I stop making changes to the code I'll update everything all at once, but it doesn't make sense to put the time into it to just change the code a week later).

I recently got a Droid, along with a multimedia dock, but found that even the "dim" setting was too bright to have by my bed. To fix this, I made an alternative clock application that comes up when you attach it to the multimedia dock, that is just plain red lettering on a black background. As with the stock multimedia dock application, I wanted to have an ongoing notification in the notification bar so I could pull it back up easily if I changed applications. This is my second shot at making an Android application so I'm sure it's not as elegant as it could be, but it works for my purposes. Below I'll go through and explain the code, or you can just download the entire source package. Either search "Night Clock" or scan QR code here from your phone to download the compiled .apk to your phone:


Main components:
NightClock.java
AndroidManifest.xml

NightClock.java

    
package com.neddashfox.nightclock;

import java.util.Calendar;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.DateFormat;
import android.view.WindowManager;
import android.widget.TextView;

All of the imports and package definitions. In eclipse use control-shift-o to add and remove required packages automatically.

public class NightClock extends Activity
{
    /** Called when the activity is first created. */
   
    private Calendar mCalendar;
    private String mFormat;
    private TextView mTimeDisplay;
    private boolean mLive = true;
    private final static String M12 = "h:mm";

Activity declaration and global variables.

    private final Handler mHandler = new Handler();
    private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver()
    {
            @Override
            public void onReceive(Context context, Intent intent)
            {
             final String action = intent.getAction();
             if (Intent.ACTION_TIMEZONE_CHANGED.equals(action))
                {
                    mCalendar = Calendar.getInstance();
                }
                // Post a runnable to avoid blocking the broadcast.
             if (Intent.ACTION_TIME_TICK.equals(action) || Intent.ACTION_TIME_CHANGED.equals(action))
             {
                mHandler.post(new Runnable() 
                {
                 public void run() 
                    {
                        updateTime();
                    }
                });
             }
             if (Intent.ACTION_DOCK_EVENT.equals(action))
             {
             int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, 0);
             if (state == Intent.EXTRA_DOCK_STATE_UNDOCKED) 
             {
             nm.cancelAll();
             finish();
             }
             if (state == Intent.EXTRA_DOCK_STATE_DESK)
             {
                     int icon = R.drawable.icon;
                  CharSequence tickerText = "Night Clock";
                  long when = System.currentTimeMillis();

                  Notification notification = new Notification(icon, tickerText, when);
                  notification.flags |= Notification.FLAG_ONGOING_EVENT;
                  CharSequence contentTitle = "Night Clock";
                  CharSequence contentText = "Open Night Clock";
                  Intent notificationIntent = new Intent(context, NightClock.class);
                  PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

                  notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
                  nm.notify(1, notification);
             }
             }
            }
    };

This is the code for the broadcast receiver. This is called when any of the actions added to the filter are seen. This handles the clock broadcasts (such as time zone changes, minute ticks. etc) and dock events. On disconnect it clears the notification and closes the activity.

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        
        //Hide status bar 

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); 
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        
The flags for the activity are set so that the screen doesn't turn off and the notification bar is hidden (so that the clock is the only thing that appears on the screen).
      
        setContentView(R.layout.main);     
        Context context = getApplicationContext();
        nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if(firstLaunch == true)
        {
         int icon = R.drawable.icon;
      CharSequence tickerText = "Night Clock";
      long when = System.currentTimeMillis();

      Notification notification = new Notification(icon, tickerText, when);
      notification.flags |= Notification.FLAG_ONGOING_EVENT;
      CharSequence contentTitle = "Night Clock";
      CharSequence contentText = "Open Night Clock";
      Intent notificationIntent = new Intent(context, NightClock.class);
      PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

      notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
      nm.notify(1, notification);
        }
        firstLaunch = false;
    
This code creates the notification during the first call to Night Clock (which occurs during the desk dock connect event).

 
//Display and update clock
        mTimeDisplay = (TextView) findViewById(R.id.rowone);
        mFormat = M12;
        mCalendar = Calendar.getInstance();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_TIME_TICK);
        filter.addAction(Intent.ACTION_TIME_CHANGED);
        filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
        filter.addAction(Intent.ACTION_DOCK_EVENT);
        this.registerReceiver(mIntentReceiver, filter);
        
        updateTime();
    }


The code that sets up the filter for broadcast receiver mIntentReceiver. The filter is set up to catch ACTION_TIME_TICK (minute ticks), ACTION_TIME_CHANGED (if the system time is changed), ACTION_TIMEZONE_CHANGED (if the current time zone has changed), and ACTION_DOCK_EVENT. Call updateTime to set initial clock time.
    
    private void updateTime() 
    {
        if (mLive)
        {
            mCalendar.setTimeInMillis(System.currentTimeMillis());
        }

        CharSequence newTime = DateFormat.format(mFormat, mCalendar);
        mTimeDisplay.setText(newTime);
    }
}

The updateTime method that changes the time to be set to the system time, and display it in the mFormat.


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.neddashfox.nightclock"
      android:versionCode="2"
      android:versionName="1.1">

Standard manifest definition, including package location.

    <application android:icon="@drawable/icon" android:theme="@android:style/Theme.NoTitleBar" android:label="@string/app_name" android:debuggable="false">

 Application tag. Sets it so there is no title bar (without this, a title bar containing the name of the application would be shown). If you are debugging, make sure to set debuggable to true.

 
       <activity android:name=".NightClock"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DESK_DOCK" />
                <category android:name="android.intent.category.DEFAULT" />
         </intent-filter>
        </activity>

The NightClock activity declaration. android.intent.action.MAIN says that this activity is the main activity for the NightClock application. android.intent.category.DESK_DOCK calls the activity when the desk dock has been plugged in. This enables the activity to be called automatically when the dock is plugged in.

    </application>
    <uses-sdk android:minSdkVersion="6" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
</manifest> 

I only have tested this on SDK version 6 (for Droid 2.0.1), so that is the minSdkVersion. android.permission.RECEIVE_BOOT_COMPLETED allows application to launch on phone startup.

If you have any questions, comments, or improvements, don't hesitate to email me at me@thiswebsitename

Č
ċ
ď
Ned Fox,
May 28, 2010, 11:30 PM
Comments