Update foreground service notification with sensor data - android

I am developing a pedometer. I have a service which is running fine. I made my service foreground also. But how do I update my notification with sensor data. I am getting steps from sensor. I just want to show it in a notification which is showing usig the foreground service.
public class StepCounterService extends Service {
private static final String LOG_TAG = "ForegroundService";
public static Boolean FLAG = false;
private SensorManager mSensorManager;
private StepDetector detector;
private PowerManager mPowerManager;
private WakeLock mWakeLock;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startServiceForeground(intent, flags, startId);
Log.d("zzz", "start command");
return START_STICKY;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
new StepCountManager(this);
FLAG = true;
Log.e("Service_Started", "");
detector = new StepDetector(this);
mSensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);
mSensorManager.registerListener(detector,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
mPowerManager = (PowerManager) this
.getSystemService(Context.POWER_SERVICE);
mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP, "S");
mWakeLock.acquire();
reloadSettings();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
FLAG = false;
if (detector != null) {
mSensorManager.unregisterListener(detector);
}
if (mWakeLock != null) {
mWakeLock.release();
}
Log.e("Service_destroyed", "");
}
public void reloadSettings() {
if (detector != null) {
detector.setSensitivity(
Float.valueOf("10")
);
}
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Intent restartService = new Intent(getApplicationContext(),
this.getClass());
restartService.setPackage(getPackageName());
PendingIntent restartServicePI = PendingIntent.getService(
getApplicationContext(), 1, restartService,
PendingIntent.FLAG_ONE_SHOT);
//Restart the service once it has been killed android
((AlarmManager) getSystemService(Context.ALARM_SERVICE))
.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, PendingIntent
.getService(this, 3, new Intent(this, StepCounterService.class), 0));
}
public int startServiceForeground(Intent intent, int flags, int startId) {
Intent notificationIntent = new Intent(this, HomeActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Mobiefit Walk")
.setContentIntent(pendingIntent)
.setOngoing(true)
.build();
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(300, notification);
Notification n;
startForeground(300, notification);
return START_STICKY;
}
}
I just want to show my steps under this notification which I am getting from sensor.
Here is my step_detector class:
public class StepDetector implements SensorEventListener {
public static UpdateStepCount mStepsUpdater;
public static int CURRENT_SETP = 0;
public static float SENSITIVITY = 0; //SENSITIVITY
private float mLastValues[] = new float[3 * 2];
private float mScale[] = new float[2];
private float mYOffset;
private static long end = 0;
private static long start = 0;
private float mLimit = 10;
private float mLastDirections[] = new float[3 * 2];
private float mLastExtremes[][] = { new float[3 * 2], new float[3 * 2] };
private float mLastDiff[] = new float[3 * 2];
private int mLastMatch = -1;
public StepDetector(Context context) {
// TODO Auto-generated constructor stub
super();
int h = 480;
mYOffset = h * 0.5f;
mScale[0] = -(h * 0.5f * (1.0f / (SensorManager.STANDARD_GRAVITY * 2)));
mScale[1] = -(h * 0.5f * (1.0f / (SensorManager.MAGNETIC_FIELD_EARTH_MAX)));
}
public void setSensitivity(float sensitivity) {
mLimit = sensitivity; // 1.97 2.96 4.44 6.66 10.00 15.00 22.50 33.75 50.62
}
#Override
public void onSensorChanged(SensorEvent event) {
Log.d("AAA", "Sensor changed");
Sensor sensor = event.sensor;
// Log.i(Constant.STEP_DETECTOR, "onSensorChanged");
synchronized (this) {
if (sensor.getType() == Sensor.TYPE_ORIENTATION) {
} else {
int j = (sensor.getType() == Sensor.TYPE_ACCELEROMETER) ? 1 : 0;
if (j == 1) {
float vSum = 0;
for (int i = 0; i < 3; i++) {
final float v = mYOffset + event.values[i] * mScale[j];
vSum += v;
}
int k = 0;
float v = vSum / 3;
float direction = (v > mLastValues[k] ? 1: (v < mLastValues[k] ? -1 : 0));
if (direction == -mLastDirections[k]) {
// Direction changed
int extType = (direction > 0 ? 0 : 1); // minimum or
// maximum?
mLastExtremes[extType][k] = mLastValues[k];
float diff = Math.abs(mLastExtremes[extType][k]- mLastExtremes[1 - extType][k]);
if (diff > mLimit) {
boolean isAlmostAsLargeAsPrevious = diff > (mLastDiff[k] * 2 / 3);
boolean isPreviousLargeEnough = mLastDiff[k] > (diff / 3);
boolean isNotContra = (mLastMatch != 1 - extType);
if (isAlmostAsLargeAsPrevious && isPreviousLargeEnough && isNotContra) {
end = System.currentTimeMillis();
if (end - start > 500) {
Log.i("Step_Detector", "CURRENT_SETP:"
+ CURRENT_SETP);
CURRENT_SETP++;
mLastMatch = extType;
start = end;
}
} else {
mLastMatch = -1;
}
}
mLastDiff[k] = diff;
}
mLastDirections[k] = direction;
mLastValues[k] = v;
}
}
}
Log.d("sensorSteps", String.valueOf(CURRENT_SETP));
if(mStepsUpdater!=null){
mStepsUpdater.UpdateStepCount(CURRENT_SETP);
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
public static void callBackInit(StepCountManager stepCountManager) {
mStepsUpdater= stepCountManager;
}
}

If you want to keep your service running even if the app is killed, make sure to return START_STICKY in onStartCommand() as follows :
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// restart service every hour to get the current step count
((AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE))
.set(AlarmManager.RTC, System.currentTimeMillis() + AlarmManager.INTERVAL_HOUR,
PendingIntent.getService(getApplicationContext(), 2,
new Intent(this, SensorListener.class),
PendingIntent.FLAG_UPDATE_CURRENT));
return START_STICKY;
}

You need to start a Foreground Service.
This is my music player Foreground service code.
public class ForegroundService extends Service {
private static final String LOG_TAG = "ForegroundService";
String audioPath;
boolean audioPlayed = false;
MediaPlayer mp;
Thread backgroundThread;
#Override
public void onCreate() {
super.onCreate();
mp = MediaPlayer.create(this,R.raw.shapeofyou);
mp.setLooping(true);
backgroundThread = new Thread(new Runnable() {
#Override
public void run() {
playMusic();
}
});
}
private void playMusic() {
mp.start();
audioPlayed = true;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// audioPath = intent.getStringExtra("path");
if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
if (mp.isPlaying()){
Toast.makeText(this,"Already playing",Toast.LENGTH_SHORT).show();
} else {
backgroundThread.start();
}
Log.i(LOG_TAG, "Received Start Foreground Intent ");
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Intent previousIntent = new Intent(this, ForegroundService.class);
previousIntent.setAction(Constants.ACTION.PREV_ACTION);
PendingIntent ppreviousIntent = PendingIntent.getService(this, 0,
previousIntent, 0);
Intent playIntent = new Intent(this, ForegroundService.class);
playIntent.setAction(Constants.ACTION.PLAY_ACTION);
PendingIntent pplayIntent = PendingIntent.getService(this, 0,
playIntent, 0);
Intent nextIntent = new Intent(this, ForegroundService.class);
nextIntent.setAction(Constants.ACTION.NEXT_ACTION);
PendingIntent pnextIntent = PendingIntent.getService(this, 0,
nextIntent, 0);
Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.mipmap.ic_launcher);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("Music Player")
.setTicker("Music Player")
.setContentText("My Music")
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(
Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(pendingIntent)
.setOngoing(true)
.addAction(android.R.drawable.ic_menu_close_clear_cancel,
"Stop", ppreviousIntent)
.addAction(android.R.drawable.ic_media_play, "Play",
pplayIntent).build();
startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE,
notification);
} else if (intent.getAction().equals(Constants.ACTION.PREV_ACTION)) {
stopForeground(true);
stopSelf();
if (mp.isPlaying()) {
mp.release();
}
backgroundThread = null;
Log.i(LOG_TAG, "Clicked Previous");
} else if (intent.getAction().equals(Constants.ACTION.PLAY_ACTION)) {
if (audioPlayed) {
mp.pause();
audioPlayed = false;
} else {
mp.start();
audioPlayed = true;
}
Log.i(LOG_TAG, "Clicked Play");
} else if (intent.getAction().equals(Constants.ACTION.NEXT_ACTION)) {
Log.i(LOG_TAG, "Clicked Next");
} else if (intent.getAction().equals(
Constants.ACTION.STOPFOREGROUND_ACTION)) {
Log.i(LOG_TAG, "Received Stop Foreground Intent");
stopForeground(true);
stopSelf();
if (mp.isPlaying()) {
mp.release();
}
backgroundThread = null;
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(LOG_TAG, "In onDestroy");
}
#Override
public IBinder onBind(Intent intent) {
// Used only in case of bound services.
return null;
}
}

