IntentService doesn't want to start - android

I want to start IntentService from an activity but didn't running. I have tried tested it by using toast or Log but still didn't give any reaction.
Is there i have gone wrong ?
This is my activity:
public class backgroundApplication extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
findViewById(R.id.cmdServiceIA).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent msgIntent = new Intent(backgroundApplication.this, Service2.class);
startService(msgIntent);
}
});
This is my intentService :
public class Service extends IntentService{
#Override
protected void onHandleIntent(Intent intent) {
mHandler.post(new DisplayToast(this, "Service Start!"));
}
public class DisplayToast implements Runnable {
private final Context mContext;
String mText;
public DisplayToast(Context mContext, String text){
this.mContext = mContext;
mText = text;
}
public void run(){
Toast.makeText(mContext, mText, Toast.LENGTH_SHORT).show();
}
}
Any ideas ?

Related

apps extremely slowing down while using broadcastreceiver to communicate with service android

in my app while i am making a communication between service and broadcastreceiver my apps extremely slowing down. if i use only service my apps running ok, but problem occurs when i try to show service's result through broadcast. below my code.
manifest:
<service
android:name=".ServiceClass_GetGps"
android:exported="false" />
broadcastreceiver :
public class FragmentMap extends Fragment implements OnMapReadyCallback{
double lat,lng;
GoogleMap googleMap=null;
public FragmentMap() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setRetainInstance(true);
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_map, null, false);
SupportMapFragment mapFragment=(SupportMapFragment)this.getChildFragmentManager().findFragmentById(R.id.map_FragmentMapId);
mapFragment.getMapAsync(this);
Intent intent=new Intent(getActivity(),ServiceClass_GetGps.class);
getActivity().startService(intent);
return view;
}
#Override
public void onResume() {
super.onResume();
IntentFilter intentFilter=new IntentFilter("imran");
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(broadcastReceiver,intentFilter);
}
#Override
public void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(broadcastReceiver);
}
//broadcast receiver
private BroadcastReceiver broadcastReceiver=new BroadcastReceiver() {
#Override
public void onReceive(final Context context, final Intent intent) {
//String result=intent.getStringExtra("result");
// Toast.makeText(getActivity(), "Lat " +intent.getStringExtra("LAT") +" Lng "+intent.getStringExtra("LNG"), Toast.LENGTH_SHORT).show();
Handler handler=new Handler();
handler.post(new Runnable() {
#Override
public void run() {
context.startService(new Intent(context.getApplicationContext(),ServiceClass_GetGps.class));
if(intent.getStringExtra("LAT")!=null && intent.getStringExtra("LNG")!=null){
lat=Double.valueOf(intent.getStringExtra("LAT"));
lng=Double.valueOf(intent.getStringExtra("LNG"));
LatLng latLng=new LatLng(lat,lng);
if(googleMap!=null){
googleMap.addMarker(new MarkerOptions().position(latLng));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,16));
}else {
Toast.makeText(getActivity(),"Map is null",Toast.LENGTH_LONG).show();
}
}
}
});
}
};
#Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap=googleMap;
}
service class:
public class ServiceClass_GetGps extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,LocationListener{
private HandlerThread handlerThread;
ServiceHandler serviceHandler;
LocalBroadcastManager localBroadcastManager;
private final static class ServiceHandler extends Handler {
public ServiceHandler(Looper looper){
super(looper);
}
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
}
#Override
public void onCreate() {
super.onCreate();
handlerThread=new HandlerThread("com.example.imranrana.datingapp");
handlerThread.start();
serviceHandler=new ServiceHandler(handlerThread.getLooper());
localBroadcastManager=LocalBroadcastManager.getInstance(this);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
final Handler handler=new Handler();
new Thread(new Runnable() {
#Override
public void run() {
// Intent intent=new Intent("com.example.imranrana.datingapp");
// intent.putExtra("result","Imran");
// localBroadcastManager.sendBroadcast(intent);
handler.post(new Runnable() {
#Override
public void run() {
Intent intent1=new Intent("imran");
intent1.putExtra("LAT","23.8758448");
intent1.putExtra("LNG","90.3981515");
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent1);
Toast.makeText(getApplicationContext(),"Service test",Toast.LENGTH_LONG).show();
}
});
handler.postDelayed(this,5000);
}
}).start();
return START_STICKY;
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getApplicationContext(),"apps stopped",Toast.LENGTH_LONG).show();
sendBroadcast(new Intent());
}
can anyone please solve my problem .
i just solved my problem by myself just removing restart command of service from broadcastreceiver . thanks

