Android app running after locking screen - android

Hello I am new to android programming. I am writing an app for school and I need to save Accelerometer data to a txt file.
The problem is that when I lock screen or turn screen saving on, the data recording stops.
Can you please give me advice ?
Here is my code:
package emzet.data2text;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.view.View;
import android.widget.Button;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor accelerometer;
private FileWriter writer;
private Button btnStart, btnStop;
String root = Environment.getExternalStorageDirectory().toString();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart = (Button) findViewById(R.id.btnStart);
btnStop = (Button) findViewById(R.id.btnStop);
btnStart.setEnabled(true);
btnStop.setEnabled(true);
//PowerManager mgr = (PowerManager)this.getSystemService(Context.POWER_SERVICE);
//PowerManager.WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "MyWakeLock");
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
public void onStartClick(View view) {
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
btnStop.setEnabled(true);
btnStart.setEnabled(false);
}
public void onStopClick(View view) {
sensorManager.unregisterListener(this);
btnStart.setEnabled(true);
btnStop.setEnabled(false);
}
protected void onResume() {
super.onResume();
try {
writer = new FileWriter(root + "/acc2txt-file.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
}
protected void onPause() {
super.onPause();
if(writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
SimpleDateFormat time = new SimpleDateFormat("HH:mm:ss:SSS");
String s = time.format(new java.util.Date());
try {
writer.write(s+"\t"+x+"\t"+y+"\t"+z+"\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}

if you want to save data in app stop as well, you can write a service with START_STICKY option , then the service stays active even if the app is killed. Here is example of STICKY Service, it is easy and would fit your needs example 1 example 2
public class MyService extends Service {
protected String messageData = null;
public static final int MSG_REGISTER_CLIENT = 1;
public static final int MSG_UNREGISTER_CLIENT = 2;
public static final int MSG_CUSTOM_TYPE = 3;
#Override public void onCreate() {
super.onCreate();
MyServiceRunningBackground();
running = true;
}
#Override public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
#Override public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
#Override public void onRebind(Intent intent) {
super.onRebind(intent);
}
#Override public void onDestroy() {
super.onDestroy();
running = false;
}
private void MyServiceRunningBackground() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
final int restartAlarmInterval = 6000;
final int resetAlarmTimer = 2*1000;
final Intent restartIntent = new Intent(this, esService.class);
restartIntent.putExtra("ALARM_RESTART_SERVICE_DIED", true);
final AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Handler restartServiceHandler = new Handler()
{
#Override
public void handleMessage(Message msg) {
PendingIntent pintent = PendingIntent.getService(getApplicationContext(), 0, restartIntent, 0);
alarmMgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + restartAlarmInterval, pintent);
sendEmptyMessageDelayed(0, resetAlarmTimer);
}
};
restartServiceHandler.sendEmptyMessageDelayed(0, 0);
}
}
private static final String TAG = "MyService";
}
create this new service and do what work you want to perform in your case saving data in background of your app, even if you app is killed, just start this service like you open new intent in your onCreate of activity. After that this service will be active even user kills app. Start this service like this
Intent intent = new Intent(MyActivity.this, MyService.class);
startService(intent);
I hope I am clear

Related

How to show UI from Notification

