Screen wont dim when I tell it to - android

I'm trying to get my screen to go dim when I call an activity from a notification. Here is the code I am using:
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = 0.01f;
getWindow().setAttributes(lp);
Maybe I am doing something wrong here, if so can someone tell me whats going on and why its not working the way its supposed to?!
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
public class NoteMe extends Activity {
/** Called when the activity is first created. */
NotificationManager nm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String title = "Example text";
String contentText = "Full hello world!";
String text = "Starting Notification!";
nm = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
long when = System.currentTimeMillis();
int icon = R.drawable.ic_launcher;
Intent intent = new Intent(getBaseContext(), MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(
getBaseContext(), 0, intent, 0);
Notification notification = new Notification(icon, text, when);
notification.setLatestEventInfo(getBaseContext(), title, contentText,
contentIntent);
notification.flags = Notification.FLAG_ONGOING_EVENT;
int NOTIFICATION_ID = 10;
nm.notify(NOTIFICATION_ID, notification);
}
}
Here is the requested code

You code is 100% correct. There are two possibilities the first is the most likely
1) The activity is not getting called off the notification. I believe there is a special way that you fire off from a notification involving pending intents. I would guess thats the problem. Just to be sure put some breakpoints in onCreate and onStart to see if it ever gets called. Or just put a log statement near your code to see if it gets called. I'm guessing it never gets called.
2) The adjustment you are making 0.1f is not visible change.
Please review this and just make sure notifications are being received:
http://www.vogella.com/articles/AndroidNotifications/article.html
One difference I see is getContextBase() vs. this
If its not that it looks like maybe MainActivity.class manifest declaration might not be right.

Try something like this - refreshing the screen after you have set the attribute.
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness =0.01f
getWindow().setAttributes(lp);
startActivity(new Intent(this,RefreshScreen.class));
So one hack on refreshing the screen is starting dummy activity and than in on create of that dummy activity to call finish(); so the changes of the brightness to take an effect.

The code you posted would only dim the screen for your application. If thats what you want, thats fine. But if you want to dim the screen on the phone then you need to change the system setting System.SCREEN_BRIGHTNESS
// turn on manual control of system screen brightness
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
final int dimBrightnessValue = 96; // valid values 0-255
// change the brightness value
System.putInt(getContentResolver(), System.SCREEN_BRIGHTNESS, dimBrightnessValue);
You would also need to add the following to the AndroidManifest.xml
<!-- Needed for changing screen brightness -->
<uses-permission android:name="android.permission.WRITE_SETTINGS" />

Related

How to update my notification to show my time counter changing?

I am almost finished with this toy app game I am making.
Problem:
My notification is always showing my counter to be 30000. Why isn't it timing down?
What I have done:
I have implemented a simple Service class and a custom timer to tick down. Eventually once I am sure the timer is working I will exit the entire game.
Here is my code:
package com.example.redshirtmarblez;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.widget.Toast;
public class TimingService extends Service{
public long counter = 30000;
private Context ctx;
private Activity localActivity;
private NotificationManager nm;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
super.onCreate();
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
declareNotification();
timer.start();
//Toast.makeText(this, "Timer is :" + counter, Toast.LENGTH_LONG).show();
//showNotification();
}
public void getActivity(Activity activity)
{
localActivity = activity;
}
//count to end the game
public CountDownTimer timer = new CountDownTimer(30000, 1000){
public void onTick(long millisUntilFinished){
counter = millisUntilFinished / 1000;
}
public void onFinish(){
counter = 0;
//Kill the game
int i = android.os.Process.myPid();
android.os.Process.killProcess(i);
}
};
/*
* Show a notification while this service is running
*/
public void declareNotification()
{
//Declare a new notification
Notification notification = new Notification(R.drawable.ic_launcher, "A New Notification", System.currentTimeMillis());
notification.flags |= Notification.FLAG_ONGOING_EVENT;
notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
Intent intent = new Intent(this, TimingService.class);
PendingIntent activity = PendingIntent.getActivity(this, 0, intent, 0);
notification.setLatestEventInfo(this, "herp", "counter: " + counter, activity);
//This is clearly not 1337, but a good joke
startForeground(1337, notification);
}
}
All this does when it runs is shows "A New Notification", and then changes to "herp counter: 30000". However, this notification never changes. It just stays 30000. Why? I thought I fixed this with making the flag ongoing?
https://developer.android.com/reference/android/app/Notification.Builder.html#setUsesChronometer(boolean)
Show the when field as a stopwatch. Instead of presenting when as a
timestamp, the notification will show an automatically updating
display of the minutes and seconds since when. Useful when showing an
elapsed time (like an ongoing phone call). The counter can also be set
to count down to when when using setChronometerCountDown(boolean).
No updating required, works off the setWhen() value
NotificationCompat.Builder notification = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_default_notification)
.setTicker("Ticker Text")
.setWhen(when) // the time stamp, you will probably use System.currentTimeMillis() for most scenarios
.setUsesChronometer(true)
.setContentTitle("Title Text")
.setContentText("Content Text");
counter is not a reference; the notification will not update with its new value until you explicitly tell it to.
Have a look at the documentation on updating an existing notification. Your ID is 1337 here, so you can use that to update it.
In fact, you may just be able to call declareNotification() again from your onTick() method... If this doesn't work, however, I would suggest keeping a reference to the Notification object (as a member variable), then updating it, and use nm.notify(1337, /* your notification object */);.
I don't know why you want to use a notification. But you need to keep updating your notification. For a simple fix add
declareNotification();
underneath this line:
counter = millisUntilFinished / 1000;
Note that this isn't a great way to code it. Really you should pass a method only updating the notification rather than "creating" a new one. However as long as they have the same ID, one will replace the other.
Also just to use a more up to date way of managing notifications, use
NotificationCompat.builder b = new NotificationCompat.Builder(context);

