Broadcast Receiver from Service in MainActivity / MapsActivity - java

I have a service, which get the current position every Second and then the Service should send the location with an Broadcast back to the Main Activity.
With the log i can see, that the Service Class sends the Broadcast, but the MainActivity never get it.
My Service:
public class MyService extends Service
{
private static final String TAG = "BOOMBOOMTESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10;
private void sendLocation(Location l) {
Intent intent = new Intent("GPSLocationUpdates");
// You can also include some extra data.
intent.putExtra("Lat", l.getLatitude());
intent.putExtra("Lon", l.getLongitude());
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
Log.e(TAG, l + "gesendet!");
}
private class LocationListener implements android.location.LocationListener
{
Location mLastLocation;
public LocationListener(String provider)
{
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location)
{
Log.e(TAG, "onLocationChanged: " + location);
Toast.makeText(MyService.this, "ja", Toast.LENGTH_LONG).show();
sendLocation(location);
mLastLocation.set(location);
}
[...]
}
}
The MainActicity (with Map included):
public class MainActivity extends AppCompatActivity
implements OnMapReadyCallback,
NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "Location";
private GoogleMap mMap;
private final static int MY_PERMISSIONS_FINE_LOCATION = 123;
track track = new track();
private BroadcastReceiver locationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG, "onReceive");
String action = intent.getAction();
LatLng pos = new LatLng(intent.getDoubleExtra("Lat", 0),
intent.getDoubleExtra("Lon", 0));
Log.e(TAG, "Position: " + pos + "empfangen");
track.posAdd(pos);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocalBroadcastManager.getInstance(this).registerReceiver(locationReceiver,
new IntentFilter("GPSLocationUpdates"));
Log.i(TAG, "BroadcastManager erstellt");
setContentView(R.layout.activity_main);
// Obtain the SupportMapFragment and get notified when the map is ready
to be used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
[...]
}
public void onMapReady(GoogleMap googleMap) {
[...]
startService(new Intent(this, MyService.class));
}
#Override
public void onRequestPermissionsResult(int requestCode, String
permissions[], int[] grantResults) {....}
public void onBackPressed() {...}
#Override
public boolean onCreateOptionsMenu(Menu menu) {...}
#Override
public boolean onOptionsItemSelected(MenuItem item) {...}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {...}
}
Hopefully you can help

Related

Android: How can I add Google map to a ViewPager?