I'm trying to make a simple musicPlayer that works on Android device.To make Background-play come true, I'm using Service class.
What I want to do is below:
1.User launches app and taps start button
2.Music starts and Notification that notes the Music is playing appears
3.User taps home button and the app's UI disappears
4.Music doesn't stop
5.User tap Notification
6.UI appears with disabled start button and enabled stop button ← I'm in trouble
With My Code, UI appears. But it is not the UI which user made to disappear. How do I describe...It is new-ed UI.
So when user taps stop button,of course music doesn't stop. The Service is different one.
I want music to stop.
Is there any way to show the first created UI? the original UI?
If there's no way to show first created UI,how can I reach to first running service?
Thank you for browsing.
My Activity
package com.websarva.wings.android.servicesample;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements ServiceConnection {
public static final String LOG_TAG = "ServiceSample:";
private Intent _intent;
public static final String INTENT_ACTION = "intentAction";
private ServiceConnection _connection = new ServiceConnection(){
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
}
#Override
public void onServiceDisconnected(ComponentName name) {
}
};
public void onPlayButtonClick(View view){
Log.e(LOG_TAG,
"#onPlayButtonClick -_intentHash - " + _intent.hashCode()
+ "-_connectionHash" + _connection.hashCode());
bindService(_intent, _connection,Context.BIND_AUTO_CREATE);
startService(_intent);
Button btPlay = findViewById(R.id.btPlay);
btPlay.setEnabled(false);
Button btStop = findViewById(R.id.btStop);
btStop.setEnabled(true);
}
public void onStopButtonClick(View view){
Log.e(LOG_TAG,
"#onStopButtonClick -_intentHash - " + _intent.hashCode()
+ "-_connectionHash" + _connection.hashCode());
unbindService(_connection);
stopService(_intent);
Button btStop = findViewById(R.id.btStop);
btStop.setEnabled(false);
Button btPlay = findViewById(R.id.btPlay);
btPlay.setEnabled(true);
}
private BroadcastReceiver _MessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Button btStop = findViewById(R.id.btStop);
btStop.setEnabled(false);
Button btPlay = findViewById(R.id.btPlay);
btPlay.setEnabled(true);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocalBroadcastManager.getInstance(this).registerReceiver(_MessageReceiver,new IntentFilter(INTENT_ACTION));
_intent = getIntent();
boolean isAlreadyPlaying = _intent.getBooleanExtra(SoundManageService.EXTRA_KEY_ISPLAYING,false);
if(isAlreadyPlaying){
Button btPlay = findViewById(R.id.btPlay);
btPlay.setEnabled(false);
Button btStop = findViewById(R.id.btStop);
btStop.setEnabled(true);
}
_intent = new Intent(MainActivity.this,SoundManageService.class);
bindService(_intent, _connection,Context.BIND_AUTO_CREATE);
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
}
#Override
public void onServiceDisconnected(ComponentName name) {
}
#Override
public void onDestroy(){
LocalBroadcastManager.getInstance(this).unregisterReceiver(_MessageReceiver);
super.onDestroy();
}
}
My Service
package com.websarva.wings.android.servicesample;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import androidx.lifecycle.LifecycleService;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import java.io.IOException;
public class SoundManageService extends LifecycleService{
public static final String CHANNEL_ID = "soundmanagerservice_notification_channel";
public static final int FINISH_NOTIFICATION_ID = 2;
public static final int START_NOTIFICATION_ID = 1;
public static final String EXTRA_KEY_ISPLAYING = "isPlaying";
MediaPlayer _player;
public SoundManageService() {
}
private class PlayerPreparedListener implements MediaPlayer.OnPreparedListener{
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
NotificationCompat.Builder builder = new NotificationCompat.Builder(SoundManageService.this,CHANNEL_ID);
builder.setSmallIcon(android.R.drawable.ic_dialog_info);
builder.setContentTitle(getString(R.string.msg_notification_title_start));
builder.setContentText(getString(R.string.msg_notification_text_start));
Intent intent = new Intent(SoundManageService.this,MainActivity.class);
intent.putExtra(EXTRA_KEY_ISPLAYING,mp.isPlaying());
PendingIntent stopServiceIntent = PendingIntent.getActivity(
SoundManageService.this,0,intent,PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(stopServiceIntent);
builder.setAutoCancel(true);
Notification notification = builder.build();
startForeground(START_NOTIFICATION_ID,notification);
}
}
private class PlayerCompletionListener implements MediaPlayer.OnCompletionListener{
#Override
public void onCompletion(MediaPlayer mp) {
stopSelf();
sendMessage();
}
}
private void sendMessage() {
Intent intent = new Intent(MainActivity.INTENT_ACTION);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
#Override
public void onCreate(){
super.onCreate();
_player = new MediaPlayer();
String channelName = getString(R.string.notification_channnel_name);
int notificationImportance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID,channelName,notificationImportance);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(notificationChannel);
}
#Override
public int onStartCommand(Intent intent,int flags,int startId){
super.onStartCommand(intent,flags,startId);
String mediaUriStr ="android.resource://" + getPackageName() + "/" + R.raw.testmusic;
Uri uri = Uri.parse(mediaUriStr);
_player = new MediaPlayer();
try{
_player.setDataSource(SoundManageService.this,uri);
_player.setOnPreparedListener(new PlayerPreparedListener());
_player.setOnCompletionListener(new PlayerCompletionListener());
_player.prepareAsync();
} catch (IOException e) {
Log.e("ServiceSample", "メディアプレーヤー準備失敗");
}
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
super.onBind(intent);
return null;
}
#Override
public boolean onUnbind(Intent intent){
return true;
}
#Override
public void onDestroy(){
if(_player.isPlaying()){
_player.stop();
}
_player.release();
_player = null;
super.onDestroy();
}
}
Changing the code (creating Intent for PendingIntent for Notification)
Intent intent = new Intent(SoundManageService.this,MainActivity.class);
to
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setClassName(getApplicationContext().getPackageName(), MainActivity.class.getName());
intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_NEW_TASK);
made the problem solved.
https://qiita.com/imp954sti/items/e075fb8a99b68dda8180
↑this Japanese note helped me.

Activity doesnt mantain connection to its service after minimalising it

