I am using this code to show battery level in my app. It works fine but doesn't update battery level automatically.
What should I do to update the battery level automatically.
public class MainActivity extends Activity {
private TextView txtBattery;
private BroadcastReceiver mBatteryLevelReciver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
//int rawLevel = intent.getIntExtra("level", -1);
int rawLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
//int scale = intent.getIntExtra("scale", -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int level = -1;
if (rawLevel >= 0 && scale > 0) {
level = (rawLevel * 100) / scale;
}
txtBattery.setText("Battery3 Level Remaining :" + level + "%");
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtBattery = (TextView) findViewById(R.id.batterymeter_txt);
batteryLevel();
}
private void batteryLevel() {
IntentFilter batteryLevelFliter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(mBatteryLevelReciver, batteryLevelFliter);
}
}
Move the receiver variable to be a class attribute so it will be in memory when the intent is received:
public class Main extends Activity {
private TextView txtBattery;
private BroadcastReceiver mBatteryLevelReciver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//int rawLevel = intent.getIntExtra("level", -1);
int rawLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
//int scale = intent.getIntExtra("scale", -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int level = -1;
if (rawLevel >= 0 && scale > 0) {
level = (rawLevel * 100) / scale;
}
txtBattery.setText("Battery Level Remaining :" + level + "%");
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtBattery = (TextView) findViewById(R.id.batterymeter_txt);
batteryLevel();
}
private void batteryLevel() {
IntentFilter batteryLevelFliter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryLevelReciver, batteryLevelFliter);
}
Why do you unregister your BroadcastReceiver in your onReceive() method?
context.unregisterReceiver(this);
Remove that.
try this code..
public class AndroidBattery extends Activity {
private TextView batteryLevel, batteryVoltage, batteryTemperature,
batteryTechnology, batteryStatus, batteryHealth;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
batteryLevel = (TextView)findViewById(R.id.batterylevel);
batteryVoltage = (TextView)findViewById(R.id.batteryvoltage);
batteryTemperature = (TextView)findViewById(R.id.batterytemperature);
batteryTechnology = (TextView)findViewById(R.id.batterytechology);
batteryStatus = (TextView)findViewById(R.id.batterystatus);
batteryHealth = (TextView)findViewById(R.id.batteryhealth);
this.registerReceiver(this.myBatteryReceiver,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
private BroadcastReceiver myBatteryReceiver
= new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
if (arg1.getAction().equals(Intent.ACTION_BATTERY_CHANGED)){
batteryLevel.setText("Level: "
+ String.valueOf(arg1.getIntExtra("level", 0)) + "%");
batteryVoltage.setText("Voltage: "
+ String.valueOf((float)arg1.getIntExtra("voltage", 0)/1000) + "V");
batteryTemperature.setText("Temperature: "
+ String.valueOf((float)arg1.getIntExtra("temperature", 0)/10) + "c");
batteryTechnology.setText("Technology: " + arg1.getStringExtra("technology"));
int status = arg1.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN);
String strStatus;
if (status == BatteryManager.BATTERY_STATUS_CHARGING){
strStatus = "Charging";
} else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING){
strStatus = "Dis-charging";
} else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING){
strStatus = "Not charging";
} else if (status == BatteryManager.BATTERY_STATUS_FULL){
strStatus = "Full";
} else {
strStatus = "Unknown";
}
batteryStatus.setText("Status: " + strStatus);
int health = arg1.getIntExtra("health", BatteryManager.BATTERY_HEALTH_UNKNOWN);
String strHealth;
if (health == BatteryManager.BATTERY_HEALTH_GOOD){
strHealth = "Good";
} else if (health == BatteryManager.BATTERY_HEALTH_OVERHEAT){
strHealth = "Over Heat";
} else if (health == BatteryManager.BATTERY_HEALTH_DEAD){
strHealth = "Dead";
} else if (health == BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE){
strHealth = "Over Voltage";
} else if (health == BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE){
strHealth = "Unspecified Failure";
} else{
strHealth = "Unknown";
}
batteryHealth.setText("Health: " + strHealth);
}
}
};
}
Related
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final int REQUEST_CODE = 1234;
private int mScreenDensity;
private MediaProjectionManager mProjectionManager;
private static final int DISPLAY_WIDTH = 720;
private static final int DISPLAY_HEIGHT = 1280;
private MediaProjection mMediaProjection;
private VirtualDisplay mVirtualDisplay;
private ToggleButton mToggleButton;
private MediaRecorder mMediaRecorder;
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
private static final int REQUEST_PERMISSIONS = 10;
static {
ORIENTATIONS.append(Surface.ROTATION_0, 90);
ORIENTATIONS.append(Surface.ROTATION_90, 0);
ORIENTATIONS.append(Surface.ROTATION_180, 270);
ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mScreenDensity = metrics.densityDpi;
mProjectionManager = (MediaProjectionManager) getSystemService
(Context.MEDIA_PROJECTION_SERVICE);
mToggleButton = (ToggleButton) findViewById(R.id.toggle);
mToggleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) + ContextCompat
.checkSelfPermission(MainActivity.this,
Manifest.permission.RECORD_AUDIO)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale
(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) ||
ActivityCompat.shouldShowRequestPermissionRationale
(MainActivity.this, Manifest.permission.RECORD_AUDIO)) {
mToggleButton.setChecked(false);
Snackbar.make(findViewById(android.R.id.content), R.string.label_permissions,
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
#Override
public void onClick(View v) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission
.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO},
REQUEST_PERMISSIONS);
}
}).show();
} else {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission
.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO},
REQUEST_PERMISSIONS);
}
} else {
onToggleScreenShare(v);
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG, " requestCode " + requestCode + " resultCode " + requestCode);
if (REQUEST_CODE == requestCode) {
if (resultCode == RESULT_OK) {
mMediaProjection = mProjectionManager.getMediaProjection(resultCode, data);
startRecording(); // defined below
} else {
Log.d(TAG, "Persmission denied");
}
}
}
private static final String VIDEO_MIME_TYPE = "video/avc";
private static final int VIDEO_WIDTH = 720;
private static final int VIDEO_HEIGHT = 1280;
// …
private boolean mMuxerStarted = false;
private Surface mInputSurface;
private MediaMuxer mMuxer;
private MediaCodec mVideoEncoder;
private MediaCodec.BufferInfo mVideoBufferInfo;
private int mTrackIndex = -1;
private final Handler mDrainHandler = new Handler(Looper.getMainLooper());
private Runnable mDrainEncoderRunnable = new Runnable() {
#Override
public void run() {
drainEncoder();
}
};
private void startRecording() {
DisplayManager dm = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);
Display defaultDisplay = dm.getDisplay(Display.DEFAULT_DISPLAY);
if (defaultDisplay == null) {
throw new RuntimeException("No display found.");
}
prepareVideoEncoder();
try {
mMuxer = new MediaMuxer(Environment.getExternalStoragePublicDirectory(Environment
.DIRECTORY_DOWNLOADS) + "/video.mp4", MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
} catch (IOException ioe) {
throw new RuntimeException("MediaMuxer creation failed", ioe);
}
// Get the display size and density.
DisplayMetrics metrics = getResources().getDisplayMetrics();
int screenWidth = metrics.widthPixels;
int screenHeight = metrics.heightPixels;
int screenDensity = metrics.densityDpi;
// Start the video input.
mMediaProjection.createVirtualDisplay("Recording Display", screenWidth,
screenHeight, screenDensity, 0 /* flags */, mInputSurface,
null /* callback */, null /* handler */);
// Start the encoders
drainEncoder();
}
private void prepareVideoEncoder() {
mVideoBufferInfo = new MediaCodec.BufferInfo();
MediaFormat format = MediaFormat.createVideoFormat(VIDEO_MIME_TYPE, VIDEO_WIDTH, VIDEO_HEIGHT);
int frameRate = 15; // 30 fps
// Set some required properties. The media codec may fail if these aren't defined.
format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
//format.setInteger(MediaFormat.KEY_SAMPLE_RATE, 8000);
format.setInteger(MediaFormat.KEY_BIT_RATE, 6000000); // 6Mbps
format.setInteger(MediaFormat.KEY_FRAME_RATE, frameRate);
//format.setInteger(MediaFormat.KEY_CAPTURE_RATE, frameRate);
// format.setInteger(MediaFormat.KEY_REPEAT_PREVIOUS_FRAME_AFTER, 1000000 / frameRate);
//format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, 1);
format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 10); // 1 seconds between I-frames
// Create a MediaCodec encoder and configure it. Get a Surface we can use for recording into.
try {
mVideoEncoder = MediaCodec.createEncoderByType(VIDEO_MIME_TYPE);
mVideoEncoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
mInputSurface = mVideoEncoder.createInputSurface();
mVideoEncoder.start();
} catch (IOException e) {
releaseEncoders();
}
}
private void releaseEncoders() {
mDrainHandler.removeCallbacks(mDrainEncoderRunnable);
if (mMuxer != null) {
if (mMuxerStarted) {
mMuxer.stop();
}
mMuxer.release();
mMuxer = null;
mMuxerStarted = false;
}
if (mVideoEncoder != null) {
mVideoEncoder.stop();
mVideoEncoder.release();
mVideoEncoder = null;
}
if (mInputSurface != null) {
mInputSurface.release();
mInputSurface = null;
}
if (mMediaProjection != null) {
mMediaProjection.stop();
mMediaProjection = null;
}
mVideoBufferInfo = null;
//mDrainEncoderRunnable = null;
mTrackIndex = -1;
}
private boolean drainEncoder() {
mDrainHandler.removeCallbacks(mDrainEncoderRunnable);
while (true) {
int bufferIndex = mVideoEncoder.dequeueOutputBuffer(mVideoBufferInfo, 0);
if (bufferIndex == MediaCodec.INFO_TRY_AGAIN_LATER) {
// nothing available yet
break;
} else if (bufferIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
// should happen before receiving buffers, and should only happen once
if (mTrackIndex >= 0) {
throw new RuntimeException("format changed twice");
}
mTrackIndex = mMuxer.addTrack(mVideoEncoder.getOutputFormat());
if (!mMuxerStarted && mTrackIndex >= 0) {
mMuxer.start();
mMuxerStarted = true;
}
} else if (bufferIndex < 0) {
// not sure what's going on, ignore it
} else {
ByteBuffer encodedData = mVideoEncoder.getOutputBuffer(bufferIndex);
if (encodedData == null) {
throw new RuntimeException("couldn't fetch buffer at index " + bufferIndex);
}
if ((mVideoBufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
mVideoBufferInfo.size = 0;
}
if (mVideoBufferInfo.size != 0) {
if (mMuxerStarted) {
encodedData.position(mVideoBufferInfo.offset);
encodedData.limit(mVideoBufferInfo.offset + mVideoBufferInfo.size);
mMuxer.writeSampleData(mTrackIndex, encodedData, mVideoBufferInfo);
} else {
// muxer not started
}
}
mVideoEncoder.releaseOutputBuffer(bufferIndex, false);
if ((mVideoBufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
break;
}
}
Log.d(TAG, "Recording");
}
mDrainHandler.postDelayed(mDrainEncoderRunnable, 10);
return false;
}
public void onToggleScreenShare(View view) {
if (((ToggleButton) view).isChecked()) {
if (mMediaProjection == null) {
startActivityForResult(mProjectionManager.createScreenCaptureIntent(), REQUEST_CODE);
} else {
startRecording();
}
} else {
releaseEncoders();
}
}
}
startActivityForResult(mProjectionManager.createScreenCaptureIntent(), REQUEST_CODE);
This line of code request permission for capturing screen. Each time my code call that and it show a dialog for permission. But if i click "don't show this again", it won't request permission but grant permission in the background. How can i take permission only once and grant all time without selecting don't show again?? Full code is given here
public void onToggleScreenShare(View view) {
if (((ToggleButton) view).isChecked()) {
if (mMediaProjection == null) {
startActivityForResult(mProjectionManager.createScreenCaptureIntent(), REQUEST_CODE);
} else {
startRecording();
}
} else {
releaseEncoders();
}
}
On this Method startActivityForResult() method prompt screen capturing permission. If grant permission or deny it the code transfer call to onActivityResultMethod()
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG, " requestCode " + requestCode + " resultCode " + requestCode);
if (REQUEST_CODE == requestCode) {
if (resultCode == RESULT_OK) {
mMediaProjection = mProjectionManager.getMediaProjection(resultCode, data);
startRecording(); // defined below
} else {
Log.d(TAG, "Persmission denied");
}
}
}
On this method we get Intent data and resultCode. To further use MediaProjectionManager without requesting continuous permission, we have to save reference of the Intent and value of resultCode and use mediaProjectionManager via this line of code
mMediaProjection = mProjectionManager.getMediaProjection(saveResult, savedIntent);
So it won't request permission again as permission is already granted
I wrote a little android program, there is a main activity with a broadcast listener, and i create another thread. The thread searches for prime numbers, and loading them into a long arraylist, and after every 3 seconds, sends the filled array to the main activity via broadcast. Everythings ok, until i'm trying to get the long array extra from the intent. It causes every time a nullpointerexception.
I tried with a string arraylist, it worked, but i am curious because the intent has an "getlongarrayextra" method.
Here is my code:
public class MainActivity extends Activity {
public static String BROADCAST_THREAD_KEY = "broadcast_key";
public static String EXTRAARRAYID = "primes";
private static long MAXNUM = 2000000;
private PrimeCalculatorThread thread;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.numberstext);
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(android.content.Context context,
android.content.Intent intent) {
String origitext = textView.getText().toString();
long[] primes = intent.getExtras().getLongArray(EXTRAARRAYID);
Log.d("ASD", "broadcast received" + primes.toString());
StringBuilder builder = new StringBuilder();
if (primes != null) {
for (long prime : primes) {
builder.append(prime + " - ");
}
textView.setText(origitext + "\n" + builder.toString());
}
};
};
#Override
protected void onResume() {
Log.d("ASD", "ONRESUME");
initReceiverAndStartThread();
super.onResume();
}
private void initReceiverAndStartThread() {
IntentFilter filter = new IntentFilter(BROADCAST_THREAD_KEY);
registerReceiver(receiver, filter);
thread = new PrimeCalculatorThread(getBaseContext(), MAXNUM);
thread.start();
Log.d("ASD", "THREAD STARTED");
}
and the second thread:
public class PrimeCalculatorThread extends Thread {
private Context context;
private long maxnum;
List<Long> primes;
boolean isrunning;
public void setIsrunning(boolean isrunning) {
this.isrunning = isrunning;
}
private long counter = 0;
private long DELAYBETWEENBROADCAST = 3000;
public PrimeCalculatorThread(Context c, long maxnum) {
this.context = c;
this.maxnum = maxnum;
primes = new ArrayList<Long>();
}
#Override
public void run() {
long startTime = System.currentTimeMillis();
long estimatedTime;
isrunning = true;
for (long i = 0; i < maxnum; i++) {
Log.d("ASD", Boolean.toString(isrunning));
if (!isrunning)
break;
Log.d("ASD", i + "");
estimatedTime = System.currentTimeMillis() - startTime;
if (isPrime(i)) {
primes.add(i);
Log.d("ASD", i + "is a prime");
} else {
Log.d("ASD", i + "is not a prime");
}
if (estimatedTime > counter * DELAYBETWEENBROADCAST
+ DELAYBETWEENBROADCAST) { // elapsed another period
Log.d("ASD", primes.toString() + " will be sending.");
sendBroadCast();
primes.clear();
counter++;
}
try { //for debug purposes
Thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void sendBroadCast() {
Intent intent = new Intent(MainActivity.BROADCAST_THREAD_KEY);
intent.putExtra(MainActivity.EXTRAARRAYID, primes.toArray());
context.sendBroadcast(intent);
Log.d("ASD", "BROADCAST SENT" + primes.toString());
}
boolean isPrime(long n) {
if (n < 2)
return false;
if (n == 2 || n == 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
long sqrtN = (long) Math.sqrt(n) + 1;
for (long i = 6L; i <= sqrtN; i += 6) {
if (n % (i - 1) == 0 || n % (i + 1) == 0)
return false;
}
return true;
}
}
The problem is that you are managing a list of Long objects and passing it in putExtra, which means you are invoking putExtra(String name, Serializable value). Then you try to get that value using getLongArray(), but you haven't put any long array extra, you see! To solve this, replace
intent.putExtra(MainActivity.EXTRAARRAYID, primes.toArray());
with
long[] primesArray = new long[primes.size()];
for (int i = 0; i < primes.size(); i++) {
primesArray[i] = primes.get(i);
}
intent.putExtra(MainActivity.EXTRAARRAYID, primesArray);
This will invoke the correct putExtra(String name, long[] value) method.
I am using a service in my mp3 player to play media. I use mediaplayer object to play music. Normally the volume keys work when the music is playing. I also used Telephony Manager in my service to check phone calls. And I start and stop the music when the call is disconnected and is in progress respectively. But after the disconnection of phone call, the volume keys stopped working. I can see the dialog of volume change. But the sound volume don't change. Any idea? It is even happening in native player.
My player service:
public class PPlayService extends Service {
public static final int NOTIFICATION_NUMBER = 0;
Context conte;
MediaPlayer playHandler;
BroadcastReceiver broadcaster;
IncomingHandler mServiceHandler;
String online = "", link = "", name = "";
boolean playing = false;
boolean currentFlag = true;
Runnable runnable;
String[] uris, names;
int send;
SharedPreferences pre;
NotificationManager notificationManager;
NotificationCompat.Builder mBuilder;
AudioManager am;
// ........
PhoneStateListener phoneStateListener;
TelephonyManager mgr;
boolean notFromTelephone = false;
RemoteViews contentView;
BroadcastReceiver stopFromNoti, forwardFromNoti, backwardFromNoti;
Thread th;
public void handleMessage(Message msg) {
try {
playing = false;
if (playHandler != null) {
playHandler.setOnPreparedListener(null);
playHandler.setOnCompletionListener(null);
}
currentFlag = true;
System.gc();
if (online.equals("0")) {
contentView = new RemoteViews(getPackageName(),
R.layout.offline_notification_layout);
PendingIntent pit = PendingIntent.getBroadcast(conte, 0,
new Intent("stopfromnoti"),
PendingIntent.FLAG_UPDATE_CURRENT);
contentView.setOnClickPendingIntent(R.id.play_or_pause_noti,
pit);
PendingIntent backSong = PendingIntent.getBroadcast(conte, 0,
new Intent("backwardFromNoti"),
PendingIntent.FLAG_UPDATE_CURRENT);
contentView.setOnClickPendingIntent(R.id.backward_noti,
backSong);
PendingIntent frontSong = PendingIntent.getBroadcast(conte, 0,
new Intent("forwardFromNoti"),
PendingIntent.FLAG_UPDATE_CURRENT);
contentView.setOnClickPendingIntent(R.id.forward_noti,
frontSong);
} else {
contentView = new RemoteViews(getPackageName(),
R.layout.online_notification_layout);
PendingIntent pit = PendingIntent.getBroadcast(conte, 0,
new Intent("stopfromnoti"),
PendingIntent.FLAG_UPDATE_CURRENT);
contentView.setOnClickPendingIntent(R.id.play_or_pause_noti,
pit);
}
Intent intt = new Intent(getBaseContext(), MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(getBaseContext(), 0,
intt, 0);
mBuilder = new NotificationCompat.Builder(conte)
.setSmallIcon(R.drawable.icon).setContent(contentView)
.setContentIntent(pi).setAutoCancel(false);
notificationManager.notify(
Mp3Constants.NOTIFICATION_NUMBER_FOR_PLAYER,
mBuilder.build());
Intent in = new Intent(Mp3Constants.NOTIFICATION);
in.putExtra("download", "0");
in.putExtra("online", online);
in.putExtra("name", name);
in.putExtra("status", Mp3Constants.LOADING);
in.putExtra("currentTime", 0);
in.putExtra("totalTime", 0);
conte.sendBroadcast(in);
if (playHandler != null) {
playing = false;
playHandler.reset();
} else {
playHandler = new MediaPlayer();
}
if (online.equals("1")) {
// Online Stream
playHandler.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
playHandler.setDataSource(link);
playHandler.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer arg0) {
if (playHandler != null) {
if (!playHandler.isPlaying()) {
playSongNow();
}
}
}
});
playHandler.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
} else {
// Offline Stream
playHandler = MediaPlayer.create(conte, Uri.parse(link));
playSongNow();
}
} catch (Exception e) {
}
}
#Override
public void onCreate() {
conte = this;
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.requestAudioFocus(new OnAudioFocusChangeListener() {
#Override
public void onAudioFocusChange(int focusChange) {
}
}, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT,
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
forwardFromNoti = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
if (playHandler != null) {
playHandler.reset();
playing = false;
}
getSD();
int i = 0;
for (i = 0; i < send; i++) {
if (link.equalsIgnoreCase(uris[i])) {
break;
}
}
if (i >= send - 1) {
if (send > 0) {
name = names[0];
link = uris[0];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
}
} else {
name = names[i + 1];
link = uris[i + 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
}
}
};
backwardFromNoti = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
if (playHandler != null) {
playHandler.reset();
playing = false;
}
getSD();
int i = 0;
for (i = 0; i < send; i++) {
if (link.equalsIgnoreCase(uris[i])) {
break;
}
}
if (i == send || i == 0) {
if (send > 0) {
name = names[send - 1];
link = uris[send - 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
}
} else {
name = names[i - 1];
link = uris[i - 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
}
}
};
stopFromNoti = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
if (playHandler != null) {
playing = false;
Intent in = new Intent(Mp3Constants.NOTIFICATION);
in.putExtra("download", "0");
in.putExtra("online", online);
in.putExtra("status", Mp3Constants.COMPLETED);
in.putExtra("name", name);
in.putExtra("currentTime",
playHandler.getCurrentPosition() / 1000);
in.putExtra("totalTime", playHandler.getDuration() / 1000);
conte.sendBroadcast(in);
playHandler.reset();
stopSelf();
}
stopSelf();
}
};
phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
if (playHandler != null)
if (playHandler.isPlaying()) {
playing = false;
playHandler.pause();
}
} else if (state == TelephonyManager.CALL_STATE_IDLE) {
if (!notFromTelephone) {
notFromTelephone = false;
if (playHandler != null)
if (!playHandler.isPlaying()) {
playSongNow();
}
}
} else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
if (playHandler.isPlaying()) {
playing = false;
playHandler.pause();
}
}
super.onCallStateChanged(state, incomingNumber);
}
};
mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if (mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
pre = getSharedPreferences("download", 0);
online = pre.getString("online", "0");
link = pre.getString("link", "");
name = pre.getString("name", "");
contentView = new RemoteViews(getPackageName(),
R.layout.online_notification_layout);
PendingIntent pit = PendingIntent.getBroadcast(conte, 0, new Intent(
"stopfromnoti"), PendingIntent.FLAG_UPDATE_CURRENT);
contentView.setOnClickPendingIntent(R.id.play_or_pause_noti, pit);
notificationManager = (NotificationManager) conte
.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(conte)
.setSmallIcon(R.drawable.icon).setContent(contentView)
.setAutoCancel(false).setContentIntent(pit);
startForeground(Mp3Constants.NOTIFICATION_NUMBER_FOR_PLAYER,
mBuilder.build());
broadcaster = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
if (arg1.getExtras().getInt("action") == Mp3Constants.PAUSE) {
if (playHandler != null)
if (playHandler.isPlaying()) {
playing = false;
notFromTelephone = true;
playHandler.pause();
}
} else if (arg1.getExtras().getInt("action") == Mp3Constants.PLAY) {
if (playHandler != null)
if (!playHandler.isPlaying()) {
playSongNow();
}
} else if (arg1.getExtras().getInt("action") == Mp3Constants.STOP) {
if (playHandler != null) {
playHandler.reset();
playing = false;
}
stopSelf();
} else if (arg1.getExtras().getInt("action") == Mp3Constants.SEEK) {
if (playHandler != null) {
{
playHandler.seekTo(arg1.getExtras()
.getInt("seekto") * 1000);
}
}
} else if (arg1.getExtras().getInt("action") == Mp3Constants.FORWARD) {
if (playHandler != null) {
playHandler.reset();
playing = false;
}
if (pre.getBoolean("repeat", false)) {
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
} else {
getSD();
if (pre.getBoolean("shuffle", false)) {
Random r = new Random();
int x = r.nextInt(send);
link = uris[x];
name = names[x];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
} else {
for (int i = 0; i < send - 1; i++) {
if (link.equalsIgnoreCase(uris[i])) {
link = uris[i + 1];
name = names[i + 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler
.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
break;
}
}
}
}
// getSD();
// int i = 0;
// for (i = 0; i < send; i++) {
// if (link.equalsIgnoreCase(uris[i])) {
// break;
// }
// }
// if (i >= send - 1) {
// if (send > 0) {
// name = names[0];
// link = uris[0];
// pre.edit().putString("name", name);
// pre.edit().putString("online", online);
// pre.edit().putString("link", link);
// Message msg = mServiceHandler.obtainMessage();
// msg.arg1 = 1;
// mServiceHandler.sendMessage(msg);
// }
// } else {
// name = names[i + 1];
// link = uris[i + 1];
// pre.edit().putString("name", name);
// pre.edit().putString("online", online);
// pre.edit().putString("link", link);
// Message msg = mServiceHandler.obtainMessage();
// msg.arg1 = 1;
// mServiceHandler.sendMessage(msg);
// }
} else if (arg1.getExtras().getInt("action") == Mp3Constants.BACKWARD) {
if (playHandler != null) {
playHandler.reset();
playing = false;
}
if (pre.getBoolean("repeat", false)) {
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
} else {
getSD();
if (pre.getBoolean("shuffle", false)) {
Random r = new Random();
int x = r.nextInt(send);
link = uris[x];
name = names[x];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
} else {
int i = 0;
for (i = 0; i < send; i++) {
if (link.equalsIgnoreCase(uris[i])) {
break;
}
}
if (i == send || i == 0) {
if (send > 0) {
name = names[send - 1];
link = uris[send - 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler
.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
}
} else {
name = names[i - 1];
link = uris[i - 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
}
// for (int i = 0; i < send - 1; i++) {
// if (link.equalsIgnoreCase(uris[i])) {
// link = uris[i - 1];
// name = names[i - 1];
// pre.edit().putString("name", name);
// pre.edit().putString("online", online);
// pre.edit().putString("link", link);
// Message msg = mServiceHandler
// .obtainMessage();
// msg.arg1 = 1;
// mServiceHandler.sendMessage(msg);
// break;
// }
// }
}
}
// getSD();
// int i = 0;
// for (i = 0; i < send; i++) {
// if (link.equalsIgnoreCase(uris[i])) {
// break;
// }
// }
// if (i == send || i == 0) {
// if (send > 0) {
// name = names[send - 1];
// link = uris[send - 1];
// pre.edit().putString("name", name);
// pre.edit().putString("online", online);
// pre.edit().putString("link", link);
// Message msg = mServiceHandler.obtainMessage();
// msg.arg1 = 1;
// mServiceHandler.sendMessage(msg);
// }
// } else {
// name = names[i - 1];
// link = uris[i - 1];
// pre.edit().putString("name", name);
// pre.edit().putString("online", online);
// pre.edit().putString("link", link);
// Message msg = mServiceHandler.obtainMessage();
// msg.arg1 = 1;
// mServiceHandler.sendMessage(msg);
// }
}
}
};
registerReceiver(broadcaster, new IntentFilter(
"com.codebrew.bestmp3downloader.PPlayService"));
registerReceiver(stopFromNoti, new IntentFilter("stopfromnoti"));
registerReceiver(forwardFromNoti, new IntentFilter("forwardFromNoti"));
registerReceiver(backwardFromNoti, new IntentFilter("backwardFromNoti"));
HandlerThread thread = new HandlerThread("ServiceStartArguments", 0);
// //..................
// notificationManager = (NotificationManager) conte
// .getSystemService(Context.NOTIFICATION_SERVICE);
// mBuilder = new NotificationCompat.Builder(conte);
// RemoteViews remoteViews = new RemoteViews(getPackageName(),
// R.layout.notification_layout);
// try {
// mBuilder.setSmallIcon(R.drawable.icon);
// mBuilder.setAutoCancel(false).setOngoing(true)
// .setContent(remoteViews);
// Uri uri = RingtoneManager
// .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// mBuilder.setSound(uri);
// notificationManager.notify(Mp3Constants.NOTIFICATION_NUMBER,
// mBuilder.build());
// } catch (Exception e) {
// e.printStackTrace();
// }
// //...................
thread.start();
mServiceHandler = new IncomingHandler(PPlayService.this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// online = intent.getExtras().getString("online");
// link = intent.getExtras().getString("link");
// name = intent.getExtras().getString("name");
online = pre.getString("online", "0");
link = pre.getString("link", "");
name = pre.getString("name", "");
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
unregisterReceiver(broadcaster);
unregisterReceiver(stopFromNoti);
unregisterReceiver(forwardFromNoti);
unregisterReceiver(backwardFromNoti);
if (playHandler != null) {
if (playHandler.isPlaying()) {
playHandler.stop();
}
playHandler = null;
}
if (mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
}
super.onDestroy();
notificationManager.cancel(Mp3Constants.NOTIFICATION_NUMBER_FOR_PLAYER);
}
public void playSongNow() {
try {
playing = true;
playHandler.start();
runnable = new Runnable() {
public void run() {
while (playing) {
if (playing) {
try {
Intent in = new Intent(
Mp3Constants.NOTIFICATION);
in.putExtra("download", "0");
in.putExtra("online", online);
in.putExtra("name", name);
in.putExtra("status", Mp3Constants.PLAYING);
if (playHandler.getCurrentPosition() / 1000 == playHandler
.getDuration() / 1000)
th.stop();
in.putExtra("currentTime",
playHandler.getCurrentPosition() / 1000);
in.putExtra("totalTime",
playHandler.getDuration() / 1000);
if (currentFlag) {
currentFlag = false;
contentView.setTextViewText(
R.id.name_of_the_song, name);
notificationManager
.notify(Mp3Constants.NOTIFICATION_NUMBER_FOR_PLAYER,
mBuilder.setContent(
contentView)
.build());
}
conte.sendBroadcast(in);
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
};
th = new Thread(runnable);
th.start();
playHandler.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
playing = false;
pre.edit().putBoolean("stopped", true).commit();
Intent in = new Intent(Mp3Constants.NOTIFICATION);
in.putExtra("download", "0");
in.putExtra("online", online);
in.putExtra("status", Mp3Constants.COMPLETED);
in.putExtra("name", name);
try {
in.putExtra("currentTime",
playHandler.getCurrentPosition() / 1000);
in.putExtra("totalTime",
playHandler.getDuration() / 1000);
} catch (Exception e) {
in.putExtra("currentTime", 0);
in.putExtra("totalTime", 0);
}
conte.sendBroadcast(in);
if (online.equals("0")) {
if (pre.getBoolean("repeat", false)) {
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
} else {
getSD();
if (pre.getBoolean("shuffle", false)) {
Random r = new Random();
int x = r.nextInt(send);
link = uris[x];
name = names[x];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
} else {
for (int i = 0; i < send - 1; i++) {
if (link.equalsIgnoreCase(uris[i])) {
link = uris[i + 1];
name = names[i + 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler
.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
break;
}
}
}
}
}
if (online.equals("1")) {
// stopSelf();
}
}
});
} catch (Exception e) {
playing = false;
Intent in = new Intent(Mp3Constants.NOTIFICATION);
in.putExtra("download", "0");
in.putExtra("online", online);
in.putExtra("name", name);
in.putExtra("status", Mp3Constants.FAILED);
in.putExtra("currentTime", 0);
in.putExtra("totalTime", 0);
conte.sendBroadcast(in);
Toast.makeText(
getBaseContext(),
"Error playing: "
+ name
+ "\nFile broken or deleted! Please try another song",
Toast.LENGTH_SHORT).show();
stopSelf();
}
}
private void getSD() {
File f = new File(Environment.getExternalStorageDirectory().toString()
+ "/Music");
File[] files = f.listFiles();
if (files == null) {
return;
}
Arrays.sort(files, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
if (((File) o1).lastModified() > ((File) o2).lastModified()) {
return +1;
} else if (((File) o1).lastModified() < ((File) o2)
.lastModified()) {
return -1;
} else {
return 0;
}
}
});
send = files.length;
uris = new String[send];
names = new String[send];
for (int i = 0; i < send; i++) {
File file = files[i];
// take the file name only
double size = file.length();
size = size / (1024 * 1024);
String myfile = file
.getPath()
.substring(file.getPath().lastIndexOf("/") + 1,
file.getPath().length()).toLowerCase();
uris[send - 1 - i] = file.getPath();
names[send - 1 - i] = myfile;
}
}
static class IncomingHandler extends Handler {
private final WeakReference<PPlayService> mService;
IncomingHandler(PPlayService service) {
mService = new WeakReference<PPlayService>(service);
}
#Override
public void handleMessage(Message msg) {
PPlayService service = mService.get();
if (service != null) {
service.handleMessage(msg);
}
}
}
}
Here's what it looks like. I'm hoping a visual will help you help me!
I have tested it on three devices and four emulators with various screen sizes (so different image sizes) and versions of Android, and I haven't gotten any out of memory errors. I let my 3-year-old repeatedly pound on the animals and flip through them like crazy and still no OOM.
According to Google Play there are close to 200 installations since September 3rd 2013. I've only gotten one report of an OOM error so far, but now I'm worried that they are going to start rolling in. I'm including the whole activity in case one of my overridden methods has relevant information or something like that. This is my first published app so please excuse any newbie mistakes and feel free to criticize anything (as long as you include some suggestions for correcting it!)
setImages method from Game2Show (includes line 235, 'int currentAnimalImage...'):
private void setImages() {
//Get current letter and switch in name, letter and image that corresponds.
getLetter();
String l_img = "letter_" + currentLetter;
String a_img = "animal_" + currentLetter;
String n_img = "name_" + currentLetter;
int currentLetterImage = getResources().getIdentifier(l_img, "drawable", this.getPackageName());
ImageView l_iv = (ImageView) findViewById(R.id.current_letter);
l_iv.setImageResource(currentLetterImage);
int currentAnimalImage = getResources().getIdentifier(a_img, "drawable", this.getPackageName());
ImageView a_iv = (ImageView) findViewById(R.id.animal_image);
a_iv.setImageResource(currentAnimalImage);
int currentAnimalName = getResources().getIdentifier(n_img, "drawable", this.getPackageName());
ImageView n_iv = (ImageView) findViewById(R.id.animal_name);
n_iv.setImageResource(currentAnimalName);
Log.v(TAG, "voice: " + voice);
Log.v(TAG, "Config.alphabetSoundsArray_voice1: " + Config.alphabetSoundsArray_voice1);
Log.v(TAG, "Config.alphabetSoundsArray_voice2: " + Config.alphabetSoundsArray_voice2);
Log.v(TAG, "currentIndex: " + currentIndex);
if (Config.alphabetSoundsArray_voice1[currentIndex] !=0){
if (voice == 1) {
Sound(Config.alphabetSoundsArray_voice1[currentIndex]);
}
}
else {
}
if (Config.alphabetSoundsArray_voice2[currentIndex] !=0){
if (voice == 2) {
Sound(Config.alphabetSoundsArray_voice2[currentIndex]);
}
}
else {
}
System.gc();
}
Stack trace:
java.lang.OutOfMemoryError
at android.graphics.Bitmap.nativeCreate(Native Method)
at android.graphics.Bitmap.createBitmap(Bitmap.java:605)
at android.graphics.Bitmap.createBitmap(Bitmap.java:551)
at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:437)
at android.graphics.BitmapFactory.finishDecode(BitmapFactory.java:524)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:499)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:351)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:773)
at android.content.res.Resources.loadDrawable(Resources.java:1937)
at android.content.res.Resources.getDrawable(Resources.java:664)
at android.widget.ImageView.resolveUri(ImageView.java:542)
at android.widget.ImageView.setImageResource(ImageView.java:315)
at com.zenlifegames.teachtryabc123.Game2Show.setImages(Game2Show.java:235)
at com.zenlifegames.teachtryabc123.Game2Show.onCreate(Game2Show.java:57)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Game2Show:
package com.zenlifegames.teachtryabc123;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Shader;
import android.graphics.Shader.TileMode;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class Game2Show extends Activity {
private TextView textViewa;
private ImageView homeClicked;
int voice;
Handler handler = new Handler();
Intent i;
int currentIndex = 1;
String currentLetter;
ArrayList<Integer> alphabetNums;
String TAG = "Game2Show: ";
//private final String TAG = "Game2Show: ";
private int minAlphaRange = 1;
private int maxAlphaRange = 26;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game2_show);
i = new Intent(Game2Show.this, MyMusicService.class);
getMyViews();
setupPrefs();
Config.getPrefs(this);
musicToggleCheck();
userPreferences();
setFont();
setupAlphabetArray();
setImages();
Toast.makeText(Game2Show.this,
"Touch the letters, animals and words to hear audio.",
Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return false;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
Intent settingsActivity = new Intent(getBaseContext(),
Preferences.class);
startActivity(settingsActivity);
return super.onPrepareOptionsMenu(menu);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(this, GameSelector.class);
startActivity(intent);
super.onBackPressed();
}
public void returnHome(View view) {
homeClicked.setImageResource(R.drawable.homebuttonclicked);
if (Config.soundArray[0] !=0){Sound(Config.soundArray[0]);}
Intent intent = new Intent(this, GameSelector.class);
startActivity(intent);
}
private void musicToggleCheck() {
ImageButton musicToggleButton =(ImageButton)findViewById(R.id.music_toggle);
if (isMyServiceRunning()) {
musicToggleButton.setImageResource(R.drawable.music_toggle);
}
else {
musicToggleButton.setImageResource(R.drawable.music_toggle_off);
}
}
private void getMyViews() {
TextView textViewa = (TextView)findViewById(R.id.childs_name);
this.textViewa = textViewa;
final ImageView homeClicked = (ImageView) findViewById(R.id.home);
this.homeClicked = homeClicked;
}
private void setFont() {
Typeface t = Typeface.createFromAsset(this.getAssets(), "fonts/pen.ttf");
textViewa.setTypeface(t);
int[] color = {Color.RED, Color.BLUE};
float[] position = {0, 1};
TileMode tile_mode = TileMode.MIRROR; // Or TileMode.REPEAT;
LinearGradient lin_grad = new LinearGradient(0, 0, 0, 50,color,position, tile_mode);
Shader shader_gradient = lin_grad;
textViewa.getPaint().setShader(shader_gradient);
}
private void userPreferences() {
//Store childs name
textViewa.setText(Config.childsNameString);
//Set voice choice
int getVoiceChoice = Integer.parseInt(Config.storeVoiceChoice);
if (getVoiceChoice == 1) {
int voice = 1; //Mom
this.voice = voice;
}
else {
int voice = 2; //yg
this.voice = voice;
}
//Log.v(TAG, "voice: " + voice);
}
private void setupAlphabetArray() {
alphabetNums = new ArrayList<Integer>(maxAlphaRange);
for(currentIndex = minAlphaRange; currentIndex <= maxAlphaRange; currentIndex++) {
alphabetNums.add(currentIndex);
}
}
private void getLetter(){
if (currentIndex < minAlphaRange)
currentIndex = maxAlphaRange;
if (currentIndex > maxAlphaRange)
currentIndex = minAlphaRange;
if (currentIndex == 1) currentLetter = "a";
if (currentIndex == 2) currentLetter = "b";
if (currentIndex == 3) currentLetter = "c";
if (currentIndex == 4) currentLetter = "d";
if (currentIndex == 5) currentLetter = "e";
if (currentIndex == 6) currentLetter = "f";
if (currentIndex == 7) currentLetter = "g";
if (currentIndex == 8) currentLetter = "h";
if (currentIndex == 9) currentLetter = "i";
if (currentIndex == 10) currentLetter = "j";
if (currentIndex == 11) currentLetter = "k";
if (currentIndex == 12) currentLetter = "l";
if (currentIndex == 13) currentLetter = "m";
if (currentIndex == 14) currentLetter = "n";
if (currentIndex == 15) currentLetter = "o";
if (currentIndex == 16) currentLetter = "p";
if (currentIndex == 17) currentLetter = "q";
if (currentIndex == 18) currentLetter = "r";
if (currentIndex == 19) currentLetter = "s";
if (currentIndex == 20) currentLetter = "t";
if (currentIndex == 21) currentLetter = "u";
if (currentIndex == 22) currentLetter = "v";
if (currentIndex == 23) currentLetter = "w";
if (currentIndex == 24) currentLetter = "x";
if (currentIndex == 25) currentLetter = "y";
if (currentIndex == 26) currentLetter = "z";
}
public void goBack(View view) {
if (Config.soundArray[0] !=0){
Sound(Config.soundArray[0]);
}
currentIndex--;
setImages();
}
public void goForward(View view) {
if (Config.soundArray[0] !=0){
Sound(Config.soundArray[0]);
}
currentIndex++;
setImages();
}
public void sayLetter(View view) {
if (voice == 1) {
if (Config.alphabetSoundsArray_voice1[currentIndex] !=0){
Sound(Config.alphabetSoundsArray_voice1[currentIndex]);
}
}
if (voice == 2) {
if (Config.alphabetSoundsArray_voice2[currentIndex] !=0){
Sound(Config.alphabetSoundsArray_voice2[currentIndex]);
}
}
}
public void sayAnimal(View v) {
if (voice == 1) {
if (Config.animalNamesArray_voice1[currentIndex] !=0){
Sound(Config.animalNamesArray_voice1[currentIndex]);
}
}
if (voice == 2) {
if (Config.animalNamesArray_voice2[currentIndex] !=0){
Sound(Config.animalNamesArray_voice2[currentIndex]);
}
}
}
public void animalNoise(View v) {
if (Config.animalSoundsArray[currentIndex] !=0){
Sound(Config.animalSoundsArray[currentIndex]);
}
}
public void sideLetterClicked(View v) {
int id = v.getId();
if (id == R.id.side_letter_1)
currentIndex=1;
else if (id == R.id.side_letter_2) currentIndex=2;
else if (id == R.id.side_letter_3) currentIndex=3;
else if (id == R.id.side_letter_4) currentIndex=4;
else if (id == R.id.side_letter_5) currentIndex=5;
else if (id == R.id.side_letter_6) currentIndex=6;
else if (id == R.id.side_letter_7) currentIndex=7;
else if (id == R.id.side_letter_8) currentIndex=8;
else if (id == R.id.side_letter_9) currentIndex=9;
else if (id == R.id.side_letter_10) currentIndex=10;
else if (id == R.id.side_letter_11) currentIndex=11;
else if (id == R.id.side_letter_12) currentIndex=12;
else if (id == R.id.side_letter_13) currentIndex=13;
else if (id == R.id.side_letter_14) currentIndex=14;
else if (id == R.id.side_letter_15) currentIndex=15;
else if (id == R.id.side_letter_16) currentIndex=16;
else if (id == R.id.side_letter_17) currentIndex=17;
else if (id == R.id.side_letter_18) currentIndex=18;
else if (id == R.id.side_letter_19) currentIndex=19;
else if (id == R.id.side_letter_20) currentIndex=20;
else if (id == R.id.side_letter_21) currentIndex=21;
else if (id == R.id.side_letter_22) currentIndex=22;
else if (id == R.id.side_letter_23) currentIndex=23;
else if (id == R.id.side_letter_24) currentIndex=24;
else if (id == R.id.side_letter_25) currentIndex=25;
else if (id == R.id.side_letter_26) currentIndex=26;
else {
}
setImages();
}
private void setImages() {
//Get current letter and switch in name, letter and image that corresponds.
getLetter();
String l_img = "letter_" + currentLetter;
String a_img = "animal_" + currentLetter;
String n_img = "name_" + currentLetter;
int currentLetterImage = getResources().getIdentifier(l_img, "drawable", this.getPackageName());
ImageView l_iv = (ImageView) findViewById(R.id.current_letter);
l_iv.setImageResource(currentLetterImage);
int currentAnimalImage = getResources().getIdentifier(a_img, "drawable", this.getPackageName());
ImageView a_iv = (ImageView) findViewById(R.id.animal_image);
a_iv.setImageResource(currentAnimalImage);
int currentAnimalName = getResources().getIdentifier(n_img, "drawable", this.getPackageName());
ImageView n_iv = (ImageView) findViewById(R.id.animal_name);
n_iv.setImageResource(currentAnimalName);
Log.v(TAG, "voice: " + voice);
Log.v(TAG, "Config.alphabetSoundsArray_voice1: " + Config.alphabetSoundsArray_voice1);
Log.v(TAG, "Config.alphabetSoundsArray_voice2: " + Config.alphabetSoundsArray_voice2);
Log.v(TAG, "currentIndex: " + currentIndex);
if (Config.alphabetSoundsArray_voice1[currentIndex] !=0){
if (voice == 1) {
Sound(Config.alphabetSoundsArray_voice1[currentIndex]);
}
}
else {
}
if (Config.alphabetSoundsArray_voice2[currentIndex] !=0){
if (voice == 2) {
Sound(Config.alphabetSoundsArray_voice2[currentIndex]);
}
}
else {
}
System.gc();
}
//new
#Override
protected void onPause() {
super.onPause();
//Implemented to force music to stop when home is pressed.
Context context = getApplicationContext();
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
if (!taskInfo.isEmpty()) {
ComponentName topActivity = taskInfo.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
if(isMyServiceRunning()){
stopService(i);
}
}
}
}
#Override
protected void onRestart() {
super.onRestart();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
public void setupPrefs() {
ImageButton settingsClicked = ((ImageButton) findViewById(R.id.prefButton));
settingsClicked.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ImageView settingsClicked = ((ImageView) findViewById(R.id.prefButton));
settingsClicked.setImageResource(R.drawable.settings_button_clicked);
MediaPlayer buttonClicked = MediaPlayer.create(Game2Show.this, R.raw.click);
buttonClicked.start();
Intent settingsActivity = new Intent(getBaseContext(),
Preferences.class);
startActivity(settingsActivity);
}
});
}
public boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (MyMusicService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
public void musicToggle(View v) {
final ImageButton musicToggleButton =(ImageButton)findViewById(R.id.music_toggle);
if ((!isMyServiceRunning())) {
startService(i);
Toast.makeText(Game2Show.this, "Music on.", Toast.LENGTH_SHORT).show();
musicToggleButton.setImageResource(R.drawable.music_toggle);
}
else {
stopService(i);
Toast.makeText(Game2Show.this, "Music off.", Toast.LENGTH_SHORT).show();
musicToggleButton.setImageResource(R.drawable.music_toggle_off);
}
}
public void Sound(int s){
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float volume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
Config.spool.play(s, volume, volume, 1, 0, 1f);
};
#Override
protected void onResume() {
Log.v(TAG, "onResume called.");
super.onResume();
if (Config.spool != null) {
}
else {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
}
I want to show the battery level in my AppWidget. I used below code to get battery level in my activity
BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
int scale = -1;
int level = -1;
int voltage = -1;
int temp = -1;
#Override
public void onReceive(Context context, Intent intent) {
level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);
Log.d("Battery_level", ""+level);
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryReceiver, filter);
How can i implement this in my Class which extends AppWidgetProvider?
public class HomeWidget1 extends AppWidgetProvider {
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[]
appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
#Override
public void onReceive(Context context, Intent intent) {
}
What should be the code in onUpdate and onReceive method??
This code gives you the battery level:
package com.exercise.AndroidBattery;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.widget.TextView;
public class AndroidBattery extends Activity {
private TextView batteryLevel, batteryVoltage, batteryTemperature,
batteryTechnology, batteryStatus, batteryHealth;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
batteryLevel = (TextView)findViewById(R.id.batterylevel);
batteryVoltage = (TextView)findViewById(R.id.batteryvoltage);
batteryTemperature = (TextView)findViewById(R.id.batterytemperature);
batteryTechnology = (TextView)findViewById(R.id.batterytechology);
batteryStatus = (TextView)findViewById(R.id.batterystatus);
batteryHealth = (TextView)findViewById(R.id.batteryhealth);
this.registerReceiver(this.myBatteryReceiver,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
private BroadcastReceiver myBatteryReceiver
= new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
if (arg1.getAction().equals(Intent.ACTION_BATTERY_CHANGED)){
batteryLevel.setText("Level: "
+ String.valueOf(arg1.getIntExtra("level", 0)) + "%");
batteryVoltage.setText("Voltage: "
+ String.valueOf((float)arg1.getIntExtra("voltage", 0)/1000) + "V");
batteryTemperature.setText("Temperature: "
+ String.valueOf((float)arg1.getIntExtra("temperature", 0)/10) + "c");
batteryTechnology.setText("Technology: " + arg1.getStringExtra("technology"));
int status = arg1.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN);
String strStatus;
if (status == BatteryManager.BATTERY_STATUS_CHARGING){
strStatus = "Charging";
} else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING){
strStatus = "Dis-charging";
} else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING){
strStatus = "Not charging";
} else if (status == BatteryManager.BATTERY_STATUS_FULL){
strStatus = "Full";
} else {
strStatus = "Unknown";
}
batteryStatus.setText("Status: " + strStatus);
int health = arg1.getIntExtra("health", BatteryManager.BATTERY_HEALTH_UNKNOWN);
String strHealth;
if (health == BatteryManager.BATTERY_HEALTH_GOOD){
strHealth = "Good";
} else if (health == BatteryManager.BATTERY_HEALTH_OVERHEAT){
strHealth = "Over Heat";
} else if (health == BatteryManager.BATTERY_HEALTH_DEAD){
strHealth = "Dead";
} else if (health == BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE){
strHealth = "Over Voltage";
} else if (health == BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE){
strHealth = "Unspecified Failure";
} else{
strHealth = "Unknown";
}
batteryHealth.setText("Health: " + strHealth);
}
}
};
}