I want to make an app that has on the main screen a ViewPager with a map and a profile section. Therefore, for position = 0 in the ViewPager, there is the map and for position = 1, there is the profile.
For each one of those two "sections" on the main screen, I have two activities: the map.xml with the MapActivity.java and the profile.xml with Profile.java. Both of those are inflated in the EnumFrag java class, depending on the position ( you see there an if ).
I have two issues:
The first one is that when I try to slide left or right, the map moves, not the ViewPager to the next slide. I tried to put a shape on the edge, but it is not working like the slide gesture is passing through the shape. Any help here, please?
The second is related to the first one, the MapActivity.java class is not even running because onCreate is not running (I put a Toast there so display something and nothing happened). Any help, please? (I create the map class object).
map.xml contains a simple fragment with an id of map.
MapActivity.java:
public class MapActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap map;
private Location me;
private FusedLocationProviderClient fusedLocationProviderClient;
private static final int REQUEST_CODE = 101;
#Override
protected void onCreate(Bundle savedInstanceState) {
Toast.makeText(this, "hey din onCreate", Toast.LENGTH_SHORT).show();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
getLastLocation();
}
private void getLastLocation() {
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_CODE);
return;
}
Toast.makeText(getApplicationContext(), "hey...", Toast.LENGTH_SHORT).show();
Task<Location> task = fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location != null){
me = location;
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapActivity.this);
}
else
Toast.makeText(getApplicationContext(), "Deschide-ti locatia", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
MapStyleOptions mapStyleOptions= MapStyleOptions.loadRawResourceStyle(this,R.raw.map_style);
googleMap.setMapStyle(mapStyleOptions);
LatLng point = new LatLng(me.getLatitude(),me.getLongitude());
MarkerOptions markerOptions = new MarkerOptions().position(point).title("Me");
googleMap.animateCamera(CameraUpdateFactory.newLatLng(point));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(point,16));
googleMap.addMarker(markerOptions);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLastLocation();
}
}
}
}
Profile.java
public class Profile extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
EditText username = findViewById(R.id.usernameProfile);
username.setText(MainScreen.getUsername());
}
}
EnumFragment.java
public class EnumFragments extends PagerAdapter {
private Context context;
public EnumFragments(Context context) {
this.context = context;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view;
MapActivity mapActivity = new MapActivity();
switch (position){
case 0:
view = layoutInflater.inflate(R.layout.activity_profile,null);
break;
default:
view = layoutInflater.inflate(R.layout.activity_map,null);
break;
}
ViewPager viewPager = (ViewPager)container;
viewPager.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
ViewPager viewPager = (ViewPager)container;
View view = (View) object;
viewPager.removeView(view);
}
#Override
public int getCount() {
return 2;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
}
MainScreen.java
public class MainScreen extends AppCompatActivity {
private static String username;
private ViewPager viewPager;
private EnumFragments enumFragments;
private static int userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
Bundle extras = getIntent().getExtras();
userID = extras.getInt("userID");
username = extras.getString("username");
viewPager = findViewById(R.id.mainSlider);
EnumFragments enumFragments = new EnumFragments(this);
viewPager.setAdapter(enumFragments);
}
public static int getUserID() {
return userID;
}
public static String getUsername() {
return username;
}
#Override
public void onBackPressed() {
//Nothing
}
}
Why you don't add the MapActivity into the MainScreen Activity. You even don't use the MapActivity in your PagerAdapter class. I would make an other attribute in the constructor of your PagerAdapter, after this :
private MapActivity current;
public EnumFragments(MapActivity map_activity)
{
this.current = map_activity;
}
then I would put a getter method in the map_activity, wich returns a view, where you can see the current GoogleMap or other features.
Your problem is that you don't use the new MapActivity...
I hope that may helps you

How can I stop and restart Android Location Service

