Radio app into a service - Java for Android App Development

Hi I was looking for tutorials to make a radio app so I followed this one but the problem is that as soon as the app closes the music stops, how do I turn it into a service. Thanks
Code:
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
public class myMain extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("stream url");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
@Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}

benpaterson said:
Hi I was looking for tutorials to make a radio app so I followed this one but the problem is that as soon as the app closes the music stops, how do I turn it into a service. Thanks
Code:
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
public class myMain extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("stream url");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
@Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
Click to expand...
Click to collapse
You'll have to learn about Android Service and extend that, instead of Activity.

Related

[Q] How Do I Stop a Media Player

I coded an application that plays a radio stream. The App is very simple just start and stop.
When I press start, the stream plays just fine. But when I call stop, nothing happens.
Here is the code (items in red have been changed to protect the identity of this app ).:
Code:
package [COLOR="red"]com.xxxxxx.stream[/COLOR];
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class [COLOR="red"]NameOfAppActivity[/COLOR] extends Activity {
private Button start;
private Button stop;
MediaPlayer mp = new MediaPlayer();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
private void initControls() {
start = (Button)findViewById(R.id.start);
start.setOnClickListener(new Button.OnClickListener() {public void onClick (View v){Start();}});
stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(new Button.OnClickListener() {public void onClick (View v){Stop();}});
}
private void Start() {
try {
mp.setDataSource("[COLOR="red"]http://xxxxx.xxxxxx.com/stream[/COLOR]");
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
setContentView(R.layout.main);
}
private void Stop(){
mp.release();
}
}
I have also tried
Code:
private void Stop(){
mp.stop();
}
}
and
Code:
private void Stop(){
mp.pause();
}
}
Nothing seems to work. I have to force close the app in order to stop it.
What am I doing wrong? Please help.
mp.release() should do it. Have you tried the debugger to make sure that Stop() is being hit? I don't see why it wouldn't, but that's always the first thing I check when things don't behave like I think they should.
Thanks Gene Poole. I will try debugging it when I am home. It's extremely frustrating. I changed the code to:
Code:
private void Stop(){
if (mp != null){
mp.stop();
mp.release();
}
}
Thanks for your input.
Thanks. I figured it out. However. If I hit release, it doesn't play the stream again. The app just FCs. For now I have it set to stop
How did you figure it out?
I see the same behavior.
I/HTTPStream( 194): 1358 Bytes read, progress 64711/65536
Still keeps going, even when I call mediaplayer.stop();
One way that does stop it is to call reset(), but that also hangs for a bit.
Here is the revised code. There is no release in there but I'll figure it out soon.
Code:
package com.xxxxxx.stream;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class NameOfAppActivity extends Activity {
private Button start;
private Button stop;
MediaPlayer mp = new MediaPlayer();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start = (Button)findViewById(R.id.start);
stop = (Button)findViewById(R.id.stop);
start.setOnClickListener(new Button.OnClickListener() {public void onClick (View v){Start();}});
stop.setOnClickListener(new Button.OnClickListener() {public void onClick (View v){Stop();}});
}
private void Start() {
try {
mp.setDataSource("http://xxxxx.xxxxxx.com/stream");
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
private void Stop(){
if (mp != null){
mp.stop();
}
}
The code works fine for the most part. However if I am running the stream and exit the app and comeback to the app, I can not stop it. How do I restore the application's previous state.

[Q] Sockets in Android

SOLVED. please lock.
I have 2 buttons, Server and Client.
The server button contain a textview which prints stuff received from the client.
The client button open Editbox and Send button which uses OnClick function.
In debug mode everything works fine.
When I run them independently and playing with ON/OFF SocketServer and Existing/New SocketClient the program would mostly get stuck and sometimes i get flowed with "Client says: null"
It usually happens when I click in device1 on Server Button, in device2 on client -> send a message from device2 to device1 and it successes -> close server on device1 -> send about 3 messages on device2 (remember that the serverSocket is closed) -> open server on device1 -> close and open client on device2.
The app also getting stuck randomaly after some turn off screen and turn on using the power button while playing with buttons.. and I cant find the issue.
Server.java:
Code:
package com.example.socketproject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.concurrent.TimeUnit;
import org.apache.http.conn.util.InetAddressUtils;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class Server extends Activity
{
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
private TextView text;
private final static int SECONDS_TO_WAIT = 1;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server);
text = (TextView) findViewById(R.id.textview_server);
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.server, menu);
return true;
}
@Override
protected void onDestroy()
{
super.onDestroy();
try
{
if (!serverSocket.isClosed())
{
serverSocket.close();
}
if (!serverThread.isInterrupted())
{
serverThread.interrupt();
}
}
catch (IOException e)
{
Log.e(TAG, e.getMessage() + " |||| " );
}
}
@Override
protected void onStop()
{
super.onStop();
try
{
if (!serverSocket.isClosed())
{
serverSocket.close();
}
if (!serverThread.isInterrupted())
{
serverThread.interrupt();
}
}
catch (IOException e)
{
Log.e(TAG, e.getMessage() + " |||| " );
}
}
private class ServerThread implements Runnable
{
public void run()
{
boolean accepted = false;
InetSocketAddress socketAddr = new InetSocketAddress(59135);
try
{
serverSocket = new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(SECONDS_TO_WAIT));
serverSocket.bind(socketAddr);
}
catch (IOException e)
{
Log.e(TAG, e.getMessage() + " |||| " );
}
while (!Thread.currentThread().isInterrupted())
{
Socket socket = null;
try
{
socket = serverSocket.accept();
accepted = true;
}
catch (InterruptedIOException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
Thread.currentThread().interrupt();
}
if (accepted)
{
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
}
accepted = false;
}
}
}
private class CommunicationThread implements Runnable
{
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket)
{
this.clientSocket = clientSocket;
try
{
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
}
catch (IOException e)
{
Log.e(TAG, e.getMessage() + " |||| " );
Thread.currentThread().interrupt();
}
}
public void run()
{
while (!Thread.currentThread().isInterrupted())
{
try
{
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
}
catch (IOException e)
{
Log.e(TAG, e.getMessage() + " |||| " );
Thread.currentThread().interrupt();
}
}
}
}
private class updateUIThread implements Runnable
{
private String msg;
public updateUIThread(String str)
{
this.msg = str;
}
@Override
public void run()
{
text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
}
}
}
Client.java:
Code:
package com.example.socketproject;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.http.conn.util.InetAddressUtils;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class Client extends Activity
{
private final static int SECONDS_TO_WAIT = 5;
private PrintWriter out = null;
private Socket socket = null;
private ClientThread clientThread = new ClientThread();
private String serverIp = null;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
serverIp = MY_PHONE_IP_HERE;
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.client, menu);
return true;
}
private String getLocalIpAddress()
{
String ipAddr = null;
try
{
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)
{
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
{
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress()) )
{
ipAddr = inetAddress.getHostAddress();
return ipAddr;
}
}
}
}
catch (SocketException ex)
{
Log.d(TAG, ex.toString());
}
return ipAddr;
}
public void onClick(View view)
{
try
{
ExecutorService poolExecutor = Executors.newSingleThreadExecutor();
poolExecutor.execute(clientThread);
poolExecutor.shutdown();
poolExecutor.awaitTermination(SECONDS_TO_WAIT, TimeUnit.SECONDS);
EditText et = (EditText) findViewById(R.id.editText_client);
String str = et.getText().toString();
if(out == null)
{
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
}
out.println(str);
}
catch (UnknownHostException e)
{
Log.e(TAG, e.getMessage() + " |||| " + e.getStackTrace());
}
catch (IOException e)
{
Log.e(TAG, e.getMessage() + " |||| " + e.getStackTrace());
}
catch (Exception e)
{
Log.e(TAG, e.getMessage() + " |||| " + e.getStackTrace());
}
}
class ClientThread implements Runnable
{
@Override
public void run()
{
try
{
InetAddress serverAddr = InetAddress.getByName(serverIp);
socket = new Socket();
socket.connect(new InetSocketAddress(serverAddr, 59135), (int) TimeUnit.SECONDS.toMillis(SECONDS_TO_WAIT));
//socket = new Socket(serverAddr, 59135);
}
catch (UnknownHostException e)
{
Log.e(TAG, e.getMessage() + " |||| " + e.getStackTrace());
}
catch (IOException e)
{
// TODO IF HOST ISNT EXIST
Log.e(TAG, e.getMessage() + " |||| " + e.getStackTrace());
}
}
}
}
EDIT:
nevermind, it was interrupt flag which was erased and made unexpected results with threads. decided to use booleans instead.
Closed at OP's request

