How to pass context var when I use IntentService in BroadcastReceiver? - android

I need to use Context object in the function killCall, but I don't know how to pass the Context object to KillCall, could you help me? Thanks!
public class ReceiverCall extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent msgIntent = new Intent(context, InternetServerCall.class);
context.startService(msgIntent);
}
}
public class InternetServerCall extends IntentService{
public InternetServerCall(String name) {
super("InternetServerCall");
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
HandleCall.killCall(context); //Need context
}
}
public class HandleCall {
public static boolean killCall(Context context) {
try {
....
Toast.makeText(context, "PhoneStateReceiver kill incoming call Ok",Toast.LENGTH_SHORT).show();
} catch (Exception ex) { // Many things can go wrong with reflection calls
return false;
}
return true;
}
}

You can get Context into InternetServerCall by doing InternetServerCall.this. And this is because all Android Components overrides Context class, on of them is IntentService.
You can also use getApplicationContext() into IntentService to get context. You can read my another similar answer Pass a Context an IntentService.
But you can not display Toast from IntentService directly, because it needs UI thread but IntentService runs into background thread. You need to use Handler to show Toast, like below example
public class TestService extends IntentService {
private Handler handler;
public TestService(String name) {
super(name);
// TODO Auto-generated constructor stub
}
public TestService () {
super("TestService");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
handler = new Handler();
return super.onStartCommand(intent, flags, startId);
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Handling Intent..", Toast.LENGTH_LONG).show();
}
});
}
}

An IntentService is subclass of Context so you can pass in this:
#Override
protected void onHandleIntent(Intent intent) {
HandleCall.killCall(this);
}

Related

Android get information from service

I made an service that triggers every 10 sec. How to connect service to activity when it triggers. Example i refresh my local DB, when appears an update Activity send an Toast.
AlarmService.class
#SuppressLint("SimpleDateFormat")
public class AlarmService extends Service {
Handler mHandler;
private PendingIntent pendingIntent;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
}
public void f() {
Toast t = Toast.makeText(this, "Service is still running",
Toast.LENGTH_SHORT);
t.show();
}
#Override
#Deprecated
public void onStart(Intent intent, int startId) {
Toast t = Toast.makeText(this, "Service started", Toast.LENGTH_SHORT);
t.show();
// TODO Auto-generated method stub
super.onStart(intent, startId);
mHandler = new Handler();
Runnable r = new Runnable() {
#Override
public void run() {
f();
mHandler.postDelayed(this,10000);
}
};
mHandler.postDelayed(r, 10000);
}
}
MainActivity.class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent serviceIntent = new Intent(this,AlarmService.class);
startService(serviceIntent);
}
}
Use broadcast receiver like this
public static class MyExtBroadcastReceiver extends BroadcastReceiver {
public MyExtBroadcastReceiver() {
super();
}
#Override
public void onReceive(Context context, Intent intent) {
//Call your activity here
}
Make a method for setting the alarm
public void setAlarm(){
f(); // call your method f() here
AlarmManager am=(AlarmManager)getSystemService(ALARM_SERVICE);
Intent alarmintent1 = new Intent(this, MyExtBroadcastReceiver.class);
PendingIntent sender1=PendingIntent.getBroadcast(this, 100, alarmintent1, PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);
try {
am.cancel(sender1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("ex....."+e);
}
Calendar cal=Calendar.getInstance();
cal.add(Calendar.Seconds,10);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000*10*60, sender1);
Call this method from OnCreate()
#Override
public void onCreate() {
setAlarm();
}
}
You can use LocalBroadcastManager, Messenger, ResultReceiver to send data from service to Activity.
Here is an example that uses ResultReceiver to send updated data from Service to Activity.

Use AlarmManger to call a specific method in Activity

How can I use AlarmManager to call a specific method of an Activity, in my case I need to stop a service by calling KillMyServer method of my Activity 2 hours later from know.
I can't use Timer or postDelayed, because if an app goes to background Android may close it after a while, but AlarmManager will survive.
why to use Alarm here? you can stop service by calling stopself() method on Service.
public class MyService extends Service {
public static final String ACTION_START_TIMER = "com.sample.myapp.action.ACTION_START_TIMER";
private TimerReceiver receiver;
#Override
public void onCreate() {
super.onCreate();
receiver = new TimerReceiver();
IntentFilter filter = new IntentFilter(ACTION_START_TIMER);
registerReceiver(receiver, filter);
}
public void runKillTimer() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
stopSelf();
}
}, 2 * 60 * 60 * 1000);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
private class TimerReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
runKillTimer();
}
}
}
public class MyActivity extends Activity {
#Override
protected void onStop() {
super.onStop();
Intent intent = new Intent(MyService.ACTION_START_TIMER);
sendBroadcast(intent);
}
}

Android and Java Static variable Initialization