I have the following Service implemented in my MainActivity and I want to start and restart the Service by Buttonclick. But when I click on stop the Service still sends Location updates! How can I stop the Service immediately when I press the stop button and what is my fault?
Service Class:
public class LocationNotifyService extends Service implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
final static String MY_ACTION = "MY_ACTION";
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
public static Location mCurrentLocation;
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
private static final int TWO_MINUTES = 1000 * 60 * 2;
public static final String MOVEMENT_UPDATE = "com.client.gaitlink.AccelerationService.action.MOVEMENT_UPDATE";
public static final String ACCELERATION_X = "com.client.gaitlink.AccelerationService.ACCELERATION_X";
public static final String ACCELERATION_Y = "com.client.gaitlink.AccelerationService.ACCELERATION_Y";
public static final String ACCELERATION_Z = "com.client.gaitlink.AccelerationService.ACCELERATION_Z";
public static final String ACCELERATION_PACE = "com.client.gaitlink.AccelerationService.ACCELERATION_PACE";
public static final String ACCELERATION_TIME = "com.client.gaitlink.AccelerationService.ACCELERATION_TIME";
#Override
public void onCreate()
{
Log.d("create", "create");
//show error dialog if GoolglePlayServices not available
if (isGooglePlayServicesAvailable()) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(5); /* min dist for location change, here it is 10 meter */
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
//Check Google play is available or not
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
return ConnectionResult.SUCCESS == status;
}
#Override
public void onConnected(Bundle bundle) {
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
}
protected void startLocationUpdates()
{
Log.d("start","start");
try {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} catch (IllegalStateException e) {}
}
#Override
public void onLocationChanged(Location location)
{
Log.d("changed", "changed");
Intent intent = new Intent(MOVEMENT_UPDATE);
intent.setAction(MY_ACTION);
intent.putExtra(ACCELERATION_X, location.getLongitude());
intent.putExtra(ACCELERATION_Y, location.getLatitude());
intent.putExtra(ACCELERATION_Z, location.getAltitude());
intent.putExtra(ACCELERATION_PACE, location.getSpeed());
intent.putExtra(ACCELERATION_TIME, location.getTime());
sendBroadcast(intent);
Log.d("send","send");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public boolean stopService(Intent name)
{
// TODO Auto-generated method stub
mGoogleApiClient.disconnect();
return super.stopService(name);
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity {
Button start;
Button stop;
TextView xyz;
MyReceiver myReceiver;
double accelerationX;
double accelerationY;
double accelerationZ;
float pace;
List<Double> pace_list = new ArrayList<Double>();
Location oldLoc = new Location("locationOld");
Location newLoc = new Location("locationNew");
double distance = 0;
long time = 0;
String temp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
start = (Button) findViewById(R.id.start);
stop = (Button) findViewById(R.id.stop);
xyz = (TextView) findViewById(R.id.xyz);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("click", "click");
myReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(LocationNotifyService.MY_ACTION);
registerReceiver(myReceiver, intentFilter);
Intent intent = new Intent(MainActivity.this,
LocationNotifyService.class);
startService(intent);
//startService(new Intent(MainActivity.this, LocationNotifyService.class));
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,
LocationNotifyService.class);
stopService(intent);
Log.d("stop", "stop");
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.d("revcive", "recive");
accelerationX = intent.getDoubleExtra(LocationNotifyService.ACCELERATION_X, 0);
accelerationY = intent.getDoubleExtra(LocationNotifyService.ACCELERATION_Y, 0);
accelerationZ = intent.getDoubleExtra(LocationNotifyService.ACCELERATION_Z, 0);
pace = intent.getFloatExtra(LocationNotifyService.ACCELERATION_PACE, 0);
pace = (float) (pace * 3.6);
time = intent.getLongExtra(LocationNotifyService.ACCELERATION_TIME, 0);
pace_list.add((double) pace);
SimpleDateFormat s = new SimpleDateFormat("yyyyMMddhhmmss");
String format = s.format(new Date());
temp += format + " | " + accelerationX + " | " + accelerationY + " | " + accelerationZ + " | " + Collections.max(pace_list) + "\n";
xyz.setText(temp);
}
}
}
Manifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar"
android:configChanges="orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="com.client.gaitlink.CommunicationService.action.ACTIVITY_STATUS_UPDATE" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".LocationNotifyService"
android:exported="false"/>
</application>
I guess you forgot to add below line inside stopService()
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
add it inside stopService -
**// Missing #Override**
#Override
public boolean stopService(Intent name) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
return super.stopService(name);
}
Modify MainActivity.java like below -
public class MainActivity extends AppCompatActivity {
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
intent = new Intent(MainActivity.this,
LocationNotifyService.class);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
...
startService(intent);
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(intent);
}
});
} // end of class MainActivity
You need to comment below code from stop.setOnClickListener and start.setOnClickListener-
Intent intent = new Intent(MainActivity.this, LocationNotifyService.class);
* You have to use same intent that started a service to stop a servivce.

Updating RecyclerView with adapter.notifyDataSetChanged()