[Q] JDBC in android fragment not working

I am working on an android application that modifies an external MySQL database. I know I can use an intermediate PHP/JSON service to do it, but I rather use JBDC because connection is faster and my project teachers want me to do it this way.
As it's my first app, I started with a simple button and an action(create a database), which actually works (in fact two buttons, the first one doesn't work on skd higher than 9, AsyncTask has to be used in them):
Code:
package com.example.prova;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.sql.*;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button1 = (Button) findViewById(R.id.btconn1);
final Button button2 = (Button) findViewById(R.id.btconn2);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try
{
String URL = "jdbc:mysql://" + "192.168.1.200" + ":" + "3306";
String USER = "app";
String PASS = "android";
Toast.makeText(getApplicationContext(),
"Conectando a servidor MySQL",
Toast.LENGTH_SHORT).show();
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(URL, USER, PASS);
Toast.makeText(getApplicationContext(),
"Conectado Servidor MySQL",
Toast.LENGTH_LONG).show();
Statement stmt = conn.createStatement();
String SQL = "CREATE DATABASE SYNC";
stmt.executeUpdate(SQL);
conn.close();
}
catch (ClassNotFoundException e)
{
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
catch (SQLException e)
{
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new LED13ON().execute();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class LED13ON extends AsyncTask<Void, Integer, Void> {
@Override
protected void onPostExecute(Void result){
SystemClock.sleep(2000);
}
@Override
protected void onPreExecute(){
SystemClock.sleep(2100);
}
@Override
protected void onProgressUpdate(Integer... values){
SystemClock.sleep(100);
}
@Override
protected Void doInBackground(Void... arg0){
try
{
String URL = "jdbc:mysql://" + "192.168.1.200" + ":" + "3306";
String USER = "app";
String PASS = "android";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(URL, USER, PASS);
Statement stmt = conn.createStatement();
String SQL = "CREATE DATABASE aSYNC";
stmt.executeUpdate(SQL);
conn.close();
}
catch (ClassNotFoundException e)
{
}
catch (SQLException e)
{
}
catch (Exception e)
{
}
return null;
}
}
}
The problem is when I try to use fragments, eclipse returns no errors but JDBC code is not working (logcat gives me no errors too). I know that's only the JDBC code which is not working because it gets inside the LED13ON and makes the SystemClock.sleep(2000), because the button is marked for two seconds. This is the code I have for the fragment in a new class:
Code:
package com.example.smarthome;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Locale;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class Fragment_main extends Fragment {
public Fragment_main() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main,container, false);
Button btn = (Button) rootView.findViewById(R.id.btconn1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick (View v) {
new LED13ON().execute();
}
});
return rootView;
}
public class LED13ON extends AsyncTask<Void, Integer, Void> {
@Override
protected void onPostExecute(Void result){
SystemClock.sleep(2000);
}
@Override
protected void onPreExecute(){
SystemClock.sleep(2100);
}
@Override
protected void onProgressUpdate(Integer... values){
SystemClock.sleep(100);
}
@Override
protected Void doInBackground(Void... arg0){
try
{
String URL = "jdbc:mysql://" + "192.168.1.200" + ":" + "3306";
String USER = "app";
String PASS = "android";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(URL, USER, PASS);
Statement stmt = conn.createStatement();
String SQL = "CREATE DATABASE aSYNC";
stmt.executeUpdate(SQL);
conn.close();
}
catch (ClassNotFoundException e)
{
}
catch (SQLException e)
{
}
catch (Exception e)
{
}
return null;
}
}
}
So I don't understand why being the same code it's not working for the second app, having changed the setOnClickListener to work in the fragment. Can anyone help me? I would really like to use the swipe views for my app as I think it fits more the android Holo style.
Thank you for your time!
EDIT:
I found the solution to my problem:
I logged the exceptions, it gave me the error:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Click to expand...
Click to collapse
The solution was to add newInstance in the Class.forName:
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
Click to expand...
Click to collapse
So that's all, now my app is working as I intended. Thanks for everything!