return START_STICKY;
to automatically restart the service when it gets killed for some reasons like low memory.

Related

Handling Multiple Downloads With Notifications Using Retrofit Library

I'm following a tutorial to download files using the Retrofit library.
My app's UI has several different buttons which download different files using the above method. The problem is when someone presses another button after pressing the first, it's queued and starts after the first finishes. I want it to start right away simultaneously.
Here's the code for the DownloadService:
public class DownloadService extends IntentService {
public DownloadService() {
super("Download Service");
}
private int totalFileSize;
private NotificationCompat.Builder notificationBuilder;
private NotificationManager notificationManager;
#Override
protected void onHandleIntent(Intent intent) {
MyApp x = (MyApp)getApplicationContext();
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_file_download_deep_orange_a400_18dp)
.setContentTitle("Downloading")
.setContentText("Please wait...")
.setAutoCancel(true);
notificationManager.notify(x.ID, notificationBuilder.build());
Log.i("Paras", "onHandleIntent: " + x.filename + x.url);
initDownload(x.filename,x.url,x.ID);
}
private void initDownload(String filename, String url, int id) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://dl.dropboxusercontent.com/")
.build();
RequestInterface.RetrofitInterface retrofitInterface = retrofit.create(RequestInterface.RetrofitInterface.class);
Call<ResponseBody> request = retrofitInterface.downloadFile(url);
try {
downloadFile(request.execute().body(),filename,id);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private void downloadFile(ResponseBody body, String filename,int id) throws IOException {
int count;
byte data[] = new byte[1024 * 4];
long fileSize = body.contentLength();
InputStream bis = new BufferedInputStream(body.byteStream(), 1024 * 8);
File outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename);
OutputStream output = new FileOutputStream(outputFile);
long total = 0;
long startTime = System.currentTimeMillis();
int timeCount = 1;
while ((count = bis.read(data)) != -1) {
total += count;
totalFileSize = (int) (fileSize / (Math.pow(1, 2))) / 1000;
double current = Math.round(total / (Math.pow(1, 2))) / 1000;
int progress = (int) ((total * 100) / fileSize);
long currentTime = System.currentTimeMillis() - startTime;
Download download = new Download();
download.setTotalFileSize(totalFileSize);
if (currentTime > 1000 * timeCount) {
download.setCurrentFileSize((int) current);
download.setProgress(progress);
sendNotification(download,id);
timeCount++;
}
output.write(data, 0, count);
}
onDownloadComplete(filename,id);
output.flush();
output.close();
bis.close();
}
private void sendNotification(Download download, int id) {
sendIntent(download);
notificationBuilder.setProgress(100, download.getProgress(), false);
notificationBuilder.setContentText("Downloading file " + download.getCurrentFileSize() + "/" + totalFileSize + " KB");
notificationManager.notify(id, notificationBuilder.build());
}
private void sendIntent(Download download) {
Intent intent = new Intent(subject.MESSAGE_PROGRESS);
intent.putExtra("download", download);
LocalBroadcastManager.getInstance(DownloadService.this).sendBroadcast(intent);
}
private void onDownloadComplete(String filename,int id) {
try {
Download download = new Download();
download.setProgress(100);
sendIntent(download);
notificationManager.cancel(id);
notificationBuilder.setProgress(0, 0, false);
notificationBuilder.setContentText("Tap to open");
notificationManager.notify(id, notificationBuilder.build());
String path1 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + filename;
File file = new File(path1);
Uri uri_path = Uri.fromFile(file);
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension
(MimeTypeMap.getFileExtensionFromUrl(path1));
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.setType(mimeType);
intent.setDataAndType(uri_path, mimeType);
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
String string = filename;
notificationBuilder
.setContentIntent(pIntent)
.setAutoCancel(true)
.setContentTitle(string + " Downloaded");
Log.i("Paras", "onDownloadComplete: " + string);
notificationManager.notify(id, notificationBuilder.build());
} catch (Exception ex) {
}
}
#Override
public void onTaskRemoved(Intent rootIntent) {
}
}
Then I read about IntentService and Service classes. Do Service classes allow simultaneous downloads? I tried something like this:
public class DownloadService extends Service {
public DownloadService() {
super();
}
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
MyApp x = (MyApp)getApplicationContext();
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationBuilder = new NotificationCompat.Builder(getBaseContext())
.setSmallIcon(R.drawable.ic_file_download_deep_orange_a400_18dp)
.setContentTitle("Downloading")
.setContentText("Please wait...")
.setAutoCancel(true);
notificationManager.notify(x.ID, notificationBuilder.build());
Log.i("Paras", "onHandleIntent: " + x.filename + x.url);
initDownload(x.filename,x.url,x.ID);
}
}
#Override
public void onCreate() {
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block. We also make it
// background priority so CPU-intensive work will not disrupt our UI.
HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// For each start request, send a message to start a job and deliver the
// start ID so we know which request we're stopping when we finish the job
MyApp x = (MyApp)getApplicationContext();
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj= intent.putExtra("ID",x.ID);
mServiceHandler.sendMessage(msg);
// If we get killed, after returning from here, restart
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private int totalFileSize;
private NotificationCompat.Builder notificationBuilder;
private NotificationManager notificationManager;
private void initDownload(String filename, String url, int id) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://dl.dropboxusercontent.com/")
.build();
RequestInterface.RetrofitInterface retrofitInterface = retrofit.create(RequestInterface.RetrofitInterface.class);
Call<ResponseBody> request = retrofitInterface.downloadFile(url);
try {
downloadFile(request.execute().body(),filename,id);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private void downloadFile(ResponseBody body, String filename,int id) throws IOException {
int count;
byte data[] = new byte[1024 * 4];
long fileSize = body.contentLength();
InputStream bis = new BufferedInputStream(body.byteStream(), 1024 * 8);
File outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename);
OutputStream output = new FileOutputStream(outputFile);
long total = 0;
long startTime = System.currentTimeMillis();
int timeCount = 1;
while ((count = bis.read(data)) != -1) {
total += count;
totalFileSize = (int) (fileSize / (Math.pow(1, 2))) / 1000;
double current = Math.round(total / (Math.pow(1, 2))) / 1000;
int progress = (int) ((total * 100) / fileSize);
long currentTime = System.currentTimeMillis() - startTime;
Download download = new Download();
download.setTotalFileSize(totalFileSize);
if (currentTime > 1000 * timeCount) {
download.setCurrentFileSize((int) current);
download.setProgress(progress);
sendNotification(download,id);
timeCount++;
}
output.write(data, 0, count);
}
onDownloadComplete(filename,id);
output.flush();
output.close();
bis.close();
}
private void sendNotification(Download download, int id) {
sendIntent(download);
notificationBuilder.setProgress(100, download.getProgress(), false);
notificationBuilder.setContentText("Downloading file " + download.getCurrentFileSize() + "/" + totalFileSize + " KB");
notificationManager.notify(id, notificationBuilder.build());
}
private void sendIntent(Download download) {
Intent intent = new Intent(subject.MESSAGE_PROGRESS);
intent.putExtra("download", download);
LocalBroadcastManager.getInstance(DownloadService.this).sendBroadcast(intent);
}
private void onDownloadComplete(String filename,int id) {
try {
Download download = new Download();
download.setProgress(100);
sendIntent(download);
notificationManager.cancel(id);
notificationBuilder.setProgress(0, 0, false);
notificationBuilder.setContentText("Tap to open");
notificationManager.notify(id, notificationBuilder.build());
String path1 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + filename;
File file = new File(path1);
Uri uri_path = Uri.fromFile(file);
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension
(MimeTypeMap.getFileExtensionFromUrl(path1));
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.setType(mimeType);
intent.setDataAndType(uri_path, mimeType);
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
String string = filename;
notificationBuilder
.setContentIntent(pIntent)
.setAutoCancel(true)
.setContentTitle(string + " Downloaded");
Log.i("Paras", "onDownloadComplete: " + string);
notificationManager.notify(id, notificationBuilder.build());
} catch (Exception ex) {
}
}
#Override
public void onTaskRemoved(Intent rootIntent) {
}
}
But it didn't work. Any clues what I should do? I'm ready to give more details if required.
Edit 1: DownloadService runs on a function "startDownload" which is executed by various buttons. As you can see in 2nd code, class Extends Service. There is one thread which handles all those button clicks. If you look in comments, it's suggested that I should use Service and different threads for all those clicks. Now how can I make so many threads programmatically. There are almost 40 buttons which make use of DownloadService.
Thanks to #Lxu, I have got it working. So IntentServiceis meant to do one task at a time and can't do multiple tasks simultaneously. We should use Serviceinstead. It allows multiple tasks to be performed simultaneously. We can create multiple threads inside the Service which will be executed simultaneously. My problem got solved by putting all the code of onCreate() to onStartCommand(). When a service is called for the first time, onCreate() is called and after that, it's not called anymore no matter how many times service is called. On every service call, onStartCommand() is executed which creates new thread every time. That's it.
Here's the complete code:
public class DownloadService extends Service {
public DownloadService() {
super();
}
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
int id1;
int id2;
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
MyApp x = (MyApp)getApplicationContext();
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.ic_file_download_deep_orange_a400_18dp)
.setContentTitle("Downloading")
.setContentText("Please wait...")
.setAutoCancel(true);
notificationManager.notify(x.ID, notificationBuilder.build());
Log.i("Paras", "onHandleIntent: " + x.filename + x.url + " " + x.ID);
initDownload(x.filename,x.url,x.ID);
}
}
#Override
public void onCreate() {
// Get the HandlerThread's Looper and use it for our Handler
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// For each start request, send a message to start a job and deliver the
// start ID so we know which request we're stopping when we finish the job
HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
MyApp x = (MyApp)getApplicationContext();
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
// If we get killed, after returning from here, restart
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private int totalFileSize;
private NotificationCompat.Builder notificationBuilder;
private NotificationManager notificationManager;
private void initDownload(String filename, String url, int id) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://dl.dropboxusercontent.com/")
.build();
RequestInterface.RetrofitInterface retrofitInterface = retrofit.create(RequestInterface.RetrofitInterface.class);
Call<ResponseBody> request = retrofitInterface.downloadFile(url);
try {
downloadFile(request.execute().body(),filename,id);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private void downloadFile(ResponseBody body, String filename,int id) throws IOException {
int count;
byte data[] = new byte[1024 * 4];
long fileSize = body.contentLength();
InputStream bis = new BufferedInputStream(body.byteStream(), 1024 * 8);
File outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename);
OutputStream output = new FileOutputStream(outputFile);
long total = 0;
long startTime = System.currentTimeMillis();
int timeCount = 1;
while ((count = bis.read(data)) != -1) {
total += count;
totalFileSize = (int) (fileSize / (Math.pow(1, 2))) / 1000;
double current = Math.round(total / (Math.pow(1, 2))) / 1000;
int progress = (int) ((total * 100) / fileSize);
long currentTime = System.currentTimeMillis() - startTime;
Download download = new Download();
download.setTotalFileSize(totalFileSize);
if (currentTime > 1000 * timeCount) {
download.setCurrentFileSize((int) current);
download.setProgress(progress);
sendNotification(download,id);
timeCount++;
}
output.write(data, 0, count);
}
onDownloadComplete(filename,id);
output.flush();
output.close();
bis.close();
}
private void sendNotification(Download download, int id) {
sendIntent(download,id);
notificationBuilder.setProgress(100, download.getProgress(), false)
.setContentTitle("Downloading");
notificationBuilder.setContentText("Downloading file " + download.getCurrentFileSize() + "/" + totalFileSize + " KB");
notificationManager.notify(id, notificationBuilder.build());
}
private void sendIntent(Download download, int id) {
Intent intent = new Intent(subject.MESSAGE_PROGRESS);
intent.putExtra("download", download);
LocalBroadcastManager.getInstance(DownloadService.this).sendBroadcast(intent);
}
private void onDownloadComplete(String filename,int id) {
try {
Download download = new Download();
download.setProgress(100);
sendIntent(download,id);
notificationManager.cancel(id);
notificationBuilder.setProgress(0, 0, false);
notificationBuilder.setContentText("Tap to open");
notificationManager.notify(id, notificationBuilder.build());
String path1 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + filename;
File file = new File(path1);
Uri uri_path = Uri.fromFile(file);
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension
(MimeTypeMap.getFileExtensionFromUrl(path1));
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.setType(mimeType);
intent.setDataAndType(uri_path, mimeType);
PendingIntent pIntent = PendingIntent.getActivity(this,(int) System.currentTimeMillis(), intent, 0);
String string = filename;
notificationBuilder
.setContentIntent(pIntent)
.setAutoCancel(true)
.setContentTitle(string + " Downloaded");
Log.i("Paras", "onDownloadComplete: " + string);
notificationManager.notify(id, notificationBuilder.build());
}catch (Exception ex){
}
}
#Override
public void onTaskRemoved(Intent rootIntent) {
}
}