I have a problem with an activity after minimalising. Everything is going ok when i start an activity and press start button. But when i minimalise activity and again maximalize it, it doesnt respond to my buttons and commands. Anybody know what to do? This is my first android app so i dont know what is going on..
here are my classes :
TrackerService
package sk.tuke.smart.makac.services;
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
public class TrackerService extends Service implements LocationListener {
private Intent commandIntent;
private long duration;
private boolean paused,checkedAfterPause;
private int sportActivity;
private double distance,pace,calories;
private ArrayList<Location> finalPositionList = new ArrayList<Location>();
private LocationManager locationManager;
private static final String TAG = "TrackerService";
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.i(TAG,"onStart intent " +intent.getAction());
commandIntent=intent;
checkedAfterPause=true;
if(intent.getAction() == "sk.tuke.smart.makac.COMMAND_START"){
if(intent.getAction() == "sk.tuke.smart.makac.COMMAND_START") {
duration = 0;
}
new Timer().scheduleAtFixedRate(new TimerTask()
{
#Override
public void run() {
if(!paused){
duration++;
Intent intent1 = new Intent();
intent1.setAction("sk.tuke.smart.makac.TICK");
intent1.putExtra("duration", duration);
intent1.putExtra("distance",distance);
sendBroadcast(intent1);
Log.i(TAG,"" + duration);
}
}
}, 1000, 1000);
}else if (intent.getAction() == "sk.tuke.smart.makac.COMMAND_PAUSE"){
paused=true;
locationManager.removeUpdates(this);
}
if(intent.getAction() == "sk.tuke.smart.makac.COMMAND_CONTINUE"){
paused=false;
checkedAfterPause=false;
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,10,this);
}
}
#Override
public void onCreate() {
super.onCreate();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,10,this);
}
#Override
public void onDestroy() {
locationManager.removeUpdates(this);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onLocationChanged(Location location) {
finalPositionList.add(location);
Location lastLocation;
double minDistance;
if (finalPositionList.size() != 1 && checkedAfterPause) {
lastLocation = finalPositionList.get(finalPositionList.size() - 2);
minDistance=location.distanceTo(lastLocation);
if(minDistance>=2){
distance += location.distanceTo(lastLocation);
}else{
finalPositionList.remove(finalPositionList.size()-1);
}
}
if(commandIntent.getAction() == "sk.tuke.smart.makac.COMMAND_CONTINUE" && !checkedAfterPause){
Log.i(TAG,"checking distance after pause");
lastLocation = finalPositionList.get(finalPositionList.size() - 2);
minDistance=location.distanceTo(lastLocation);
if(minDistance<=100){
distance += location.distanceTo(lastLocation);
}
checkedAfterPause=true;
}
Log.i(TAG,"locations " + finalPositionList);
Log.i(TAG,"distance = " + distance);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
public long getDuration(){
return duration;
}
public double getPace(){
return pace;
}
}
SportsActivity
package sk.tuke.smart.makac;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import sk.tuke.smart.makac.helpers.MainHelper;
import sk.tuke.smart.makac.services.TrackerService;
public class StopwatchActivity extends AppCompatActivity {
private static final int MY_PERMISSIONS_REQUEST_FINE_LOCATION = 111;
private static final String TAG = "StopwatchActivity";
private boolean started;
private boolean running;
private boolean paused=false;
private long duration;
private double distance;
private MainHelper helper;
private TextView durationView,distanceView;
private Button startButton,endButton;
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction()=="sk.tuke.smart.makac.TICK"){
duration = intent.getLongExtra("duration",duration);
distance = intent.getDoubleExtra("distance",distance);
durationView.setText(helper.formatDuration(duration));
distanceView.setText(helper.formatDistance(distance));
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stopwatch);
IntentFilter intentFilter = new IntentFilter("sk.tuke.smart.makac.TICK");
registerReceiver(receiver,intentFilter);
started=false;
running=false;
helper = new MainHelper();
durationView = findViewById(R.id.textview_stopwatch_duration);
distanceView = findViewById(R.id.textview_stopwatch_distance);
startButton = findViewById(R.id.button_stopwatch_start);
endButton = findViewById(R.id.button_stopwatch_endworkout);
if(!canAccessLocation()){
ActivityCompat.requestPermissions(this,
new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_FINE_LOCATION);
}
}
public void toggle(View view){
Intent intent = new Intent(this,TrackerService.class);
started=true;
this.running = !this.running;
if(running && started){
startButton.setText("Stop");
endButton.setVisibility(view.GONE);
if(paused){
intent.setAction("sk.tuke.smart.makac.COMMAND_CONTINUE");
paused=false;
}else
intent.setAction("sk.tuke.smart.makac.COMMAND_START");
}
if(!running && started){
startButton.setText("Continue");
endButton.setVisibility(view.VISIBLE);
intent.setAction("sk.tuke.smart.makac.COMMAND_PAUSE");
paused=true;
}
startService(intent);
}
public void endWorkout(View view){
Intent intent = new Intent(this,TrackerService.class);
intent.setAction("sk.tuke.smart.makac.COMMAND_STOP");
startService(intent);
setContentView(R.layout.activity_workout_detail);
onStop();
}
public void openMaps(View view){
Intent intent = new Intent(StopwatchActivity.this, MapsActivity.class);
startActivity(intent);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
Intent intent= new Intent(this,TrackerService.class);
stopService(intent);
}
private boolean hasPermission(String perm) {
return(PackageManager.PERMISSION_GRANTED==checkSelfPermission(perm));
}
private boolean canAccessLocation() {
return(hasPermission(Manifest.permission.ACCESS_FINE_LOCATION));
}
}
You aren't creating a connection to the service. You're only starting it, not binding it. So there's no connection to maintain.
It looks like you're trying to do quasi-binding via actions. Don't do that, properly bind the service and avoid a whole raft of problems like this.

