It has been asked a few times before but the solution provided couldn't solve my problem. I am working on the app which has several classes: mainactivity, SMS, and MService. service has a timer. I am trying to call SMS to send a text message every time timer is over. Can please someone help me .... Thanks for consideration...
public class MService extends Service {
private Handler HandleIt = new Handler();
private final int INTERVAL = 60 * 1000;
private Timer timer = new Timer();
boolean timeout = false;
public interface SmsService
{
void SmsServiceSenter();
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
class TimeDisplayTimerTask extends TimerTask {
@Override
public void run() {
HandleIt.post(new Runnable(){
public void run(){
Toast.makeText(getApplicationContext(), TextonScreen(), Toast.LENGTH_SHORT).show();
// Intent smsintent = new Intent(getBaseContext(), SMS.class);
// startService(smsintent);
}
});
}
}
private String TextonScreen()
{
timeout = true;
return "it is running";
}
boolean isTimeout()
{
return timeout;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Toast.makeText(this, "Service is created", Toast.LENGTH_SHORT).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
// Display the Toast Message
Toast.makeText(this, "Start it", Toast.LENGTH_SHORT).show();
// Execute an action after period time
//comes from the TimeDisplayTimerTask class
timer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, INTERVAL);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
// Display the Toast Message
Toast.makeText(this, "Stop it", Toast.LENGTH_SHORT).show();
super.onDestroy();
}
}
public class SMS extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
message();;
}
boolean issent = false;
String text = "I am here";
String num = "2085578209";
SmsManager smsManager = SmsManager.getDefault();
public void message()
{
// if(Timeout.isTimeout()) {
smsManager.sendTextMessage(num, null, text, null, null);
issent = true;
// }
}
boolean isSent()
{
return issent;
}
}
It is really simple. After you create your Intent variable, before starting activity add a flag to it like below
Intent launch = new Intent(this, MyActivity.class);
launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(launch);
With this above code you can call activity from service
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.