Android UI freeze when service is downloading progress

I'm using the library bitcoinj to create a Android wallet. The case is that I want the blockchain to be downloaded in the background so that the user can start using the other features of the app, but when it starts the download and opens a new activity, the application freezes, you can't use anything, not even return to the previous screen. This is part of the code:
public class BitcoinService extends Service {
private final PeerDataEventListener blockchainDownloadListener = new AbstractPeerEventListener() {
private final long CALLBACK_TIME = 1000L;
private final AtomicLong lastMessageTime = new AtomicLong(0);
private int height;
private int blocksLeft;
private Block block;
#Override
public void onBlocksDownloaded(final Peer peer, final Block block, final FilteredBlock filteredBlock, final int blocksLeft) {
config.maybeIncrementBestChainHeightEver(blockChain.getChainHead().getHeight());
delayHandler.removeCallbacksAndMessages(null);
final long now = System.currentTimeMillis();
this.block = block;
this.height = (int) peer.getBestHeight() - blocksLeft;
this.blocksLeft = blocksLeft;
if (now - lastMessageTime.get() > CALLBACK_TIME) {
delayHandler.post(RUNNER);
} else {
delayHandler.postDelayed(RUNNER, CALLBACK_TIME);
}
}
private final Runnable RUNNER = new Runnable() {
#Override
public void run() {
notifyBlockchainProgress(height, (height + blocksLeft));
Log.e(TAG, "LAST_BLOCK=" + height + ", REMAINS=" + blocksLeft);
if (blocksLeft == 0) {
broadcastBlockchainDownloaded();
}
}
};
};
private final BroadcastReceiver connectivityReceiver = new BroadcastReceiver() {
#SuppressLint("Wakelock")
#Override
public void onReceive(final Context context, final Intent intent) {
Log.d(TAG, "acquiring wakelock");
wakeLock.acquire();
// consistency check
final int walletLastBlockSeenHeight = wallet.getLastBlockSeenHeight();
final int bestChainHeight = blockChain.getBestChainHeight();
if (walletLastBlockSeenHeight != -1 && walletLastBlockSeenHeight != bestChainHeight) {
final String message = "wallet/blockchain out of sync: " + walletLastBlockSeenHeight + "/" + bestChainHeight;
Log.e(TAG, message);
}
Log.i(TAG, "starting peergroup");
peerGroup = new PeerGroup(Constants.WALLET.NETWORK_PARAMETERS, blockChain);
peerGroup.setDownloadTxDependencies(false);
peerGroup.setUserAgent("TestWallet", "0.0.1");
peerGroup.setMaxConnections(6);
peerGroup.setConnectTimeoutMillis(15000);
peerGroup.setPeerDiscoveryTimeoutMillis(10000);
// start peergroup
peerGroup.startAsync();
peerGroup.startBlockChainDownload(blockchainDownloadListener);
}
};
private final Handler delayHandler = new Handler();
private PeerGroup peerGroup;
private WakeLock wakeLock;
private PeerConnectivityListener peerConnectivityListener;
private NotificationManager nm;
private Configuration config;
private Wallet wallet;
#Override
public void onCreate() {
wallet = new Wallet(Constants.WALLET.NETWORK_PARAMETERS);
nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
final String lockName = getPackageName() + " blockchain sync";
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, lockName);
config = Configuration.getInstance();
broadcastPeerState(0);
blockChainFile = Constants.WALLET.BLOCKCHAIN_FILE;
final boolean blockChainFileExists = blockChainFile.exists();
if (!blockChainFileExists) {
new File(Constants.WALLET.WALLET_PATH).mkdirs();
}
try {
blockStore = new SPVBlockStore(Constants.WALLET.NETWORK_PARAMETERS, blockChainFile);
blockStore.getChainHead(); // detect corruptions as early as possible
final long earliestKeyCreationTime = wallet.getEarliestKeyCreationTime();
if (!blockChainFileExists && earliestKeyCreationTime > 0){
try {
config.setDeletingBlockchain(true);
final long start = System.currentTimeMillis();
final InputStream checkpointsInputStream = getAssets().open("bitcoin/" + Constants.WALLET.CHECKPOINTS_FILENAME);
CheckpointManager.checkpoint(Constants.WALLET.NETWORK_PARAMETERS, checkpointsInputStream, blockStore, earliestKeyCreationTime);
Log.i(TAG, String.format("checkpoints loaded from '%1$s', took %2$dms", Constants.WALLET.CHECKPOINTS_FILENAME, System.currentTimeMillis() - start));
} catch (final IOException x) {
Log.e(TAG, "problem reading checkpoints, continuing without", x);
}
}
} catch (final BlockStoreException x) {
blockChainFile.delete();
final String msg = "blockstore cannot be created";
Log.e(TAG, msg, x);
}
try {
blockChain = new BlockChain(Constants.WALLET.NETWORK_PARAMETERS, walletHelper.getMainWallet(), blockStore);
} catch (final BlockStoreException x) {
throw new Error("blockchain cannot be created", x);
}
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
registerReceiver(connectivityReceiver, intentFilter); // implicitly start PeerGroup
}
#Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
Log.e(TAG, "onStartCommand");
...
return START_NOT_STICKY;
}
private void notifyBlockchainProgress(int progress, int max) {
boolean isCompleted = progress == max;
if (config.isDeletingBlockchain()) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
long percent = Math.round(Math.floor((progress * 100) / max));
mBuilder.setContentTitle("Blockchain download")
.setContentText(" Synchronization in progress - " + percent + "%")
.setSmallIcon(R.drawable.ic_logo_splash)
.setProgress(max, progress, false)
.setAutoCancel(false);
if (isCompleted) {
mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setProgress(0, 0, false)
.setAutoCancel(true)
.setContentText(getString(R.string.synchronization_completed));
config.setDeletingBlockchain(false);
}
Notification notif = mBuilder.build();
if (isCompleted) {
notif.flags = Notification.FLAG_FOREGROUND_SERVICE;
} else {
notif.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE;
}
nm.notify(2, notif);
}
}
public void broadcastBlockchainDownloaded() {
Intent i = new Intent(UiRefreshReceiver.REFRESH_UI);
LocalBroadcastManager.getInstance(this).sendBroadcast(i);
}
}
I used part of the code of the official project of the Android wallet
Service in android runs in UI thread. You need to put all the job into different thread inside your Service
You need to use IntentService for downloading process.
public class BitcoinService extends IntentService {
private final PeerDataEventListener blockchainDownloadListener = new AbstractPeerEventListener() {
private final long CALLBACK_TIME = 1000L;
private final AtomicLong lastMessageTime = new AtomicLong(0);
private int height;
private int blocksLeft;
private Block block;
#Override
public void onBlocksDownloaded(final Peer peer, final Block block, final FilteredBlock filteredBlock, final int blocksLeft) {
config.maybeIncrementBestChainHeightEver(blockChain.getChainHead().getHeight());
delayHandler.removeCallbacksAndMessages(null);
final long now = System.currentTimeMillis();
this.block = block;
this.height = (int) peer.getBestHeight() - blocksLeft;
this.blocksLeft = blocksLeft;
if (now - lastMessageTime.get() > CALLBACK_TIME) {
delayHandler.post(RUNNER);
} else {
delayHandler.postDelayed(RUNNER, CALLBACK_TIME);
}
}
private final Runnable RUNNER = new Runnable() {
#Override
public void run() {
notifyBlockchainProgress(height, (height + blocksLeft));
Log.e(TAG, "LAST_BLOCK=" + height + ", REMAINS=" + blocksLeft);
if (blocksLeft == 0) {
broadcastBlockchainDownloaded();
}
}
};
};
private final BroadcastReceiver connectivityReceiver = new BroadcastReceiver() {
#SuppressLint("Wakelock")
#Override
public void onReceive(final Context context, final Intent intent) {
Log.d(TAG, "acquiring wakelock");
wakeLock.acquire();
// consistency check
final int walletLastBlockSeenHeight = wallet.getLastBlockSeenHeight();
final int bestChainHeight = blockChain.getBestChainHeight();
if (walletLastBlockSeenHeight != -1 && walletLastBlockSeenHeight != bestChainHeight) {
final String message = "wallet/blockchain out of sync: " + walletLastBlockSeenHeight + "/" + bestChainHeight;
Log.e(TAG, message);
}
Log.i(TAG, "starting peergroup");
peerGroup = new PeerGroup(Constants.WALLET.NETWORK_PARAMETERS, blockChain);
peerGroup.setDownloadTxDependencies(false);
peerGroup.setUserAgent("TestWallet", "0.0.1");
peerGroup.setMaxConnections(6);
peerGroup.setConnectTimeoutMillis(15000);
peerGroup.setPeerDiscoveryTimeoutMillis(10000);
// start peergroup
peerGroup.startAsync();
peerGroup.startBlockChainDownload(blockchainDownloadListener);
}
};
private final Handler delayHandler = new Handler();
private PeerGroup peerGroup;
private WakeLock wakeLock;
private PeerConnectivityListener peerConnectivityListener;
private NotificationManager nm;
private Configuration config;
private Wallet wallet;
#Override
protected void onHandleIntent(Intent intent) {
wallet = new Wallet(Constants.WALLET.NETWORK_PARAMETERS);
nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
final String lockName = getPackageName() + " blockchain sync";
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, lockName);
config = Configuration.getInstance();
broadcastPeerState(0);
blockChainFile = Constants.WALLET.BLOCKCHAIN_FILE;
final boolean blockChainFileExists = blockChainFile.exists();
if (!blockChainFileExists) {
new File(Constants.WALLET.WALLET_PATH).mkdirs();
}
try {
blockStore = new SPVBlockStore(Constants.WALLET.NETWORK_PARAMETERS, blockChainFile);
blockStore.getChainHead(); // detect corruptions as early as possible
final long earliestKeyCreationTime = wallet.getEarliestKeyCreationTime();
if (!blockChainFileExists && earliestKeyCreationTime > 0){
try {
config.setDeletingBlockchain(true);
final long start = System.currentTimeMillis();
final InputStream checkpointsInputStream = getAssets().open("bitcoin/" + Constants.WALLET.CHECKPOINTS_FILENAME);
CheckpointManager.checkpoint(Constants.WALLET.NETWORK_PARAMETERS, checkpointsInputStream, blockStore, earliestKeyCreationTime);
Log.i(TAG, String.format("checkpoints loaded from '%1$s', took %2$dms", Constants.WALLET.CHECKPOINTS_FILENAME, System.currentTimeMillis() - start));
} catch (final IOException x) {
Log.e(TAG, "problem reading checkpoints, continuing without", x);
}
}
} catch (final BlockStoreException x) {
blockChainFile.delete();
final String msg = "blockstore cannot be created";
Log.e(TAG, msg, x);
}
try {
blockChain = new BlockChain(Constants.WALLET.NETWORK_PARAMETERS, walletHelper.getMainWallet(), blockStore);
} catch (final BlockStoreException x) {
throw new Error("blockchain cannot be created", x);
}
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
registerReceiver(connectivityReceiver, intentFilter); // implicitly start PeerGroup
}
private void notifyBlockchainProgress(int progress, int max) {
boolean isCompleted = progress == max;
if (config.isDeletingBlockchain()) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
long percent = Math.round(Math.floor((progress * 100) / max));
mBuilder.setContentTitle("Blockchain download")
.setContentText(" Synchronization in progress - " + percent + "%")
.setSmallIcon(R.drawable.ic_logo_splash)
.setProgress(max, progress, false)
.setAutoCancel(false);
if (isCompleted) {
mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setProgress(0, 0, false)
.setAutoCancel(true)
.setContentText(getString(R.string.synchronization_completed));
config.setDeletingBlockchain(false);
}
Notification notif = mBuilder.build();
if (isCompleted) {
notif.flags = Notification.FLAG_FOREGROUND_SERVICE;
} else {
notif.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE;
}
nm.notify(2, notif);
}
}
}
Hope this will help you.