Update TextView in Broadcast Receivers

I want to update my text view on the receivers side as soon as I receive the message. I have the following code which creates the instance of main activity and uses it in the Broadcast receiver to update UI. But the text view isn't getting updated??
public class Mainactivity extends activity{
private static MainActivity ins;
public static MainActivity getInst()
{
return ins;
}
protected void onCreate(Bundle savedInstanceState) {
ins=this;}
public void updateUI(final String s)
{
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
TextView textView=(TextView) findViewById(R.id.textView);
textView.setText(s);
}
});
}
In the smsreceiver class
public class smsreceiver extends BroadcastReceiver
{
try{
if (MainActivity.getInst()!=null)
MainActivity.getInst().updateUI(str);
}
catch(Exception e){
e.printStackTrace();
}
}
Please help me out!!
What if you try like below:
public class Mainactivity extends activity{
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.your_layout);
//register your receiver
}
protected void onDestroy() {
//unregister your receiver
super.onDestroy();
}
public void updateUI(final String s)
{
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
TextView textView=(TextView) findViewById(R.id.textView);
textView.setText(s);
}
});
}
private class smsreceiver extends BroadcastReceiver
{
try{
updateUI(str)
}
catch(Exception e){
e.printStackTrace();
}
}
}
this is my code base you code it can work
public class MainActivity extends Activity
{
private static MainActivity ins;
private Button mButton;
public static MainActivity getInst()
{
return ins;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ins = this;
mButton = (Button) findViewById(R.id.but_send);
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent inten = new Intent(MainActivity.this, SmsReceiver.class);
inten.setAction("com.example.demo.action.info");
sendBroadcast(inten);
}
});
}
public void updateUI(final String s)
{
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
TextView textView=(TextView) findViewById(R.id.tv_info);
textView.setText(s);
}
});
}
}
public class SmsReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent) {
try {
if (MainActivity.getInst() != null)
MainActivity.getInst().updateUI("Hello World");
} catch (Exception e) {
e.printStackTrace();
}
}
}
<receiver android:name="com.example.demoexample.SmsReceiver" >
<intent-filter>
<action android:name="com.example.demo.action.info" />
</intent-filter>
</receiver>

Receive Listener onResults() from a different activity