Is LocalBroadcastReceiver + IntentService the correct practice?

I am trying to understand how this stuff works a little better.
So I learned about Runnables and Threads and ASyncTasks but apparently they have some serious drawbacks when it comes to configuration changes like rotating the screen.
Is it better to instead use IntentService for anything that should run in the background like SQL database commands, file-system procedures, Internet input/output processes, etc -- and then use LocalBroadcastReceiver to pass results back to the Activity?
Is it better to instead use IntentService for anything that should run in the background like SQL database commands, file-system procedures, Internet input/output processes, etc -- and then use LocalBroadcastReceiver to pass results back to the Activity?
A service is needed if your UI might move to the background while the work is going on, and you are concerned that your process might be terminated while the work is going on. I tend to only worry about this if the work might exceed a second or so. Otherwise, a plain thread suffices.
Using an event bus, like LocalBroadcastManager, is a reasonable approach to let other components know when your service/thread is done with its work. This sample app demonstrates this. Personally, I tend to use greenrobot's EventBus — this sample app is a clone of the first one, but using EventBus instead of LocalBroadcastManager.
Follow an example of a chat using one activity (chat activity) that run a class in service (realtime class). I use a mvc webapi to controll chat between chatters. When realtime receive a message "onConnected" or "ReceivedMessageServer" automatically send by LocalBroadcastManager to chat activity. This way in "onReceive" from BroadcastReceiver receives the message and runs other tasks.
a) ChatActivity.class
package br.com.yourapp;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.Calendar;
import br.com.yourapp.model.MessageReceived;
import util.RealTime;
public class ChatActivity extends AppCompatActivity implements View.OnClickListener,
View.OnKeyListener , TextWatcher {
AppController obj;
private ProgressDialog pDialog;
MediaPlayer mp;
private ListView lstChatLog;
private ArrayAdapter<String> listAdapter;
private EditText txtChatMessage;
private TextView lblTyping;
private Button btnSendChat;
private boolean resultRequest = true;
private String errorMessage = "Internet is not working";
private AlertDialog alertDialog;
private AlertDialog.Builder alertBuilder;
String userType = "V";
String spaces = "\u0020\u0020\u0020\u0020";
Calendar time;
MessageReceived msg;
private RealTime realTime;
private final Context mContext = this;
private boolean mBound = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
showProgressDialog();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
obj = (AppController) getApplicationContext();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
lblTyping = (TextView) findViewById(R.id.lblTyping);
txtChatMessage = (EditText) findViewById(R.id.txtChatMessage);
txtChatMessage.setOnKeyListener(this);
txtChatMessage.addTextChangedListener(this);
btnSendChat = (Button) findViewById(R.id.btnSendChat);
btnSendChat.setOnClickListener(this);
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Alert");
alertBuilder = new AlertDialog.Builder(this);
lstChatLog = (ListView) findViewById(R.id.lstChatLog);
listAdapter = new ArrayAdapter<String>(ChatActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView tv = (TextView) view.findViewById(android.R.id.text1);
tv.setHeight(20);
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
return view;
}
};
Intent intent = new Intent();
intent.setClass(mContext, RealTime.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
IntentFilter filter = new IntentFilter("Connect");
filter.addAction("RecMsg");
LocalBroadcastManager.getInstance(ChatActivity.this).registerReceiver(mMessageReceiver, filter);
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().toString().equals("Connect")) {
msg = (MessageReceived) intent.getExtras().getParcelable("msg");
if (msg == null || msg.Message == null)
return;
listAdapter.add(msg.Destiny + "" + msg.CurrentTime + " : " + msg.Message);
lstChatLog.setAdapter(listAdapter);
realTime.SendToSpecific(msg.Sender, "Hi !", userType, obj.getRiderId(), obj.getDriverId());
hideProgressDialog();
}
else
if (intent.getAction().toString().equals("RecMsg")) {
msg = (MessageReceived) intent.getExtras().getParcelable("msg");
if (msg == null || msg.Message == null)
return;
if (msg.Message.equals("*0.+9=&!*#_&1|8%digi")) {
lblTyping.setVisibility(View.VISIBLE);
}
else
if (msg.Message.equals("*0.+9=&!*#_&1|8%"))
{
lblTyping.setVisibility(View.INVISIBLE);
}
else
{
lblTyping.setVisibility(View.INVISIBLE);
listAdapter.add(msg.Sender + "" + msg.CurrentTime + " : " + msg.Message);
lstChatLog.setAdapter(listAdapter);
mp = MediaPlayer.create(ChatActivity.this, R.raw.notify);
mp.setLooping(false);
mp.setVolume(100, 100);
mp.start();
}
}
}
};
private final ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
RealTime.LocalBinder binder = (RealTime.LocalBinder) service;
realTime = binder.getService();
mBound = true;
realTime.Connect(obj.getRiderName(), userType, obj.getRiderId(), obj.getLatitudeRider(), obj.getLongitudeRider(), obj.getDriverId(), obj.getVehicieId());
hideProgressDialog();
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
#Override
protected void onStop() {
if (mBound) {
unbindService(mConnection);
mBound = false;
}
super.onStop();
}
public void SendToSpecific(String sender, String message, String userType, long userId, long operatorId) {
realTime.SendToSpecific(sender, message, userType, userId,operatorId);
if (!message.equals("*0.+9=&!*#_&1|8%digi") && !message.equals("*0.+9=&!*#_&1|8%"))
{
time = Calendar.getInstance();
listAdapter.add(spaces + sender + " " + "(" + time.get(Calendar.HOUR) + ":" + time.get(Calendar.MINUTE) + ")" + " : " + message);
lstChatLog.setAdapter(listAdapter);
txtChatMessage.setText("");
}
}
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode==KeyEvent.KEYCODE_ENTER) {
if (txtChatMessage.getText().length() > 0)
{
InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.
INPUT_METHOD_SERVICE);
if (this.getCurrentFocus() != null)
imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
SendToSpecific(obj.getRiderName(), txtChatMessage.getText().toString(), userType, obj.getRiderId(), obj.getDriverId());
}
}
return false;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (txtChatMessage.getText().toString().length() > 0) {
if (txtChatMessage.getText().length() == 1) {
SendToSpecific(obj.getRiderName(), "*0.+9=&!*#_&1|8%digi", userType, obj.getRiderId(), obj.getDriverId());
}
} else {
SendToSpecific(obj.getRiderName(), "*0.+9=&!*#_&1|8%", userType, obj.getRiderId(), obj.getDriverId());
}
}
#Override
public void afterTextChanged(Editable s) {
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSendChat:
if (txtChatMessage != null && txtChatMessage.getText().length() > 0) {
InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.
INPUT_METHOD_SERVICE);
if (this.getCurrentFocus() != null)
imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
SendToSpecific(obj.getRiderName(), txtChatMessage.getText().toString(), userType, obj.getRiderId(), obj.getDriverId());
}
break;
}
}
private void showProgressDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideProgressDialog() {
if (pDialog.isShowing())
pDialog.hide();
}
#Override
protected void onDestroy() {
try {
if (pDialog != null && pDialog.isShowing())
pDialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
super.onDestroy();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.
INPUT_METHOD_SERVICE);
if (getCurrentFocus() != null)
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
mMessageReceiver.clearAbortBroadcast();
Intent i = new Intent(this, MenuPageActivity.class);
obj.setLastActivity("Chat");
startActivity(i);
return true;
}
public void ShowAlert() {
hideProgressDialog();
if (resultRequest)
errorMessage = "Internet is not working";
alertBuilder.setTitle("Alert");
alertBuilder.setMessage(errorMessage);
alertBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
arg0.dismiss();
}
});
alertDialog = alertBuilder.create();
alertDialog.show();
errorMessage = "";
resultRequest = true;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
}
b) Realtime.class
package util;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import java.util.concurrent.ExecutionException;
import br.com.yourapp.model.MessageReceived;
import microsoft.aspnet.signalr.client.Platform;
import microsoft.aspnet.signalr.client.SignalRFuture;
import microsoft.aspnet.signalr.client.http.android.AndroidPlatformComponent;
import microsoft.aspnet.signalr.client.hubs.HubConnection;
import microsoft.aspnet.signalr.client.hubs.HubProxy;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler1;
import microsoft.aspnet.signalr.client.transport.ClientTransport;
import microsoft.aspnet.signalr.client.transport.ServerSentEventsTransport;
public class RealTime extends Service {
private HubConnection mHubConnection;
private HubProxy mHubProxy;
private Handler mHandler;
private final IBinder mBinder = new LocalBinder();
public RealTime() { }
#Override
public void onCreate() {
super.onCreate();
mHandler = new Handler(Looper.getMainLooper());
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
int result = super.onStartCommand(intent, flags, startId);
startSignalR();
return result;
}
#Override
public void onDestroy() {
mHubConnection.stop();
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
startSignalR();
return mBinder;
}
public class LocalBinder extends Binder {
public RealTime getService() {
return RealTime.this;
}
}
public void Connect(String userName, String userType, long userId, double latitude, double longitude, long driverId, long vehicleId) {
mHubProxy.invoke("Connect", userName, userType, userId, latitude, longitude, driverId, vehicleId);
}
public void SendMessageToGroup(String userName, String userGroup, String userType, long userId, double latitude, double longitude, long vehicleId, short option)
{
mHubProxy.invoke("SendMessageToGroup", userName, userGroup, userType, userId, latitude, longitude, vehicleId, option);
}
public void SendToSpecific(String sender, String message, String userType, long userId, long operatorId)
{
mHubProxy.invoke("SendToSpecific", sender, message, userType, userId, operatorId);
}
private void startSignalR() {
Platform.loadPlatformComponent(new AndroidPlatformComponent());
mHubConnection = new HubConnection("http://webapi.com");
mHubProxy = mHubConnection.createHubProxy("ChatHub");
ClientTransport clientTransport = new ServerSentEventsTransport(mHubConnection.getLogger());
SignalRFuture<Void> signalRFuture = mHubConnection.start(clientTransport);
try {
signalRFuture.get();
} catch (InterruptedException | ExecutionException e) {
Log.e("SimpleSignalR", e.toString());
return;
}
mHubProxy.on("onConnected",
new SubscriptionHandler1<MessageReceived>() {
#Override
public void run(final MessageReceived msg) {
mHandler.post(new Runnable() {
#Override
public void run() {
Intent intent = new Intent("Connect");
intent.putExtra("msg", msg);
LocalBroadcastManager.getInstance(RealTime.this).sendBroadcast(intent);
}
});
}
}
, MessageReceived.class);
}
}
mHubProxy.on("ReceivedMessageServer",
new SubscriptionHandler1<MessageReceived>() {
#Override
public void run(final MessageReceived msg) {
mHandler.post(new Runnable() {
#Override
public void run() {
Intent intent = new Intent("RecMsg");
intent.putExtra("msg", msg);
LocalBroadcastManager.getInstance(RealTime.this).sendBroadcast(intent);
}
});
}
}
, MessageReceived.class);
}