Android Widget Works in Lollipop, but NOT in KitKat

I have a clock widget that updates every minute. It renders a bitmap and replaces an imageview. This is to use a custom font in a widget. Below I showed the important pieces of my code. My problem is that the widget is there, but nothing shows up. I can still tap the widget to bring up the settings, so I know it's there. It's like the service update isn't working correctly in Kitkat but it does in Lollipop. Any suggestions?
public class DigitalClockWidget_2x1 extends AppWidgetProvider {
public RemoteViews mRemoteViews;
static String APP_SETTINGS = "8BitSettings";
#Override
public void onEnabled(Context context) {
super.onEnabled(context);
context.startService(new Intent(UpdateTimeService.UPDATE_TIME));
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
mRemoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
Intent LaunchIntent = getLaunchIntent(context);
PendingIntent clickPendIntent = PendingIntent.getActivity(context, 0, LaunchIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mRemoteViews.setOnClickPendingIntent(R.id.widget_root, clickPendIntent);
ComponentName componentName = new ComponentName(context.getPackageName(),DigitalClockWidget_2x1.class.getName());
appWidgetManager.updateAppWidget(componentName, mRemoteViews);
context.startService(new Intent(UpdateTimeService.UPDATE_TIME));
}
public static Intent getLaunchIntent(Context context){
SharedPreferences clockSettings = context.getSharedPreferences("ClockSettings", 0);
String launchString = clockSettings.getString("tappedAction", APP_SETTINGS);
if(launchString.compareTo(APP_SETTINGS) == 0){
return new Intent(context, SettingsPage.class);
}
return context.getPackageManager().getLaunchIntentForPackage(launchString);
}
public static final class UpdateTimeService extends Service {
static final String UPDATE_TIME = "org.penguinproductions.eight_bit_clock.action.UPDATE_TIME_2x1";
RemoteViews mRemoteViews;
private Calendar mCalendar;
private final static IntentFilter mIntentFilter = new IntentFilter();
int textColor = 0;
boolean tweentyfourHour = false;
SharedPreferences clockSettings;
String APP_SETTINGS = "8BitSettings";
static {
mIntentFilter.addAction(Intent.ACTION_TIME_TICK);
mIntentFilter.addAction(Intent.ACTION_TIME_CHANGED);
mIntentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
}
#Override
public void onCreate() {
super.onCreate();
mCalendar = Calendar.getInstance();
registerReceiver(mTimeChangedReceiver, mIntentFilter);
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mTimeChangedReceiver);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (intent != null) {
if (UPDATE_TIME.equals(intent.getAction())) {
updateTime();
}
}
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private final BroadcastReceiver mTimeChangedReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateTime();
}
};
private void updateTime() {
mCalendar.setTimeInMillis(System.currentTimeMillis());
mRemoteViews = new RemoteViews(getPackageName(), R.layout.widget);
String date = DateFormat.format(getString(R.string.date_format), mCalendar).toString();
mRemoteViews.setImageViewBitmap(R.id.imageView_txt, buildUpdate(getTodaysTime(), mCalendar.get(Calendar.AM_PM), date));
ComponentName mComponentName = new ComponentName(this, DigitalClockWidget_2x1.class);
AppWidgetManager mAppWidgetManager = AppWidgetManager.getInstance(this);
mAppWidgetManager.updateAppWidget(mComponentName, mRemoteViews);
Intent LaunchIntent = getLaunchIntent(getBaseContext());
PendingIntent clickPendIntent = PendingIntent.getActivity(getBaseContext(), 0, LaunchIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mRemoteViews.setOnClickPendingIntent(R.id.widget_root, clickPendIntent);
mAppWidgetManager = AppWidgetManager.getInstance(getBaseContext());
mAppWidgetManager.updateAppWidget(mComponentName, mRemoteViews);
}
}
EDIT:
The issue seems to have to do with the Bitmap rendering. I replaced the imageview with a textview and it worked. So the Bitmap isn't displaying in KitKat, but it does in Lollipop
public Bitmap buildUpdate(String time, int AMPM, String date) {
Log.v("Penguin", "Building time string:" + time);
clockSettings = this.getSharedPreferences("ClockSettings", 0);
boolean showDate = clockSettings.getBoolean("showDate", true);
boolean showampm = clockSettings.getBoolean("ampm", true);
boolean leading0 = clockSettings.getBoolean("leading0", true);
textColor = clockSettings.getInt("clockColor", Color.WHITE);
int dateColor = clockSettings.getInt("dateColor", Color.WHITE);
Bitmap myBitmap = Bitmap.createBitmap(2500, 1100, Bitmap.Config.ARGB_8888);
int fontSize = 425;
Canvas myCanvas = new Canvas(myBitmap);
Paint paint = new Paint();
Typeface clock = Typeface.createFromAsset(this.getAssets(), "fonts/PressStart2P.ttf");
paint.setAntiAlias(true);
paint.setSubpixelText(true);
paint.setTypeface(clock);
paint.setStyle(Paint.Style.FILL);
paint.setColor(textColor);
paint.setTextSize(fontSize);
paint.setTextAlign(Paint.Align.CENTER);
myCanvas.drawText(time, myBitmap.getWidth() / 2, fontSize+200, paint);
paint.setTextSize(100);
if(showampm) {
// alert("AMPM");
String ampm = "AM";
if (AMPM == 1) ampm = "PM";
myCanvas.drawText(ampm, (myBitmap.getWidth() / 2) + ((time.length() * fontSize) / 2) + 100, 300, paint);
}
paint.setTextSize(125);
if(showDate) {
paint.setColor(dateColor);
myCanvas.drawText(date, myBitmap.getWidth() / 2, (myBitmap.getHeight() / 2 + 400), paint);
}
return myBitmap;
}
So the issue was that the size limit for my older phone running KitKat only allows for texture sizes no bigger than 2048x2048 pixels. My bitmap was 2500x1100, so scaling it down has fixed the issue

How to make custom notification large icon in android

I am going to make custom notification bar. But not great.
I would like to create an Large icon.
remoteViews = new RemoteViews(getPackageName(), R.layout.widget_main);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setContentTitle("Title")
.setTicker("Ticker")
.setSmallIcon(R.mipmap.howlong)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.howlong))//I dot understand why entering this icon.
.setContent(remoteViews).setOngoing(true);
This my code.
https://www.dropbox.com/s/njywqp5s5swtfdd/img.jpg?dl=0
This my notification state.
How can I have put the Large icon?
------------------------------------add code-------------------------------
package com.example.namsoo.mynotificationpractice5;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.widget.RemoteViews;
import android.widget.Toast;
/**
* Created by namsoo on 2015-07-22.
*/
/*
Add code for manifest
<service android:name=".WidgetService"
android:enabled="true"
android:exported="true" >
</service>
*/
/*
Add code for MainActivity.onCreate
Intent widgetIntent = new Intent(this, WidgetService.class);
startService(widgetIntent);
*/
public class WidgetService extends Service {
RemoteViews remoteViews;
NotificationManager notificationManager;
int NOTIFICATION_ID = 111;
int INITIAL_VALUE = 0;//초기값
int FUNCTION_ON =1;//ON
int FUNCTION_OFF =2;//OFF
int functionFlag = 0;//0 = 초기 1 = ON 2 = OFF
#Override
public void onCreate() {
Toast.makeText(getApplicationContext(), "Start Widget Service", Toast.LENGTH_LONG).show();
startWidget();
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
remoteViews = new RemoteViews(getPackageName(), R.layout.widget_main);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String btn = intent.getStringExtra("btn");
if (btn != null)
{
if (btn.equals("state"))
{
//function code or Value redirects.
startWidget();
Toast.makeText(getApplicationContext(), "btn : " + btn + startId + " " + flags, Toast.LENGTH_LONG).show();
}
else if (btn.equals("exit"))
{
Toast.makeText(getApplicationContext(), "btn : " + btn + startId + " " + flags, Toast.LENGTH_LONG).show();
notificationManager.cancelAll();
stopService(intent);
System.exit(1);
}
else
{
Toast.makeText(getApplicationContext(), "not null btn : " + btn, Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getApplicationContext(), " null btn", Toast.LENGTH_LONG).show();
}
return super.onStartCommand(intent, flags, startId);
}//서비스 실행
public void startWidget() {
if (functionFlag != INITIAL_VALUE) {
remoteViews.removeAllViews(R.id.widgetLayout);
}//노피티케이션 뷰 삭제(처음이 아닐때만 실행)
remoteViews = new RemoteViews(getPackageName(), R.layout.widget_main);//뷰 추가
setWidgetButtonListeners();//버튼이벤트 추가
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContent(remoteViews).setOngoing(true);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, MainActivity.class);
resultIntent.addFlags(resultIntent.FLAG_ACTIVITY_NEW_TASK | resultIntent.FLAG_ACTIVITY_SINGLE_TOP);//화면이 없는 상태에서 만들어주는 플래그 || 화면이 있으면 화면을 재사용하세요.
PendingIntent resultPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, resultIntent, 0);
// start the activity when the user clicks the notification text
mBuilder.setContentIntent(resultPendingIntent).setAutoCancel(false);
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// pass the Notification object to the system
notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
public void setWidgetButtonListeners() {
if (functionFlag == INITIAL_VALUE) {
remoteViews.setImageViewResource(R.id.btnState, android.R.drawable.ic_media_pause);
remoteViews.setTextViewText(R.id.tv, "On~~");
functionFlag = FUNCTION_ON;
} else if (functionFlag == FUNCTION_ON)//On 일 때
{
remoteViews.setImageViewResource(R.id.btnState, android.R.drawable.ic_media_play);
remoteViews.setTextViewText(R.id.tv, "Off~~");
functionFlag = FUNCTION_OFF;
} else if (functionFlag == FUNCTION_OFF)//Off 일 때
{
remoteViews.setImageViewResource(R.id.btnState, android.R.drawable.ic_media_pause);
remoteViews.setTextViewText(R.id.tv, "On");
functionFlag = FUNCTION_ON;
}//버튼과 텍스트의 값 변경
Intent intentBtnState = new Intent(getApplicationContext(), this.getClass());
intentBtnState.putExtra("btn", "state");
PendingIntent piState = PendingIntent.getService(getApplicationContext(), R.id.btnState, intentBtnState, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.btnState, piState);
Intent intentBtnExit = new Intent(getApplicationContext(), this.getClass());
intentBtnExit.putExtra("btn", "exit");
PendingIntent piExit = PendingIntent.getService(getApplicationContext(), R.id.btnExit, intentBtnExit, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.btnExit, piExit);
//이벤트 추가
}
#Override
public void onDestroy() {
Toast.makeText(getApplicationContext(), "Destroy", Toast.LENGTH_LONG).show();
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
private Bitmap getCircleBitmap(Bitmap bitmap) {
final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(output);
final int color = Color.RED;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawOval(rectF, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
bitmap.recycle();
return output;
}

Android mediaplayer volume change issues after phone call

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);
}
}
}
}

Categories

Resources