I'm developing an App with SpeechRecognizer. I will use it in different activities for different uses and It's a bit dirty add the same code all time to different classes. So I moved my custom RecognitionListener to a new class. In that way I just initialize it when I want from my activities. But I canĀ“t find a way to receive the result of the listener (in this case, an ArrayList of possible values for the speech recognized) in my current activity to use it.
I have tried to implement it through an interface, but I think that I did it in a wrong way. My Listener code is this:
public class SpeechRecognitionListener implements RecognitionListener
{
private final String TAG = "SpeechRecognitionListener";
private Intent mSpeechRecognizerIntent;
private SpeechRecognizer mSpeechRecognizer;
public SpeechRecognitionListener(Intent speechRecognizerIntent, SpeechRecognizer speechRecognizer ) {
mSpeechRecognizerIntent = speechRecognizerIntent;
mSpeechRecognizer = speechRecognizer;
}
#Override
public void onBeginningOfSpeech()
{
//Log.d(TAG, "onBeginingOfSpeech");
}
#Override
public void onBufferReceived(byte[] buffer)
{
}
#Override
public void onEndOfSpeech()
{
//Log.d(TAG, "onEndOfSpeech");
}
#Override
public void onError(int error)
{
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
//Log.d(TAG, "error = " + error);
}
#Override
public void onEvent(int eventType, Bundle params)
{
}
#Override
public void onPartialResults(Bundle partialResults)
{
}
#Override
public void onReadyForSpeech(Bundle params)
{
Log.d(TAG, "onReadyForSpeech"); //$NON-NLS-1$
}
#Override
public void onResults(Bundle results)
{
//I want to recieve this array in my main activity
ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
}
#Override
public void onRmsChanged(float rmsdB)
{
}
}
I just want to receive the onResult() array in my current activity to work with it.
Try to define an interface first:
public interface RecognitionCallback
{
abstract void onRecoginitionFinished(ArrayList<String> matches);
}
Now let your activity that needs to be called back implement this interface. For example:
public class MainActivity extends AppCompatActivity implements RecognitionCallback {
...
public void onRecognitionFinished(ArrayList<String> matches)
{
//do your things with the data
}
}
Also add some properties of SpeechRecognitionListener class:
public class SpeechRecognitionListener implements RecognitionListener
{
private final String TAG = "SpeechRecognitionListener";
private Intent mSpeechRecognizerIntent;
private SpeechRecognizer mSpeechRecognizer;
private RecognitionCallback mCallback
public SpeechRecognitionListener(Intent speechRecognizerIntent, SpeechRecognizer speechRecognizer, RecognitionCallback callback ) {
mSpeechRecognizerIntent = speechRecognizerIntent;
mSpeechRecognizer = speechRecognizer;
mCallback = callback;
...
public void onResults(Bundle results)
{
ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
mCallback.onRecognitionFinished(matches);
}
}
And finally in your activity where you need to get called back write this:
SpeechRecognitionListener listener = new SpeechRecognitionLinstner(intent,recognizer,this);

How to display the value in the text field of Activity which is updated from service class?

This is my service class in that i increment the i value based on time...
public class BackService extends Service {
int i=0;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
pollForUpdates();
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
private void pollForUpdates() {
Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Log.v("Service class called", "service class called "+i);
getRunningApps();
i++;
}
},0,1000);
}
private void getRunningApps()
{
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
I want to append the i value to the TextView. i.e the TextView value is dynamically change based on i value...
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(this, BackService.class));
TextView tx=(TextView)findViewById(R.id.textView1);
}}
how to append the i value to tx...
Thank you in advance..
You will need to register Broadcast receiver for Sending data back from Service to Activity.see these usefull example for communication between Activity to service :
http://androidexperinz.wordpress.com/2012/02/14/communication-between-service-and-activity-part-1/
http://androidexperinz.wordpress.com/2012/02/21/communication-between-service-and-activity-part-2/
http://blog.philippheckel.com/2012/06/10/android-example-communication-between-activity-and-service-using-messaging/
Use this
public class MainActivity extends Activity {
TextView tx;
RefreshBroadcastReciver mBroadCastReciver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(this, BackService.class));
tx =(TextView)findViewById(R.id.textView1);
}
#Override
protected void onResume() {
super.onResume();
mBroadCastReciver = new RefreshBroadcastReciver();
registerReceiver(mBroadCastReciver, new IntentFilter("sendData"));
}
private class RefreshBroadcastReciver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
tx.setText(intent.getIntExtra("i", 0)+"");
}
}
#Override
protected void onStop() {
super.onStop();
if(mBroadCastReciver!=null)
unregisterReceiver(mBroadCastReciver);
}
}
and your service is here
public class BackService extends Service {
int i=0;
Intent intent1;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
pollForUpdates();
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
intent1=new Intent("sendData");
}
private void pollForUpdates() {
Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Log.v("Service class called", "service class called "+i);
getRunningApps();
i++;
Message msg=new Message();
msg.arg1=i;
handler.sendMessage(msg);
}
},0,1000);
}
private void getRunningApps()
{
}
#Override
public void onDestroy() {
super.onDestroy();
}
protected Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
intent1.putExtra("i", msg.arg1);
sendBroadcast(intent1);
}
};
}

How to add a listener to a running service on Android

I added a listener to the service called "BindService".
And then I killed the Activity which have added the listener to the "BindService".
"BindService" is still running. I can see it on DDMS of eclipse.
Now I started the Activity again and I want to add a listener to the "BindService" again.
How could I?
"BindService" is just a service which is counting number.
With the following code, after I start the Activity again and tap the button "button_sendwords", it starts to count number from 0 again. That is not my purpose.
public class MainActivity extends Activity {
private ICallbackService service;
private static final int CALLBACK_MESSAGE = 1;
private Handler handler = new Handler(){
#Override
public void dispatchMessage(Message msg){
if(msg.what == CALLBACK_MESSAGE){
TextView resultlbl = (TextView)findViewById(R.id.label_result);
resultlbl.setText((String)msg.obj);
}else{
super.dispatchMessage(msg);
}
}
};
private ICallbackListener listener = new ICallbackListener.Stub() {
#Override
public void receiveMessage(String message) throws RemoteException {
handler.sendMessage(handler.obtainMessage(CALLBACK_MESSAGE, message));
}
};
private ServiceConnection conn = new ServiceConnection(){
#Override
public void onServiceConnected(ComponentName name, IBinder binder) {
service = ICallbackService.Stub.asInterface(binder);
try{
service.addListener(listener);
}catch(RemoteException e){
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnSendWords = (Button)findViewById(R.id.button_sendwords);
btnSendWords.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, BindService.class);
bindService(intent, conn, BIND_AUTO_CREATE);
}
});
}
}

Categories

Resources