I've implemented a RecyclerView which has a user interface of a timer counting down. I created a BroadcastService class which creates a CountDownTimer and broadcasts the timer's contents in the onTick() method to my MainActivity, where I use a BroadCast receiever to update the UI.
My BroadcastReceiver is only receiving the initial value from the BroadcastService. I figured that's because I hadn't notified the recycler view's adapter that the data had changed. However, because of variable scope, I'm unable to access my adapter from my broadcast receiver.
Perhaps I have a fundamental lack of understanding of variable scope, but how can I access the adapter from
adapter = new DataAdapter(getApplicationContext(), data);
in my broadcast receiver class? Because right now it's not being recognized.
This is my class definition + onCreate()
public class Profile_Page extends ActionBarActivity implements DataAdapter.ClickListener {
private RecyclerView recyclerView;
public DataAdapter adapter;
private Context context;
String currentUser;
Data current = new Data();
final List<Data> data = new ArrayList<>();
public static String BROADCAST_ACTION =
"packagename.countdown_br";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter();
filter.addAction(BROADCAST_ACTION);
filter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(br, filter);
startService(new Intent(this, Broadcast_Service.class));
setContentView(R.layout.activity_profile__page);
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseClass");
query.whereEqualTo("author", ParseUser.getCurrentUser());
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
if (e == null) {
for (ParseObject getData : list)
{
current.1= getData.getString("1");
current.2= getData.getString("2");
current.3= getData.getString("3");
current.4= getData.getString("4");
current.5= getData.getString("5");
data.add(current);
}
}
else {
}
adapter = new DataAdapter(getApplicationContext(), data);
recyclerView.setAdapter(adapter); //set recyclerView to this adapter
}
});
}
And here's my Broadcast Receiver code [which is also in MainActivity.java]
public BroadcastReceiver br = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateGUI(intent);
//HOW TO NOTIFY DATA SET CHANGE
}
};
public void updateGUI(Intent intent) {
if (intent.getExtras() != null) {
long millisUntilFinished = intent.getLongExtra("countdown", 0);
current.goalTimer = String.valueOf(intent.getExtras().getLong("countdown") / 1000);
}
}
And, if it is of any use, here's my Broadcast Service class:
public class Broadcast_Service extends Service {
private final static String TAG = "BroadcastService";
LocalBroadcastManager broadcastManager;
public static final String COUNTDOWN_BR = "packagename.countdown_br";
Intent bi = new Intent(COUNTDOWN_BR);
CountDownTimer cdt = null;
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Starting timer...");
cdt = new CountDownTimer(30000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
bi.putExtra("countdown", millisUntilFinished);
sendBroadcast(bi);
}
#Override
public void onFinish() {
Log.i(TAG, "Timer finished");
}
};
cdt.start();
}
#Override
public void onDestroy() {
cdt.cancel();
Log.i(TAG, "Timer cancelled");
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
First of all, extend the BroadcastReciever class as follows:
public class MyReciever extends BroadcastReciever{
private Profile_Page activity;
public MyReciever(Profile_Page activity){
this.activity = activity;
}
#Override
public void onReceive(Context context, Intent intent) {
activity.updateGUI(intent);
}
}
Create a static instance of your activity and pass it to your receiver.
public class Profile_Page extends ActionBarActivity implements DataAdapter.ClickListener {
private static Profile_Page instance;
private MyReciever myReceiver;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance = this;
myReceiver = new MyReciever(instance);
...
}
public void updateGUI(Intent intent) {
...
}
}
Now you can access your adapter quite easily. Hope this helps.

Android Media Player App services