How can you detect if your activity is being onPaused because of a PendingIntent which you created?

If I have an Activity which is in the foreground and I navigate to another Activity within my app, I can detect this by setting a flag when you begin the transfer and wiping it when you have transferred to the new activity. This allows me to distinguish between an activity onPause due to an internal (flag set) or external (flag not set) event.
However, I am having trouble doing this for PendingIntents embedded in Notifications. Is it possible to detect that my Activity is being onPaused because they selected the notification I created on the notification bar? Is there some kind of notification listener I can use which will trigger before the notification fires and the pending intent is executed which onPauses my Activity?
I appreciate that this is somewhat confusing, so I've made a skeleton project which demonstrates the problem:
package com.example.notificationtest;
import android.os.Bundle;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
public class MainActivity extends Activity {
private static final int INCOMING_NOTIFICATION_ID = 1;
private static final String TAG = "NotificationTest";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onPause() {
super.onPause();
Log.e(TAG,"onPause");
}
#Override
public void onResume() {
super.onResume();
Log.e(TAG,"onResume");
}
public void onTransitionButtonClick(View view) {
Intent intent = new Intent(this, MainActivity.class);
Log.e(TAG,"About to start activity: onPause will be invoked.");
startActivity(intent);
}
public void onNotificationButtonClick(View view) {
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
Notification notification = new Notification(android.R.drawable.alert_dark_frame, "Alert!", System.currentTimeMillis());
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.flags |= Notification.FLAG_INSISTENT;
notification.setLatestEventInfo(this, "Click to open", "Click to open", pendingIntent);
// Show the alert.
final NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(INCOMING_NOTIFICATION_ID, notification);
}
}
With the activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/notify_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="#dimen/padding_medium"
android:text="Make a notification"
android:onClick="onNotificationButtonClick"
tools:context=".MainActivity" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/notify_button"
android:padding="#dimen/padding_medium"
android:text="Normal transition"
android:onClick="onTransitionButtonClick"
tools:context=".MainActivity" />
</RelativeLayout>
If you select the "Normal transition" button, the log prints "About to start activity: onPause will be invoked." prior to onPause.
If you select the "Make a notification" button and then drag down the notification bar and tap on the notification, I want to be informed of that tap prior to onPause so I can insert the same line "About to start activity: onPause will be invoked.". How can I do that?
beside holding intent to start activity, PendingIntent can hold also intent to "fire" a broadcast.
you can use such custom broadcast as trigger to the notification, then implement BroadcastReceiver that will be registered to that broadcast, and will show whatever you want , and only then will start the desired activity.
Intent intent = new Intent("my.custom.broadcast.action");
pendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
the receiver will look something like this:
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//do whatever you want
// if this code is being executed - it's a sign that the user clicked on the notification...
Intent intent = new Intent(this, MainActivity.class);
Log.e(TAG,"About to start activity: onPause will be invoked.");
startActivity(intent);
}
};
don't forget to register the mReceiver when onCreate() invokes, and unregister it onDestroy()
registerReceiver(mReceiver , new IntentFilter("my.custom.broadcast.action"));
unregisterReceiver(mReceiver);
in this approach you can control exactly what will happen when the user click on the notification. as you can see - it's possible only to send broadcast when notification clicked. no one said you must start activity at all..
Let me begin by trying to translate your question to another (just for clarity): How can I have my Activity execute code before it is paused because an Activity associated with my Notification (which I can control) is going to be displayed?
Provided that the translation is good enough for the purpose of answering:
Are you sure that this approach would be a solution? Because there are many cases where your Activity will get paused and the user displays your Notification's Activity "almost immediately after", while there will still be steps in between (like when other notifications are viewed first). I presume that technically, this means that you still must perform the same code there, while at the same time you can't have any indication that your notification will be viewed "in the very near future".
So for a suitable answer, I believe one will have to think outside of the box a bit, depending on the nature of the code you intend to execute and the motivation for it.
So if you update your question in this regard and notify me, I'll be glad to have a second look.
Update after update of question:
You can avoid firing the next Activity when the user presses the notification, and instead just fire an event. If your activity registers a BroadcastReceiver programmatically, it should be able to receive this event, and then update itself and start the next Activity, just as you wish.