Exception in Using LocationClient with a service

Hello there. I write a service that should work with LocationClient (Google Play Services). I have an IntentService and an AlarmReceiver (to get location periodically). I have an exception that I cannot catch. Please help!
AlarmReceiver.java
Code:
package com.afusionlocation;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
public class AlarmReceiver extends BroadcastReceiver implements GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,LocationListener {
private LocationClient locationclient;
private LocationRequest locationrequest;
private Intent mIntentService;
private PendingIntent mPendingIntent;
@Override
public void onReceive(Context context, Intent intent) {
mIntentService = new Intent(context,MyLocationService.class);
mPendingIntent = PendingIntent.getService(context, 1, mIntentService, 0);
int resp = -1;
try{
resp = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);
}
catch (Exception ex)
{
Log.d("Error","onReceive(): exception: " +ex.toString());
}
if(resp == ConnectionResult.SUCCESS){
locationclient = new LocationClient(context,this,this);
locationclient.connect();
}
else{
Log.e("Error","Google Play Service Error: resp="+resp);
}
}
@Override
public void onLocationChanged(Location arg0) {
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
}
@Override
public void onConnected(Bundle arg0) {
locationrequest = LocationRequest.create();
locationrequest.setInterval(10000);
try{
locationclient.requestLocationUpdates(locationrequest, mPendingIntent); //HERE EXCEPTION that I cannot catch
}
catch(Exception ex)
{
Log.e("Error","Exception: "+ex.toString());
}
}
@Override
public void onDisconnected() {
}
}
MyLocationService.java
Code:
package com.afusionlocation;
import com.google.android.gms.location.LocationClient;
import android.app.IntentService;
import android.content.Intent;
import android.location.Location;
import android.util.Log;
public class MyLocationService extends IntentService {
public MyLocationService(String name) {
super(name);
}
@Override
protected void onHandleIntent(Intent intent) {
Location location = intent.getParcelableExtra(LocationClient.KEY_LOCATION_CHANGED);
if(location !=null){
Log.i("Error", "onHandleIntent " + location.getLatitude() + "," + location.getLongitude());
}
}
}

