I have two files.
IntentServiceTest1Activity.java
public class IntentServiceTest1Activity extends Activity {
/** Called when the activity is first created. */
public class ResponseReceiver extends BroadcastReceiver {
public static final String ACTION_RESP = "com.mamlambo.intent.action.MESSAGE_PROCESSED";#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
TextView result = (TextView) findViewById(R.id.txt_result);
String text = intent.getStringExtra(SimpleIntentService.PARAM_OUT_MSG);
result.setText(text);
}
}
private ResponseReceiver receiver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IntentFilter filter = new IntentFilter(ResponseReceiver.ACTION_RESP);
filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new ResponseReceiver();
registerReceiver(receiver, filter);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText input = (EditText) findViewById(R.id.txt_input);
String strInputMsg = input.getText().toString();
Intent msgIntent = new Intent(IntentServiceTest1Activity.this, SimpleIntentService.class);
msgIntent.putExtra(SimpleIntentService.PARAM_IN_MSG, strInputMsg);
startService(msgIntent);
}
});
}
}
SimpleIntentService.java
public class SimpleIntentService extends IntentService {
public static final String PARAM_IN_MSG = "imsg";
public static final String PARAM_OUT_MSG = "omsg";
public SimpleIntentService()
{
super("SimpleIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
String msg = intent.getStringExtra(PARAM_IN_MSG);
SystemClock.sleep(30000); // 30 seconds
String resultTxt = msg + " " + DateFormat.format("MM/dd/yy h:mmaa", System.currentTimeMillis());
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(ResponseReceiver.ACTION_RESP);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
broadcastIntent.putExtra(PARAM_OUT_MSG, resultTxt);
sendBroadcast(broadcastIntent);
}
}
Via Log.d(), I can see the onHandleIntent was never called even though the service was started. My Log.d trail goes after startService(msgIntent); and stops there. No Log.d from within onHandleIntent was displayed. What is wrong? And what can I do to make it work?
Thanks!
I solved mine by adding onStartCommand but not overriding it.
public int onStartCommand(Intent intent, int flags, int startId) //sometimes overriding onStartCommand will not call onHandleIntent
{
Logger_.logtoFile(tag, "here..!", 1);
return super.onStartCommand(intent,flags,startId);
}
Related
I wanna implement a Countdown timer with updating TextView and a service so the counting can keep going if the app is in background, foreground or even fully closed.
I examined these codes in a simple project and they worked very well
Service
public class MyService extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
final Integer[] timeRemaining = {intent.getIntExtra("TimeValue", 0)};
final Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Intent intent1local = new Intent();
intent1local.setAction("Counter");
timeRemaining[0]--;
if (timeRemaining[0] <= 0) {
timer.cancel();
}
intent1local.putExtra("TimeRemaining", timeRemaining[0]);
sendBroadcast(intent1local);
}
},
0, 1000);
return super.onStartCommand(intent, flags, startId);
}
}
Main Activity
public class MainActivity extends AppCompatActivity {
private TextView textView;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(this,
new String[]{FOREGROUND_SERVICE},
PackageManager.PERMISSION_GRANTED);
textView = findViewById(R.id.textView);
editText = findViewById(R.id.editText);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("Counter");
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Integer integerTime = intent.getIntExtra("TimeRemaining",
0);
textView.setText(integerTime.toString());
}
};
registerReceiver(broadcastReceiver, intentFilter);
}
public void startButton(View view) {
Intent intentService = new Intent(this, MyService.class);
Integer integerTimeSet =
Integer.parseInt(editText.getText().toString());
intentService.putExtra("TimeValue", integerTimeSet);
startService(intentService);
}
}
But when i implement these codes in an app with fragments (Service codes are in a seperate service class and i put MainActivity codes in a fragment), if you close the app, everything will gone off and you will get an error.
Please help me
I need your detailed advices.
I am building app regarding battery indicator and i am using code from this post.
Getting battery status even when the application is closed
it is working fine when app is closed, but when an app is active or on foreground it did not work or did not send any broadcast.
This is main activity from i start service
public class Main extends Activity {
private MyService service;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (service == null) {
Intent i = new Intent(this, MyService.class);
startService(i);
}
finish();
}
}
Following is the service code.
public class MyService extends Service{
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MyService", "onStartCommand");
// do not receive all available system information (it is a filter!)
final IntentFilter battChangeFilter = new IntentFilter(
Intent.ACTION_BATTERY_CHANGED);
// register our receiver
this.registerReceiver(this.batteryChangeReceiver, battChangeFilter);
return super.onStartCommand(intent, flags, startId);
}
private final BroadcastReceiver batteryChangeReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, final Intent intent) {
checkBatteryLevel(intent);
}
};
private void checkBatteryLevel(Intent batteryChangeIntent) {
// some calculations
final int currLevel = batteryChangeIntent.getIntExtra(
BatteryManager.EXTRA_LEVEL, -1);
final int maxLevel = batteryChangeIntent.getIntExtra(
BatteryManager.EXTRA_SCALE, -1);
final int percentage = (int) Math.round((currLevel * 100.0) / maxLevel);
if(percentage==100)
{
Intent intent = new Intent(getBaseContext(), Last.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(intent);
}
// do not forget to unregister
unregisterReceiver(batteryChangeReceiver);
} }
And when following activity start i did not receive any broadcast.
public class Last extends Activity {
Button btnCancel;
Uri notification;
Ringtone r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_last);
notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
btnCancel = (Button) findViewById(R.id.stopsound);
btnCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
r.stop();
}
});
} }
As I understood,
when you start application in first time, you see nothing, just service is started and a broadcast receiver is registered. When battery level will be changed, the method checkBatteryLevel() is calling and the broadcast receiver will be unregistered. As result you have never received a new changing of battery level.
I have a service and an activity that communicate.
When I click the button(I have galaxy s3 there is only one button) then my activity of course disapear and my service is keep running but if I click the back (touch) button then my service is destroyed.
How can I change that?I want the service to keep running untill the activity destroys it.
EDIT
Here is the code:
Service:
public class MyService extends Service
{
private static final String TAG = "BroadcastService";
public static final String BROADCAST_ACTION = "com.websmithing.broadcasttest.displayevent";
private final Handler handler = new Handler();
private Intent intent;
int counter = 0;
#Override
public void onCreate()
{
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onStart(Intent intent, int startId)
{
// handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
DisplayLoggingInfo();
handler.postDelayed(this, 1000); // 10 seconds
}
};
private void DisplayLoggingInfo() {
intent.putExtra("counter", String.valueOf(++counter));
sendBroadcast(intent);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
handler.removeCallbacks(sendUpdatesToUI);
super.onDestroy();
}
}
Activity:
public class MainActivity extends Activity {
private static final String TAG = "BroadcastTest";
private Intent intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = new Intent(this, MyService.class);
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(MyService.BROADCAST_ACTION));
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateUI(intent);
}
};
#Override
public void onDestroy() {
super.onPause();
unregisterReceiver(broadcastReceiver);
stopService(intent);
}
private void updateUI(Intent intent)
{
String counter = intent.getStringExtra("counter");
Log.d(TAG, counter);
TextView txtCounter = (TextView) findViewById(R.id.textView1);
txtCounter.setText(counter);
}
}
you can put your app in the background instead off finishing it.
#Override
public void onBackPressed() {
moveTaskToBack(true);
// super.onBackPressed();
}
Ofcourse your service stops, when you press the back button. The back button most calls finish() on the activity, and it is destroyed. When you press the other button (the home button), it just minimizes your app, and it will be only destroyed later, when the OS wants to free up space.
If you want to keep your service running, make it a foreground service, and dont stop it on activity destroy.
I want to display an alert when a sms is received, so my idea is to start a new activity that launch the alertdialog.
My service starts with no problem, and starts receiver as well..
I can receive sms and display toast alerts fine.. but i'd like to show a custom alertdialog instead.
This is the activity that starts my service (ServiceExampleActivity ):
public class ServiceExampleActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnStartService = (Button) findViewById(R.id.btnStart);
Button btnStopService = (Button) findViewById(R.id.btnStop);
btnStartService.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
StartMyService();
}
});
btnStopService.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
StopMyService();
}
});
}
private void StartMyService() {
Intent myServiceIntent = new Intent(this, ServiceTest.class);
startService(myServiceIntent);
}
private void StopMyService() {
Intent myServiceIntent = new Intent(this, ServiceTest.class);
stopService(myServiceIntent);
}
}
This is my Service (ServiceTest):
public class ServiceTest extends Service {
private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
private BroadcastReceiver myBroadcastReceiver = null;
#Override
public void onCreate() {
super.onCreate();
final IntentFilter theFilter = new IntentFilter();
theFilter.addAction(ACTION);
this.myBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
StartDialogActivity(context, intent);
}
};
this.registerReceiver(myBroadcastReceiver, theFilter);
}
#Override
public IBinder onBind(Intent arg) {
return null;
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d("ServiceTest", "Started");
Toast.makeText(this, "Service started...", 3000).show();
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(myBroadcastReceiver);
Toast.makeText(this, "Service destroyed...", 3000).show();
}
private void StartDialogActivity(Context context, Intent intent) {
Intent dlgIntent = new Intent(context, DialogActivity.class);
dlgIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(dlgIntent);
}
}
And this is the activity i want to launch to display the alertdialog normally..
public class DialogActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog);
}
}
When it tries to start the activity, the app crashes..
Can you tell me were is the error..??
Like this, you want start activity from service
Intent dlgIntent = new Intent(context, DialogActivity.class);
dlgIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(dlgIntent );
I have two relatively simple codes. One main activity and one intent service.
Main activity
public class IntentServiceTest1Activity extends Activity {
/** Called when the activity is first created. */
public class ResponseReceiver extends BroadcastReceiver {
public static final String ACTION_RESP =
"com.mamlambo.intent.action.MESSAGE_PROCESSED";
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
TextView result = (TextView) findViewById(R.id.txt_result);
String text = intent.getStringExtra(SimpleIntentService.PARAM_OUT_MSG);
result.setText(text);
}
}
private ResponseReceiver receiver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IntentFilter filter = new IntentFilter(ResponseReceiver.ACTION_RESP);
filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new ResponseReceiver();
registerReceiver(receiver, filter);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener(){
public void onClick(View v){
EditText input = (EditText) findViewById(R.id.txt_input);
String strInputMsg = input.getText().toString();
Intent msgIntent = new Intent(IntentServiceTest1Activity.this, SimpleIntentService.class);
msgIntent.putExtra(SimpleIntentService.PARAM_IN_MSG, strInputMsg);
startService(msgIntent);
}
});
}
}
Intent Service
public class SimpleIntentService extends IntentService {
public static final String PARAM_IN_MSG = "imsg";
public static final String PARAM_OUT_MSG = "omsg";
public SimpleIntentService() {
super("SimpleIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
String msg = intent.getStringExtra(PARAM_IN_MSG);
SystemClock.sleep(30000); // 30 seconds
String resultTxt = msg + " "
+ DateFormat.format("MM/dd/yy h:mmaa", System.currentTimeMillis());
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(ResponseReceiver.ACTION_RESP);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
broadcastIntent.putExtra(PARAM_OUT_MSG, resultTxt);
sendBroadcast(broadcastIntent);
}
}
Logcat says the
06-26 04:16:00.545: W/ActivityManager(67): Unable to start service Intent {
cmp=com.intentservicetest1/.SimpleIntentService (has extras) }: not found
What can I do to correct this?
Make sure you have Register IntentService in AndroidManifest.xml as:
<service android:name=".SimpleIntentService" />