start/stop button radio stream service

I have the code of a radio stream app from this site radio stream example, but when i want to stop the stream it restarts. The only way to stop it is exit the app and get back to the app via the "recent apps" button or notification screen.
Can someone help me with the code?
StreamService.java
package id.pratama.example.streamingaudio.service;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import id.pratama.example.streamingaudio.MainActivity;
import id.pratama.example.streamingaudio.R;
/**
* Created by pratama on 4/22/14.
*/
public class StreamService extends Service implements
MediaPlayer.OnCompletionListener,
MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener,
MediaPlayer.OnBufferingUpdateListener {
/**
* for educational only
*/
// public static final String URL_STREAM = "http://jkt.jogjastreamers.com:8000/jisstereo?s=02766";
// radio UNISI
public static final String URL_STREAM = "http://202.162.32.23:8000";
// notification
private static final int NOTIFICATION_ID = 1;
private PhoneStateListener phoneStateListener;
private TelephonyManager telephonyManager;
private boolean isPausedInCall = false;
private NotificationCompat.Builder builder;
//intent
private Intent bufferIntent;
public static final String BROADCAST_BUFFER = "id.pratama.example.streamingaudio.broadcastbuffer";
private MediaPlayer mediaPlayer = new MediaPlayer();
#Override
public void onCreate() {
super.onCreate();
Log.d("create", "service created");
bufferIntent = new Intent(BROADCAST_BUFFER);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.reset();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("play", "play streaming");
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_OFFHOOK:
case TelephonyManager.CALL_STATE_RINGING:
if (mediaPlayer != null) {
pauseMedia();
isPausedInCall = true;
}
break;
case TelephonyManager.CALL_STATE_IDLE:
if (mediaPlayer != null) {
if (isPausedInCall) {
isPausedInCall = false;
playMedia();
}
}
break;
}
}
};
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
initNotification();
mediaPlayer.reset();
/**
* play media
*/
if (!mediaPlayer.isPlaying()) {
try {
Log.d("streamm", "" + URL_STREAM);
mediaPlayer.setDataSource(URL_STREAM);
// sent to UI radio is buffer
sendBufferingBroadcast();
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
Log.d("error", e.getMessage());
} catch (IllegalStateException e) {
Log.d("error", e.getMessage());
} catch (IOException e) {
Log.d("error", e.getMessage());
}
}
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int i) {
}
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
stopMedia();
stopSelf();
}
#Override
public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
Toast.makeText(this, "Error not valid playback", Toast.LENGTH_SHORT).show();
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
Toast.makeText(this, "Error server died", Toast.LENGTH_SHORT).show();
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
Toast.makeText(this, "Error unknown", Toast.LENGTH_SHORT).show();
break;
}
return false;
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
// sent to UI, audio has buffered
sendBufferCompleteBroadcast();
playMedia();
}
private void pauseMedia() {
if (mediaPlayer.isPlaying())
mediaPlayer.pause();
}
private void playMedia() {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
}
private void stopMedia() {
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
}
/**
* sent buffering
*/
private void sendBufferingBroadcast() {
bufferIntent.putExtra("buffering", "1");
sendBroadcast(bufferIntent);
}
/**
* sent buffering complete
*/
private void sendBufferCompleteBroadcast() {
bufferIntent.putExtra("buffering", "0");
sendBroadcast(bufferIntent);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("tag", "remove notification");
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
if (phoneStateListener != null) {
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
}
cancelNotification();
}
/**
* show notificaiton
*/
private void initNotification() {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent intent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Stream Radio")
.setContentText("895 JIZ fm");
builder.setContentIntent(intent);
builder.setOngoing(true);
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
/**
* cancel notification
*/
private void cancelNotification() {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);
builder.setOngoing(false);
}
}
MainActivity.java
package id.pratama.example.streamingaudio;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import id.pratama.example.streamingaudio.service.StreamService;
import id.pratama.example.streamingaudio.utils.Utils;
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private Intent serviceIntent;
private Button btnPlay;
private static boolean isStreaming = false;
private ProgressDialog pdBuff = null;
private boolean mBufferBroadcastIsRegistered;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPlay = (Button) findViewById(R.id.btnPlay);
btnPlay.setOnClickListener(this);
serviceIntent = new Intent(this, StreamService.class);
isStreaming = Utils.getDataBooleanFromSP(this, Utils.IS_STREAM);
if (isStreaming)
btnPlay.setText("Stop");
}
#Override
public void onClick(View view) {
if (view == btnPlay) {
Log.d("playStatus", "" + isStreaming);
if (!isStreaming) {
btnPlay.setText("Stop");
startStreaming();
Utils.setDataBooleanToSP(this, Utils.IS_STREAM, true);
} else {
if (isStreaming) {
btnPlay.setText("Start");
Toast.makeText(this, "Stop Streaming..", Toast.LENGTH_SHORT).show();
stopStreaming();
isStreaming = false;
Utils.setDataBooleanToSP(this, Utils.IS_STREAM, false);
}
}
}
}
#Override
protected void onPause() {
super.onPause();
if (mBufferBroadcastIsRegistered) {
unregisterReceiver(broadcastBufferReceiver);
mBufferBroadcastIsRegistered = false;
}
}
#Override
protected void onResume() {
super.onResume();
if (!mBufferBroadcastIsRegistered) {
registerReceiver(broadcastBufferReceiver, new IntentFilter(
StreamService.BROADCAST_BUFFER));
mBufferBroadcastIsRegistered = true;
}
}
private void startStreaming() {
Toast.makeText(this, "Start Streaming..", Toast.LENGTH_SHORT).show();
stopStreaming();
try {
startService(serviceIntent);
} catch (Exception e) {
}
}
private void stopStreaming() {
try {
stopService(serviceIntent);
} catch (Exception e) {
}
}
private BroadcastReceiver broadcastBufferReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent bufferIntent) {
showProgressDialog(bufferIntent);
}
};
private void showProgressDialog(Intent bufferIntent) {
String bufferValue = bufferIntent.getStringExtra("buffering");
int bufferIntValue = Integer.parseInt(bufferValue);
switch (bufferIntValue) {
case 0:
if (pdBuff != null) {
pdBuff.dismiss();
}
break;
case 1:
pdBuff = ProgressDialog.show(MainActivity.this, "",
"Streaming...", true);
break;
}
}
}
finally figured it out myself!
edit the MainActivity.java and use this code
package id.pratama.example.streamingaudio;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import id.pratama.example.streamingaudio.service.StreamService;
import id.pratama.example.streamingaudio.utils.Utils;
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private Intent serviceIntent;
private Button btnPlay;
private static boolean isStreaming;
private ProgressDialog pdBuff = null;
private boolean mBufferBroadcastIsRegistered;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPlay = (Button) findViewById(R.id.btnPlay);
btnPlay.setOnClickListener(this);
serviceIntent = new Intent(this, StreamService.class);
isStreaming = Utils.getDataBooleanFromSP(this, Utils.IS_STREAM);
if (isStreaming)
btnPlay.setText("Stop");
}
#Override
public void onClick(View view) {
if (view == btnPlay) {
Log.d("playStatus", "" + isStreaming);
if (!isStreaming) {
btnPlay.setText("Stop");
startStreaming();
isStreaming = true;
Utils.setDataBooleanToSP(this, Utils.IS_STREAM, true);
} else {
if (isStreaming) {
btnPlay.setText("Start");
Toast.makeText(this, "Stop Streaming..", Toast.LENGTH_SHORT).show();
stopStreaming();
isStreaming = false;
Utils.setDataBooleanToSP(this, Utils.IS_STREAM, false);
}
}
}
}
#Override
protected void onPause() {
super.onPause();
if (mBufferBroadcastIsRegistered) {
unregisterReceiver(broadcastBufferReceiver);
mBufferBroadcastIsRegistered = false;
}
}
#Override
protected void onResume() {
super.onResume();
if (!mBufferBroadcastIsRegistered) {
registerReceiver(broadcastBufferReceiver, new IntentFilter(
StreamService.BROADCAST_BUFFER));
mBufferBroadcastIsRegistered = true;
}
}
private void startStreaming() {
Toast.makeText(this, "Start Streaming..", Toast.LENGTH_SHORT).show();
stopStreaming();
try {
startService(serviceIntent);
} catch (Exception e) {
}
}
private void stopStreaming() {
try {
stopService(serviceIntent);
} catch (Exception e) {
}
}
private BroadcastReceiver broadcastBufferReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent bufferIntent) {
showProgressDialog(bufferIntent);
}
};
private void showProgressDialog(Intent bufferIntent) {
String bufferValue = bufferIntent.getStringExtra("buffering");
int bufferIntValue = Integer.parseInt(bufferValue);
switch (bufferIntValue) {
case 0:
if (pdBuff != null) {
pdBuff.dismiss();
}
break;
case 1:
pdBuff = ProgressDialog.show(MainActivity.this, "",
"Streaming...", true);
break;
}
}
}