How to add sound with ImageSwitcher

Respected developers , I m creating app of alphabets , I am unable to add sound with imageswitcher,
I want when user press next button , It should give next image with its sound
my code is
Code:
I have sound in Row folder name a,b,c
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;
public class New extends ActionBarActivity implements ViewFactory {
ImageSwitcher is;
int [] imgid = {R.drawable.i1,
R.drawable.i2,
R.drawable.i3,
R.drawable.i4};
Button prev, next;
int count =0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.poetry);
final Button switchact = (Button) findViewById(R.id.btn1);
switchact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent act2 = new Intent(view.getContext(), MainActivity.class);
startActivity(act2);
}
});
is = (ImageSwitcher)findViewById(R.id.imageSwitcher1);
prev = (Button)findViewById(R.id.button1);
next = (Button)findViewById(R.id.button2);
is.setFactory(this);
is.setInAnimation(this, android.R.anim . slide_in_left);
is.setOutAnimation(this, android.R.anim.slide_out_right);
prev.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(count>0)
{
count--;
try{
is.setImageResource(imgid[count]);
}
catch(Exception e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(New.this, "First", Toast.LENGTH_LONG).show();
}
}
});
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(count<imgid.length)
{
try{
is.setImageResource(imgid[count]);
}
catch(Exception e)
{
e.printStackTrace();
}
count++;
}
else
{
Toast.makeText(New.this, "Last", Toast.LENGTH_LONG).show();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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);
}
public boolean appnot(View v){
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "http://rafeeqsir.in";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "I found a best Urdu Learing App Please try");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
return false;
}
public void about(View v){
{
new AlertDialog.Builder(this)
.setTitle(R.string.app_about)
.setNegativeButton(R.string.str_ok,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialoginterface, int i)
{
}
})
.show();
}
}
public void exit(View v){
{
new AlertDialog.Builder(this)
.setTitle(R.string.app_exit)
.setIcon(R.drawable.ic_launcher)
.setMessage(R.string.app_exit_message)
.setNegativeButton(R.string.exit,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialoginterface, int i)
{
System.exit(0);
}
})
.show();
}
}
@Override
public View makeView() {
// TODO Auto-generated method stub
ImageView iv = new ImageView(this);
iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
iv.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
return iv;
}
}
please help me about it

Categories

Resources