I am developing a media player app that has a bound service to an activity.It works fine when i press the home button or the app switcher and then come back to the app from the recent app, but as i press the back button the activity also ends the Music Service. Please guide me the exact steps that can solve these minor issues, so that i can give media controls to the app.My App has 2 main classes
MyActivity
AudioService
My code is given below.
AudioService.java
public class AudioService extends Service implements
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
MediaPlayer.OnCompletionListener{
// -----------------------------------------Attributes--------------------------------------------------------
private ArrayList<File> songs;
private ArrayList<File> audio;
private MediaPlayer player;
private int songPosn;
private String name="";
private final IBinder musicBind = new AudioBinder();
private Uri trackUri;
private int NOTIFY_ID=1;
// -----------------------------------------------------------------------------------------------------------
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
public void onCreate(){
//create the service
//create the service
super.onCreate();
//initialize position
songPosn=0;
//create player
player = new MediaPlayer();
initMusicPlayer();
}
// to initialize the media class
public void initMusicPlayer(){
//set player properties
player.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
}
public void setList(ArrayList<File> theSongs){
songs=theSongs;
}
public void setSong(int songIndex){
songPosn=songIndex;
}
public class AudioBinder extends Binder {
AudioService getService() {
return AudioService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return musicBind;
}
#Override
public boolean onUnbind(Intent intent){
player.stop();
player.release();
return false;
}
#Override
public void onCompletion(MediaPlayer mp) {
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
mp.reset();
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
//start playback
mp.start();
showNotification();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
songPosn = intent.getIntExtra("pos",0);
audio=(ArrayList)intent.getParcelableArrayListExtra("songlist");
name = intent.getStringExtra("name");
Log.e("Service","name"+audio.get(0));
Log.e("Service","position "+songPosn);
return START_STICKY;
}
public void playSong(){
//play a song
player.reset();
Log.e("TRACH the URI",""+trackUri);
trackUri =Uri.parse(audio.get(songPosn).toString());
try{
player.setDataSource(getApplicationContext(), trackUri);
}
catch(Exception e){
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
player.prepareAsync();
}
private void showNotification(){
Intent notIntent = new Intent(this, MyActivity.class);
notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendInt = PendingIntent.getActivity(this, 0,
notIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentIntent(pendInt)
.setTicker(name)
.setOngoing(true)
.setContentTitle("Playing")
.setContentText(name);
Notification not = builder.build();
startForeground(NOTIFY_ID, not);
}
#Override
public void onDestroy()
{
stopForeground(true);
}
}
MyActivity.java
public class MyActivity extends Activity {
// ***************************** Attributes Start ******************************************************
private ArrayList<File> myfiles= new ArrayList<File>();
private ListView listView;
private ArrayAdapter<String> adapter ;
private String name="";
private int position;
private AudioService musicSrv;
private Intent playIntent;
private boolean musicBound=false;
// ***************************** Attributes End ******************************************************
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
String toneslist[] ={"Airtel"
,"sherlock_theme"};
listView = (ListView) findViewById(R.id.listView);
adapter = new ArrayAdapter<String>(getApplication(),R.layout.list_item,R.id.list_textview,toneslist);
listView.setAdapter(adapter);
getMp3();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
name =adapter.getItem(pos);
position =pos;
Log.e("MAINACTIVITY (clickListener) pos =",""+position+" name = "+name);
musicSrv.setSong(position);
musicSrv.playSong();
}
});
}
#Override
protected void onStart() {
super.onStart();
if(playIntent==null){
Log.e("MAINACTIVITY pos =",""+position+" name = "+name);
playIntent = new Intent(this, AudioService.class).putExtra("pos",position).putExtra("songlist", myfiles).putExtra("name", name);
bindService(playIntent, audioConnection, Context.BIND_AUTO_CREATE);
startService(playIntent);
}
}
private ServiceConnection audioConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
AudioService.AudioBinder binder = (AudioService.AudioBinder)service;
musicSrv = binder.getService();
musicSrv.setList(myfiles);
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void getMp3(){
String s=(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)).toString();
// s="content://media/external/audio/media";
GetFiles(s);
}
private void GetFiles(String path) {
File file = new File(path);
File[] allfiles = file.listFiles();
if (allfiles.length == 0) {
} else {
for (int i = 0; i < allfiles.length; i++)
{
Log.e("FFFFFFFFF", allfiles[i].getName().toString());
myfiles.add(allfiles[i]);
}
}
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onDestroy() {
stopService(playIntent);
musicSrv=null;
super.onDestroy();
}
}
Try with this in your Activity:
#Override
public void onDestroy(){
if (!isChangingConfigurations()) stopService(new Intent (this, YourService.class));
super.onDestroy();
}
#Override
public void onBackPressed(){
if (mediaIsPlaying) moveTaskToBack(true);
else super.onBackPressed();
}

Accessing an activity through a service

I have an Activity and a service.
The activity has a TextView member and a setText() method.
I would like to call that method through the Service, how can I do that?
Here is the code:
Activity:
public class MainActivity extends Activity {
private TextView tv1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.tv1 = (TextView) findViewById(R.id.textView1);
Intent intent = new Intent(this,MyService.class);
startService(intent);
}
// <-- some deleted methods.. -->
public void setText(String st) {
this.tv1.setText(st);
}
}
Service:
public class MyService extends Service {
private Timer timer;
private int counter;
public void onCreate() {
super.onCreate();
this.timer = new Timer();
this.counter = 0;
startService();
}
private void startService() {
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
//MainActivityInstance.setText(MyService.this.counter); somthing like that
MyService.this.counter++;
if(counter == 1000)
timer.cancel();
}
},0,100);
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
You can use an intent in order to send any information (i.e. the counter for TextView member) to the Activity.
public void run() {
//MainActivityInstance.setText(MyService.this.counter); somthing like that
MyService.this.counter++;
Intent intentBroadcast = new Intent("MainActivity");
intentBroadcast.putExtra("counter",MyService.this.counter);
sendBroadcast(intentBroadcast);
if(counter == 1000)
timer.cancel();
}
...then, you will receive your data in the Activity using a Broadcast Receiver
/**
* Declares Broadcast Reciver for recive location from Location Service
*/
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Get data from intent
serviceCounter = intent.getIntExtra("counter", 0);
// Change TextView
setText(String.valueOf(counterService));
}
};

Categories

Resources