I have a problema with my service. I have 3 button, the first one call service in order to get numbers at randon and show them in a textbox every 10 second, the second button call service in order to get numbers at rand every I press that button and the last button must stop the service but I cannot when I press it and when I close the app and open again the service run automatically I do not understand!!
There is my service class
public class MyService extends Service{
public static final String NEW_DATA = "com.example.t8ej1.MyService.NEW_DATA";
private static final String stringUrl =
"http://www.imaginaformacion.com/recursos/rand.php";
private static final int updateInterval = 1000;
private Timer updateTimer;
private TimerTask doRefresh;
private String data;
public int service_id;
private IBinder binder = new MyBinder ();
public class MyBinder extends Binder {
MyService getService() {
return MyService.this;
}}
private void updateData() {
// Nos conectamos al servicio web y obtenemos los datos
try{
URL url = new URL(stringUrl);
HttpURLConnection httpURLConnection =(HttpURLConnection) url.openConnection();
int responseCode = httpURLConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
InputStream in = httpURLConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
data= reader.readLine();
in.close();
announceData();
}
}
catch( MalformedURLException e){
Log.e("Service", e.getMessage());
}catch(IOException e){
Log.e("Service", e.getMessage());
}
}
private void announceData() {
// Lanzamos el broadcast con el intent y los datos
Intent intent = new Intent(NEW_DATA);
intent.putExtra("data", data);
sendBroadcast(intent);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return binder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
// Creamos el Timer y el TimerTask
service_id=startId;
updateTimer = new Timer();
doRefresh = new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
updateData();
}
};
// Lo programamos para que se lance cada updateInterval milisegundos
updateTimer.scheduleAtFixedRate(doRefresh, 0, updateInterval);
// Queremos que el servicio esté siempre encendido
return Service.START_STICKY;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
Log.e("mm", "4444");
super.onDestroy();
}
public String getData() {
return data;
}}
There is my activity class
public class Service extends Activity {
private MyServiceReceiver myReceiver;
private MyService myService;
TextView txtManual;
TextView txtAuto;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service);
bindService(new Intent(Service.this, MyService.class),
myConnection,
Context.BIND_AUTO_CREATE);
IntentFilter filter;
filter = new IntentFilter(MyService.NEW_DATA);
myReceiver = new MyServiceReceiver();
registerReceiver(myReceiver, filter);
txtAuto = (TextView) findViewById(R.id.txtAuto);
txtManual = (TextView) findViewById(R.id.txtManual);
Button cmdStart = (Button) findViewById(R.id.cmdStart);
Button cmdRefresh = (Button) findViewById(R.id.cmdRefresh);
Button cmdStop = (Button) findViewById(R.id.cmdStop);
cmdStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
unbindService(myConnection);
stopService(new Intent(Service.this, MyService.class));
}
});
cmdRefresh.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
txtManual.setText(myService.getData());
}
});
cmdStart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startService(new Intent(Service.this, MyService.class));
}
});
}
private ServiceConnection myConnection = new ServiceConnection () {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
myService = ((MyService.MyBinder) service).getService();
}
#Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
myService=null;
}
};
public class MyServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
txtAuto.setText(intent.getStringExtra("data"));
}
}
#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
protected void onPause() {
// TODO Auto-generated method stub
//unregisterReceiver(myReceiver);
super.onPause();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
unregisterReceiver(myReceiver);
super.onStop();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}}
unbind service using unbindService() in your onStop() of MyService class (Your Service),
and then call stopService in Service class (your Activity)
Related
First time to use AIDL. I want to test it.
Below is my code:
MainActivity:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "CalculateClient";
private Button btnCalculate;
private EditText etNum1;
private EditText etNum2;
private TextView tvResult;
private CalculateInterface mService;
private ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
logE("disconnect service");
mService = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
logE("connect service");
mService = CalculateInterface.Stub.asInterface(service);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle args = new Bundle();
Intent intent = new Intent("com.example.calculate.CalculateService");
intent.putExtras(args);
bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
etNum1 = (EditText) findViewById(R.id.editText);
etNum2 = (EditText) findViewById(R.id.editText2);
tvResult = (TextView) findViewById(R.id.textView);
btnCalculate = (Button) findViewById(R.id.button);
btnCalculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
logE("Start..");
try {
double num1 = Double.parseDouble(etNum1.getText().toString());
double num2 = Double.parseDouble(etNum2.getText().toString());
logE(Double.toString(num1));
logE(Double.toString(num2));
String answer = "Result:" + mService.doCalculate(num1, num2); //this line BUG
tvResult.setTextColor(Color.BLUE);
tvResult.setText(answer);
} catch (RemoteException ignored) {
}
}
});
}
private void logE(String str) {
Log.e(TAG, "--------" + str + "--------");
}
}
MyTestService:
package com.radio.miao.aidltest;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
public class MyTestService extends Service {
private static final String TAG = "CalculateService";
private final CalculateInterface.Stub mBinder = new CalculateInterface.Stub() {
#Override
public double doCalculate(double a, double b) throws RemoteException {
// TODO Auto-generated method stub
Log.e("Calculate", "remote");
return b + a;
}
};
private static void logE(String str) {
Log.e(TAG, "--------" + str + "--------");
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
logE("onBind()");
return mBinder;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
logE("onCreate()");
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
logE("onStart()");
super.onStart(intent, startId);
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
logE("onUnbind()");
return super.onUnbind(intent);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
logE("onDestroy()");
super.onDestroy();
}
}
<service android:name="com.radio.miao.aidltest.MyTestService">
<intent-filter>
<action android:name="com.radio.miao.aidltest.MyTestService" />
</intent-filter>
package com.radio.miao.aidltest;
// Declare any non-default types here with import statements
interface CalculateInterface {
double doCalculate(double a, double b);
}
The error is
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.radio.miao.aidltest.MainActivity$2.onClick(MainActivity.java:79)
The following line creates an intent for an invalid service:
Intent intent = new Intent("com.example.calculate.CalculateService");
The correct should be:
Intent intent = new Intent(this,MyTestService.class);
Anyone can help me to debug where I m going wrong. Test Code may get from:
https://drive.google.com/file/d/0Bz1lc03pNQm6Qkw3bE93dWxjdXc/view?usp=sharing
Scenario, I have 3 activities
Main, Splash and menu. First I call Splash activity for 5 seconds after 5 seconds I call menu activity its not working from menu I want to call Main activity. If I skip Menu activity than its working fine.
Splash Activity
public class Splash extends Activity{
MediaPlayer ourSong;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
ourSong = MediaPlayer.create(Splash.this, R.raw.dj);
ourSong.start();
Thread timer = new Thread()
{
public void run()
{
try
{
sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
Intent start = new Intent("com.example.test.menu");
startActivity(start);
}
}
};
timer.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
ourSong.release();
finish();
}
}
Menu Activity
public class menu extends ListActivity{
String classes[] = {"MainActivity", "example1", "example1", "example1", "example1"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(menu.this, android.R.layout.simple_list_item_1, classes));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String cheese = classes[position];
try
{
Class ourclass = Class.forName("com.example.test."+cheese);
Intent ourIntent = new Intent(menu.this, ourclass);
startActivity(ourIntent);
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
Main Activity
public class MainActivity extends Activity {
int counter;
Button add, subtruct;
TextView textarea;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 0 ;
add = (Button)findViewById(R.id.button1);
subtruct = (Button)findViewById(R.id.button2);
textarea = (TextView)findViewById(R.id.textView1);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
textarea.setText("Your total is"+counter);
}
});
subtruct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
textarea.setText("Your total is"+counter);
}
});
}
}
Your code:
Thread timer = new Thread()
{
public void run()
{
try
{
sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
Intent start = new Intent("com.example.test.menu");
startActivity(start);
}
}
};
timer.start();
Right code:
Thread timer = new Thread()
{
public void run()
{
try
{
sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
Intent start = new Intent(Splash.this, menu.class);
startActivity(start);
}
}
};
timer.start();
Tip: Don't use lowerCase for Class Names
public class MainActivity extends Activity implements OnClickListener {
Button start,stop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start=(Button) findViewById(R.id.button1);
stop=(Button) findViewById(R.id.button2);
start.setOnClickListener(this);
stop.setOnClickListener(this);
TelecomManager tm=(TelecomManager) getSystemService(TELEPHONY_SERVICE);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(this,MyService.class);
if(v.getId()==R.id.button1) {
startService(i);
} else if(v.getId()==R.id.button2) {
stopService(i);
}
}
}
MyService.java
public class MyService extends Service {
MediaPlayer player;
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
player=MediaPlayer.create(this, R.raw.song1);
}
#Override
#Deprecated
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
player.start();
super.onStart(intent, startId);
}
#Override
public void onDestroy() {
if (!(player == null)) {
if (player.isPlaying()) {
player.stop();
player.release();
player = null;
}
}
In your Service you could register a PhoneStateListener via TelephonyManager.listen(PhoneStateListener, int)
But as the interface is quite big you could also just register a BroadcastReceiver in your Service
IntentFilter phoneStateFilter = new IntentFilter(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
registerReceiver(phoneStateReceiver, phoneStateFilter);
In your BroadcastReceiver you check the phone state by
String phoneState = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
I'm trying to write a simple app that updates the MainActivity with the Lat/Lng values returned by the service. But it always returns the null value. I have added permissions and added TheService.java as service in AndroidManifest.xml file...Kindly tell me where I have gone wrong.
MainActivity.java
public class MainActivity extends Activity {
TextView tv1, tv2;
IntentFilter filter;
receive rec;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 =(TextView)findViewById(R.id.textView1);
tv2 = (TextView)findViewById(R.id.textView2);
filter = new IntentFilter("Updated");
rec = new receive();
Intent gps_int = new Intent(this,TheService.class);
startService(gps_int);
}
#Override
public void onPause()
{
super.onPause();
unregisterReceiver(rec);
}
#Override
public void onResume()
{
super.onResume();
rec = new receive();
registerReceiver(rec, filter);
}
#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 receive extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
tv1.setText(intent.getExtras().getString("lat"));
tv2.setText(intent.getExtras().getString("lon"));
Toast.makeText(getApplicationContext(), "Toast Executed", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "BR Latitude "+intent.getExtras().getString("lat"),Toast.LENGTH_SHORT).show();
}
}}
TheService.java
public class TheService extends Service implements LocationListener {
LocationManager lm;
Location loc;
double lat = 0;
double lon = 0;
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
lm=(LocationManager)getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
onLocationChanged(loc);
return START_STICKY;
}
#Override
public void onCreate()
{
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
updateui(location);
}
private void updateui(Location location) {
// TODO Auto-generated method stub
lat = location.getLatitude();
lon = location.getLongitude();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent gps_intent = new Intent("Updated");
gps_intent.putExtra("lat", lat);
gps_intent.putExtra("lon", lon);
sendBroadcast(gps_intent);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}}
You should use the Google Play Services for the location, that's easier to handle.
What for do you even need a Service? Having a location listener in your Activity is totally fine.
If you want to stay with the Service, than bind the Activity to it, instead of using a Broadcast.
I want to send data from one application A to other application B using AIDL file. My appl A is like below,
public class LibValue {
public static native int intFromJNI(int n);
static {
System.loadLibrary("hello");
System.out.println("LibValue : Loading library");
}
I am getting value from JNI file to above class. The data from above class to send another app B using AIDL service is like below.
IEventService.aidl
interface IEventService {
int intFromJNI(in int n);
}
for this I written IEventImpl.java class
public class IEventImpl extends IEventService.Stub{
int result;
#Override
public int intFromJNI(int n) throws RemoteException {
// TODO Auto-generated method stub
System.out.println("IEventImpl"+LibValue.intFromJNI(n));
return LibValue.intFromJNI(n);
}
}
To access above class I writtn service class like below
public class EventService extends Service {
public IEventImpl iservice;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
Log.i("EventService", "indside onBind");
return this.iservice;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
this.iservice = new IEventImpl();
Log.i("EventService", "indside OncREATE");
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
return super.onUnbind(intent);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
this.iservice = null;
super.onDestroy();
}
All above classes are server side. The below class is Client(app) class to access data.
public class EventClient extends Activity implements OnClickListener, ServiceConnection{
public IEventService myService;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_client);
button = (Button)findViewById(R.id.button1);
this.button.setOnClickListener(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (!super.bindService(new Intent(IEventService.class.getName()),
this, BIND_AUTO_CREATE)) {
Log.w("EventClient", "Failed to bind to service");
System.out.println("inside on resume");
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
super.unbindService(this);
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
this.myService = IEventService.Stub.asInterface(service);
Log.i("EventClient", "ServiceConnected");
}
#Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
Log.d("EventClient", "onServiceDisconnected()'ed to " + name);
// our IFibonacciService service is no longer connected
this.myService = null;
}
I am trying to access data from service class but not able to find out the way. can anybody tell how to access data from service to client application ?
Thanks