This is my code for service class here previous_network_type is global static variable it is not initialized in oncreate() or onstartcommand() function also not from activity on create function why is that any help?? whenever i used it, it gives me 0 value it should give me 10 after starting of this service but returns 0. To be more clear
First MyService has previous_network_type variable i want to assign it a value in oncreate or oncommand function
which i'l use in another class which is broadcast receiver
and you know that broadcast receiver runs only when an event is occur so what m trying to do whenever a particular event occur i want to access this value
public class MyService extends Service {
static int previous_network_type=0;
public void onCreate() {
previous_network_type=10;
};
public int onStartCommand(Intent intent, int flags, int startId) {
previous_network_type=10;
return Service.START_STICKY;
}
}
and the code of other class(Broadcast receiver is given below)
public void onReceive(Context context, Intent intent)
{
MyService.current_network_type=MyService.previous_network_type;
}
public class MainActivity extends Activity {
Intent i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
i=new Intent(this,MyService.class);
startService(i);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();;
stopService(i);
}
}
public class MyService extends Service {
static int previous_network_type=0;
public void onCreate() {
previous_network_type=10;
};
public int onStartCommand(Intent intent, int flags, int startId) {
previous_network_type=10;
Log.e("check","Value"+previous_network_type);
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
check once if you have defined the Service in Android.manifest.xml
<service android:name="com.example.kuchbhi.MyService"
></service>
Just make sure that you are accessing the value after the service has been created/started.
Try to debug.

android Activity and a service with sms contentobserver

My app requirements
The application will have an activity and a service.
The service has a sms contentobserver.
After application installation the Service should run all the time irrespective of
application active or not
The registration and unregistration of contentobserver inside the service should
be controlled from the activity.
On uninstallation of the application the service should be destroyed.
I tried some code. In oncreate of the service i have done resgitartion of content observer
and ondestroy i unregistered it. I have used start and stop service from the activity.
But even after stop service the onchange method of the content observer is still getting called.
please let me know some sample code and the manifest definition of this service.
public class MyActivity extends ListActivity implements OnInitListener {
#Override
protected void onDestroy() {
super.onDestroy(); // let it be here as per the android TTS samples
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent sintent = new Intent(MyActivity.this,MyService.class);
MyActivity.this.startService(sintent);
}
private boolean SSMyservice() {
// TODO Auto-generated method stub
//stop service
Intent sintent = new Intent(MyActivity.this,MyService.class);
MyActivity.this.stopService(sintent);
//do some work
//start service again
MyActivity.this.startService(sintent); //start service again
return true;
} //importdata
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.TTSread:
return true;
case R.id.SSS:
SSMyservice();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Log.v(TAG,"option menu created");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.omenu, menu);
return true;
}
}
------------end MyActivity---------------------
----------------------------------
public class MyService extends Service {
protected SmsObserver smsSentObserver=null;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
registersmsevent();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
super.onStartCommand(intent, flags, startId);
return Service.START_STICKY;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregistersmsevent();
}
public void registersmsevent() {
// TODO Auto-generated method stub
if(smsSentObserver == null)
{
final Uri SMS_STATUS_URI = Uri.parse("content://sms");
smsSentObserver = new SmsObserver(new Handler());
MyService.this.getContentResolver().registerContentObserver(SMS_STATUS_URI, true, smsSentObserver);
}
}
public void unregistersmsevent() {
if(smsSentObserver != null)
{
MyService.this.getContentResolver().unregisterContentObserver(smsSentObserver);
smsSentObserver = null;
}
}
public class SmsObserver extends ContentObserver {
Handler handler;
public SmsObserver(Handler handler) {
super(handler);
// TODO Auto-generated constructor stub
this.handler = handler;
}
#Override
public boolean deliverSelfNotifications() {
return true;
}
#Override
public void onChange(boolean selfChange) {
//my code........
super.onChange(selfChange);
}
}//End of class SmsObserver
}//end of service
I could fix the issue. This was a timing issue. Stopping service takes sometime.

what happens when a service is started multiple times

I have created a simple service which will increment a counter and log it.
public class AudioService extends Service {
int i=0;
private final IAudioInterface.Stub mBinder = new IAudioInterface.Stub() {
public int getI()
{
return i;
}
};
#Override
public IBinder onBind(Intent intent) {
Log.d("onBind from service","****");
return mBinder;
}
#Override
public void onCreate() {
super.onCreate();
Log.d("onCreate from service","***");
Log.d("i=","="+i);
i=i+1;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("OnDestroy Called from service","***");
}
public void onStartCommand(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d("onStartCommand from service","***");
}
#Override
public boolean onUnbind(Intent intent) {
Log.d("onUnbind from service","***");
return super.onUnbind(intent);
}
i am incrementing the i value in the oncreate method of he service.
The Client Activity is as shown below
public class AidlInterfaceServiceActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
private static final String TAG = "Audio:Service";
IAudioInterface mService = null;
boolean connected = false;
ServiceConnection mConnection = new ServiceConnection(){
public void onServiceConnected(ComponentName arg0, IBinder service) {
// TODO Auto-generated method stub
connected = true;
Log.d("Service connected","**");
mService = IAudioInterface.Stub.asInterface(service);
try {
Log.d("i from client","="+mService.getI());
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
Log.i(TAG, "Service disConnected");
connected = false;
mService= null;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d("on created ","**********");
Intent music = new Intent();
music.setClass(this,AudioService.class);
startService(music);
bindService(music, mConnection, Context.BIND_AUTO_CREATE);
}
The AIDL file is as below
interface IAudioInterface
{
int getI();
}
The problem is when i run the client activity every time the value of i is "0".
i value is not getting incremented.
I have these queries.
1.what happens when the service is started multiple time.
2.what happens when the service is bounded multiple times.
3.what happens to the data members inside the service class when it is started multiple times.Does those data members get reinitialized.
I am really confused ..Any one please help.
Does it help if you declare your counter variable as static?

Categories

Resources