Android Honeycomb notification popup too frequently

I am developing for Honeycomb and for days i am trying to solve this problem.
I have an notification service without intent (don`t need one), the problem is that after every call for displaymessage function the notification pup-up each time, so i get 100 notifications. I would like it to popup only once and after that only change the text of percent. Similar to downloading from market progress bar and percentage. I have isolated the function and created new testing code but with no success. If you look at this from other angle, i wish to change the text on existing notification without creating new notification.
Can you please help me?
Here is the whole code (after the isolation):
package com.disp;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Bundle;
import android.os.SystemClock;
public class DispalyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for (int i = 0; i < 100; i++) {
SystemClock.sleep(300);
displaymessage(""+i+"%");
}
}
public void displaymessage(String string) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
Notification notification = new Notification(R.drawable.ic_launcher, "Notification Service", System.currentTimeMillis());
Context context = getApplicationContext();
notification.setLatestEventInfo(context, "Downloading Content:", string, null);
final int HELLO_ID = 2;
mNotificationManager.notify(HELLO_ID, notification);
}
}
Because each notification is uniquely identified by the NotificationManager with an integer ID, you can revise the notification by calling setLatestEventInfo() with new values, change some field values of the notification, and then call notify() again.
You can revise each property with the object member fields (except for the Context and the notification title and text). You should always revise the text message when you update the notification by calling setLatestEventInfo() with new values for contentTitle and contentText. Then call notify() to update the notification. (Of course, if you've created a custom notification layout, then updating these title and text values has no effect.)
from
http://developer.android.com/guide/topics/ui/notifiers/notifications.html

Android Phonegap App - How to send notifications

Could anyone possibly offer some advice on how to setup Status bar notifications in Android?
My skillset is all based around design/front-end dev (hence using phonegap) so I'm a beginner with Eclipse.
I have read this tutorial - http://androidforbeginners.blogspot.com/2010/02/how-to-create-status-bar-notifications.html and have pasted the code into the activity area of my Android Manifest file. But I don't quite understand how it will work. If I compile this now as an APK and install it on a phone -- is it now ready to receive notifications? If so how do I send them, and where do I type the sending code?
Hopefully it's fairly simple as my boss is hoping that I'll have it completed before christmas!
Cheers for your help.
All the best
Paul
You want status bar notification? If yes...you are lucky...here's a plugin which I already created for phonegap. Look around for how to embed the external plugin in android.
https://github.com/phonegap/phonegap-plugins/tree/master/Android/StatusBarNotification
Here you can find better explanation with source codes about notifications.
Notification can be a reaction on some event. For instance, you can develop a simple application with one button. When you press this button a notification will be displayed in the status bar.
About the development. You should install Android SDK, create an emulator of the device. Also it is very useful to install Android ADT - this is a pluging for Eclipse to help to develop Android applications. After that when you build an application it will be automatically installed on the emulator.
Here is the code how to make a simple notification:
package your.package
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class AcNotificationTestMain extends Activity implements OnClickListener {
/** Called when the activity is first created. */
private static final int SEND_ID = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button mBtnSend = (Button) findViewById(R.id.button1);
mBtnSend.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Log.v("","OnClick...");
// Create an object of Notification manager
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int icon = android.R.drawable.sym_action_email; // icon from resources
CharSequence tickerText = "New Notification"; // ticker-text
long when = System.currentTimeMillis(); // notification time
Context context = getApplicationContext(); // application Context
CharSequence contentTitle = "My notification"; // expanded message title
CharSequence contentText = "Click me!"; // expanded message text
Intent notificationIntent = new Intent(this, AcNotificationTestMain.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
// the next two lines initialize the Notification, using the configurations above
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(SEND_ID, notification);
}
}
And layout file:
<LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="#string/hello"/>
<Button android:id="#+id/button1" android:text="#string/AcNotificationTest_BtnSendNotificationText" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</LinearLayout>

Cancel dynamic notification in Android when the notification is selected

Suppose I am creating an Android application that's like an SMS app. The requirements are as follows:
The user can receive multiple notifications, each one having a dynamic ID of type int.
When a notification is selected, it loads an activity which displays a corresponding message (the SMS).
The single notification that was selected should be automatically dismissed.
My idea for how to handle this was to use putExtra to add the integer ID to the intent, which would then be accessible from the intent within the activity it loads, which would then dismiss the notification that called it.
For my test case, here are the specs:
Notifications will eventually be
generated from a service, for now
they are being spawned when the test
user presses a button.
When a notification is selected, the
called activity toasts the message,
then attempts to dismiss the
notification. (For the sake of
visibility)
Here are my problems:
When the first notification is
selected, it is correct. The
notification is dismissed.
When each successive notification is
selected, the first notification's
ID is shown, and nothing is
dismissed.
I am a Java novice, more accustomed
to scripting languages (such as
Perl, PHP, etc) :)
Here is my source:
<?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"
>
<Button
android:id="#+id/create_notification"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:text = "Create new notification"
/>
package org.test.notifydemo;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.Random;
public class aRunNotificationDemo extends Activity
{
private NotificationManager mNotificationManager;
#Override
public void onCreate( Bundle icicle )
{
super.onCreate( icicle );
setContentView( R.layout.run_notify_demo );
mNotificationManager = (NotificationManager) getSystemService( aRunNotificationDemo.NOTIFICATION_SERVICE );
int close_notify_id = getIntent().getIntExtra( "notification_id", 0 );
if ( close_notify_id != 0 )
{
Toast.makeText( aRunNotificationDemo.this, "Dimissing this notification: " + Integer.toString(close_notify_id), Toast.LENGTH_SHORT ).show();
mNotificationManager.cancel( close_notify_id );
}
findViewById( R.id.create_notification ).setOnClickListener( new MyButtonListener() );
}
private class MyButtonListener implements Button.OnClickListener
{
public void onClick( View my_view )
{
Random randGen = new Random();
int notify_id = randGen.nextInt();
int icon = R.drawable.icon_notification_01;
CharSequence tickerText = Integer.toString(notify_id) + " New SMS!";
long when = System.currentTimeMillis();
Notification my_notification = new Notification(icon, tickerText, when);
Context context = getApplicationContext();
CharSequence contentTitle = Integer.toString(notify_id) + " New SMS Available!";
CharSequence contentText = Integer.toString(notify_id) + " There is a new SMS available.";
Intent notificationIntent = new Intent( aRunNotificationDemo.this, aRunNotificationDemo.class );
notificationIntent.putExtra( "notification_id", notify_id );
PendingIntent contentIntent = PendingIntent.getActivity( aRunNotificationDemo.this, 0, notificationIntent, 0 );
my_notification.setLatestEventInfo( context, contentTitle, contentText, contentIntent );
mNotificationManager.notify( notify_id, my_notification );
}
}
}
When activity is once created its onCreate() method is called. Next time it is displayed the method is not necessarily called. Try moving code which removes the notification to onResume() method. Get familiar with Activity life cycle.
And by the way it is easier than you think:
http://developer.android.com/reference/android/app/Notification.html#FLAG_AUTO_CANCEL
my_notification.flags |= Notification.FLAG_AUTO_CANCEL;
Put the code above when creating a Notification.

Categories

Resources