Application crash with no exception after resuming

I am making simple app to display video and plaing audio playback if activity is in background.
My app works fine if i just turn screen off/on.
It crashes when I resume my app after brawsing another application.
Log cat show no error.
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import com.squareup.otto.Subscribe;
public class MainActivity
extends Activity
implements android.view.SurfaceHolder.Callback {
private SurfaceView surfaceViewFrame;
private SurfaceHolder holder;
private Bundle extras;
private static final String TAG = "log_tag";
private boolean b = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceViewFrame = (SurfaceView) findViewById(R.id.surfaceView);
surfaceViewFrame.setClickable(false);
holder = surfaceViewFrame.getHolder();
holder.addCallback(this);
}
#Subscribe
public void attachPlayer(MediaPlayer player) {
player.setDisplay(holder);
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
public void surfaceCreated(SurfaceHolder holder) {
startService(new Intent(this, MediaPlayerService.class));
}
public void surfaceDestroyed(SurfaceHolder holder) {
}
#Override
protected void onStart() {
super.onStart();
BusProvider.getInstance().register(this);
}
#Override
protected void onStop() {
super.onStop();
BusProvider.getInstance().unregister(this);
}
Service
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;
import java.io.IOException;
public class MediaPlayerService
extends Service
implements MediaPlayer.OnPreparedListener,
MediaPlayer.OnCompletionListener,
MediaPlayer.OnSeekCompleteListener {
private static final String TAG = "MediaService";
private static final String ACTION_PLAY = "com.example.action.PLAY";
private MediaPlayer player;
public String[]
video_path =
{"https://ellovidsout.s3.amazonaws.com/1265/9/1422967594.mp4.m3u8", "https://ellovidsout.s3.amazonaws.com/1260/9/1422887544.mp4.m3u8"};
#Override
public void onCreate() {
super.onCreate();
player = new MediaPlayer();
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnSeekCompleteListener(this);
player.setScreenOnWhilePlaying(true);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
playVideo();
Notification note = new Notification(
R.drawable.ic_launcher, "Can you hear the music?", System.currentTimeMillis()
);
Intent i = new Intent(this, MediaPlayerService.class);
i.setFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP
);
PendingIntent pi = PendingIntent.getActivity(
this, 0, i, 0
);
note.setLatestEventInfo(
this, "Fake Player", "Now Playing: \"Ummmm, Nothing\"", pi
);
note.flags |= Notification.FLAG_NO_CLEAR;
startForeground(1337, note);
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
player.stop();
player.release();
player = null;
}
private Thread playback = new Thread(
new Runnable() {
public void run() {
try {
try {
player.setDataSource(
MediaPlayerService.this, Uri.parse(
video_path[0]
)
);
player.prepareAsync();
} catch (IOException e) {
Log.e(TAG, "Error while playing video: " + e.getMessage());
}
} catch (IllegalArgumentException e) {
Log.e(TAG, "Error while playing video: " + e.getMessage());
}
}
}
);
private void playVideo() {
if (player!=null&&!playback.isAlive()) playback.start();
}
public void onPrepared(MediaPlayer mp) {
if (!player.isPlaying()) {
player.start();
BusProvider.getInstance()
.post(player);
}
}
public void onCompletion(MediaPlayer mp) {
try {
player.setDataSource(
MediaPlayerService.this, Uri.parse(
video_path[0]
)
);
} catch (IOException e) {
Log.e(TAG, "Error while playing video: " + e.getMessage());
}
player.prepareAsync();
}
public void onSeekComplete(MediaPlayer mp) {
}
}
you missed in onStop:
#Override
protected void onStop() {
holder.removeCallback(this);
super.onStop();
}
please add the crash report

Categories

Resources