How can we call an activity through service in android? - android

I want to know if it is possible to call an activity through background service in android like :
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
public class background extends Service{
private int timer1;
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
SharedPreferences preferences = getSharedPreferences("SaveTime", MODE_PRIVATE);
timer1 = preferences.getInt("time", 0);
startservice();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
private void startservice() {
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
public void run() {
mediaPlayerPlay.sendEmptyMessage(0);
}
}, timer1*60*1000);
}
private Handler mediaPlayerPlay = new Handler(){
#Override
public void handleMessage(Message msg) {
try
{
getApplication();
MediaPlayer mp = new MediaPlayer();
mp = MediaPlayer.create(background.this, R.raw.alarm);
mp.start();
}
catch(Exception e)
{
e.printStackTrace();
}
super.handleMessage(msg);
}
};
/*
* (non-Javadoc)
*
* #see android.app.Service#onDestroy()
*/
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
i want to call my activity......

You can call an Activity while onStart() of your service.....
Snippet might be as follows:
#Override
public void onStart(Intent intent, int startId) {
...
Log.i("Service", "onStart() is called");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
callIntent.setClass(<Set your package name and class name here>);
startActivity(callIntent);
...
}

I believe launching user-interactive Activity from a non-interactive Service goes against the design of Android, in that it would pull out control from under the user.
Notifications are the mechanism intended to get user's attention from a background app, and give them an opportunity to launch the interactive Activity.

Related

IntentService Thread.sleep() limit?

i was wondering if the IntentService has thread blocking limit like calling Thread.sleep(); and if so what's the maximum time limit for it?
so i wrote the following code snippet:
package net.yassin.aaaservice;
import android.app.IntentService;
import android.content.Intent;
import android.os.Handler;
import android.os.SystemClock;
import android.widget.Toast;
public class MyService extends IntentService {
private Thread t;
private static int i = 0;
private static final int SLEEP_DURATION = 2000;
private Handler handler;
public MyService() {
super("MyService");
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
this.handler = new Handler();
}
#Override
protected void onHandleIntent(Intent arg0) {
this.t = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
MyService.this.handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(MyService.this,
"This is toast #" + (++i),
Toast.LENGTH_SHORT).show();
}
});
try {
Thread.sleep(SLEEP_DURATION);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
this.t.start();
}
}
and i found that whenever i change the time SLEEP_DURATION constant to over than 2000 Milis the service will stop showing Toasts if i removed the app form the recent menu?
am i right or there is another time limit or behavior ?
thnx :)

how can show toast from service every 10 seconds

I have an android application and I want to show a notification or toast every 10 seconds for example from Service when application is closed or finished
I have provided below a sample activity, a service class and a Timer class. use similar implementation in your application.
Activity Class
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
public class Sample extends Activity {
Button button1,button2;
private Handler mHandler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Call the start and stop method when needed.
}
public void Start(View v)
{
startService(new Intent(MainActivity.this , Sample_service.class));
}
public void Stop(View v)
{
stopService(new Intent(MainActivity.this , Sample_service.class));
}
}
Service Class
package com.example.connect;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class Sample_service extends Service{
Timer timer = new Timer();
TimerTask updateProfile = new CustomTimerTask(Sample_service.this);
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
timer.scheduleAtFixedRate(updateProfile, 0, 10000);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();
timer.cancel();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Timer class
package com.example.connect;
import java.util.TimerTask;
import android.content.Context;
import android.os.Handler;
import android.widget.Toast;
public class CustomTimerTask extends TimerTask {
private Context context;
private Handler mHandler = new Handler();
public CustomTimerTask(Context con) {
this.context = con;
}
#Override
public void run() {
new Thread(new Runnable() {
public void run() {
mHandler.post(new Runnable() {
public void run() {
Toast.makeText(context, "DISPLAY YOUR MESSAGE", Toast.LENGTH_SHORT).show();
}
});
}
}).start();
}
}
I have given here three files,MainActivity,Manifest and MyService file implement it in your application and it will display toast service at every 10 seconds.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);//load the layout file
startService(new Intent(this,MyService.class));//use to start the services
}
}
MyService.java
public class MyService extends Service {
public static final long INTERVAL=10000;//variable to execute services every 10 second
private Handler mHandler=new Handler(); // run on another Thread to avoid crash
private Timer mTimer=null; // timer handling
#Nullable
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("unsupported Operation");
}
#Override
public void onCreate() {
// cancel if service is already existed
if(mTimer!=null)
mTimer.cancel();
else
mTimer=new Timer(); // recreate new timer
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(),0,INTERVAL);// schedule task
}
#Override
public void onDestroy() {
Toast.makeText(this, "In Destroy", Toast.LENGTH_SHORT).show();//display toast when method called
mTimer.cancel();//cancel the timer
}
//inner class of TimeDisplayTimerTask
private class TimeDisplayTimerTask extends TimerTask {
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
// display toast at every 10 second
Toast.makeText(getApplicationContext(), "Notify", Toast.LENGTH_SHORT).show();
}
});
}
}
}
AndroidManifest.xml
<service android:name=".MyService"
android:enabled="true"/>
Technically, When task is executed which you wrote in onCreate() method, It automatically close. For this you can use timer/scheduler.
Example :
Timer timer;
TimerTask timerTask;
timer.schedule(timerTask, 5000, 10000);
timerTask = new TimerTask() {
public void run() {
//use a handler to run a toast that shows the current timestamp
handler.post(new Runnable() {
public void run() {
Toast toast = Toast.makeText(getApplicationContext(), strDate, duration);
toast.show();
}
});
}
};
Don't forget to add your service in the manifest file inside the application Tag :
<service android:name=".ServiceGPS"
android:permission="[Add permission here if exists]"
android:label="[service name]" android:exported="true"
android:enabled="true">
</service>

Android Messenger Application using services

I want to implement a simple messenger application for Android devices,I'm working with a web service which contains all the required methods for sending and receiving(by pressing the send button a record will be inserted in the DB and by calling the receive method all the rows related to this receiver(user) are retrieved).
I've written a service in a separate class and in onStart() I check the receive method of my .Net web service,I start the service in onCreate() of my activity ,so the service is in the background and receives the incoming messages perfectly,I can show the new message by using a toast directly in my service code,but I know that for accessing the views which are in my activity I should use pendingintent and maybe a BroadcastReceiver,so I can add the new messages to the main screen of my activity(for example a textview).
Now I want to find a way to access the textview of my activity and set the text of it through my service or anything else...
please help me on this issue,
Here is my activity:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MyOwnActivity extends Activity
{
Button btnSend;
Button btnExtra;
EditText txtMessageBody;
TextView lblMessages;
BerryService BS = new BerryService();
public void SetMessageHistory(String value)
{
txtMessageBody.setText(value);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnSend = (Button) findViewById(R.id.btnSend);
btnExtra = (Button) findViewById(R.id.btnExtraIntent);
txtMessageBody = (EditText) findViewById(R.id.txtMessageBody);
lblMessages = (TextView) findViewById(R.id.lblMessages);
/////////
//////////
startService(new Intent(this, IncomingMessageService.class));
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// call webservice method to send
BS.SetSoapAction("http://tempuri.org/Send");
BS.SetMethodName("Send");
String a = BS.SendMessage(txtMessageBody.getText().toString());
lblMessages.setText(lblMessages.getText().toString() + "\n"
+ txtMessageBody.getText().toString());
txtMessageBody.setText("");
}
});
}
}
Here is my service:
import java.util.Timer;
import java.util.TimerTask;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.widget.Toast;
public class IncomingMessageService extends Service
{
private static final int NOTIFY_ME_ID = 12;
BerryService BS = new BerryService();
String text = "";
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Bind Failed");
}
#Override
public void onCreate() {
Toast.makeText(this, "onCreate", 5000).show();
}
#Override
public void onStart(Intent intent, int startId) {
// ////////////////////////
Toast.makeText(this, "onStart ", 1000).show();
// Timer Tick
final Handler handler = new Handler();
Timer _t = new Timer();
TimerTask tt = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "tick ", 1000)
.show();
// here the receive method should be called
BS.SetSoapAction("http://tempuri.org/RecieveMessage");
BS.SetMethodName("RecieveMessage");
String receivedMsg = BS.ReceiveMessage("sh");
//Instead of toast I want to access the textview in my activity!!!!!
Toast.makeText(getApplicationContext(), receivedMsg, 5000).show();
}
});
}
};
_t.scheduleAtFixedRate(tt, 0, 1000);
}
// /
#Override
public void onDestroy() {
Toast.makeText(this, "onDestroy", 5000).show();
}
}
You need to understand the concept of Broadcast, in your case it is the correct solution.
Start Broadcast in its activity
public static final String ACTION = "com.yourapp.ACTION.TEXT_RECEIVED";
private BroadcastReceiver mReceiver;
#Override
public void onCreate(Bundle savedInstanceState) {
////////
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String msg = intent.getStringExtra("msg");
yourTextView.setText(msg);
}
};
IntentFilter filter = new IntentFilter(ACTION);
filter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(mReceiver, filter);
////////
}
protected void onDestroy() {
// remember to unregister the receiver
super.onDestroy();
if (mReceiver != null) {
unregisterReceiver(mReceiver);
}
}
When you need to send the message of service you should use:
Intent i = new Intent();
i.setAction(MyOwnActivity.ACTION);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.putExtra("msg", "the message received by webservice");
i.putExtras(b);
sendBroadcast(i);
Have a look here: http://developer.android.com/reference/android/content/BroadcastReceiver.html
Using a broadcast manager is great but I personally prefer to use square's Otto because it is just so easy to perform communication between components in an android application.
http://square.github.io/otto/
If you do choose to use otto, you are going to have to override the Bus's post method to be able to talk post messages to a bus on the foreground. Here is the code for that:
public class MainThreadBus extends Bus {
private final Handler handler = new Handler(Looper.getMainLooper());
#Override public void post(final Object event) {
if (Looper.myLooper() == Looper.getMainLooper()) {
super.post(event);
} else {
handler.post(new Runnable() {
#Override
public void run() {
post(event);
}
});
}
}
}

In Android, How can I avoid the onStart method from being deprecated?

I am having a problem with setting the onStart method in my app. It always has a strikethrough, saying "This method was deprecated in API level 5. I need onStart, not onStartCommand.
How can I resolve this?
MyNotificationService.java
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyNotificationService extends Service {
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Toast.makeText(this, "OnCreate()", Toast.LENGTH_SHORT).show();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "OnDestroy()", Toast.LENGTH_SHORT).show();
}
#Override
#Deprecated
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
}
Reminder_2.java
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.DatePicker;
import android.widget.ImageButton;
public class Reminder_2 extends Activity {
String message;
DatePicker datepicker;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminder_2);
datepicker=(DatePicker)findViewById(R.id.datePicker1);
Home();
Next();
Save();
}
private void Next() {
final MediaPlayer button_tone = MediaPlayer.create(this, R.raw.button_sound);
ImageButton Button = (ImageButton) findViewById(R.id.imageButton1);
View.OnClickListener myListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
button_tone.start();
finish();
}
};
Button.setOnClickListener(myListener);
}
private void Save() {
final MediaPlayer button_tone = MediaPlayer.create(this, R.raw.button_sound);
ImageButton Button = (ImageButton) findViewById(R.id.imageButton3);
View.OnClickListener myListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
button_tone.start();
Intent intent = new Intent();
intent.setClass(getApplicationContext(), MyNotificationService.class);
startService(intent);
}
};
Button.setOnClickListener(myListener);
}
private void Home() {
final MediaPlayer button_tone = MediaPlayer.create(this, R.raw.button_sound);
ImageButton Button = (ImageButton) findViewById(R.id.imageButton2);
View.OnClickListener myListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
button_tone.start();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
};
Button.setOnClickListener(myListener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.reminder, menu);
return true;
}
}
Use onStartCommand().
It you want to know more about how they change it, refer to google documentation like below.
// This is the old onStart method that will be called on the pre-2.0
// platform. On 2.0 or later we override onStartCommand() so this
// method will not be called.
#Override
public void onStart(Intent intent, int startId) {
handleStart(intent, startId);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleStart(intent, startId);
return START_NOT_STICKY;
}
You can use like this with onStartCommand().
package htin.linnzaw.service;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service
{
private MediaPlayer mediaplayer;
public MyService()
{
}
#Override
public IBinder onBind(Intent intent)
{
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate()
{
Toast.makeText(this, "Service created", Toast.LENGTH_SHORT).show();
mediaplayer = MediaPlayer.create(this, R.raw.eventually);
mediaplayer.setLooping(false);
}
#Override
public int onStartCommand(Intent intent, int flags, int startid)
{
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
mediaplayer.start();
return startid;
}
#Override
public void onDestroy()
{
Toast.makeText(this, "Service stopped", Toast.LENGTH_SHORT).show();
mediaplayer.stop();
}
}

How to display toast inside timer?

I want to display toast message inside timer and I used the following code :
timer.scheduleAtFixedRate( new TimerTask()
{
public void run()
{
try {
fun1();
} catch (Exception e) {e.printStackTrace(); }
}
}, 0,60000);
public void fun1()
{
//want to display toast
}
And I am getting following error:
WARN/System.err(593): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
WARN/System.err(593): at android.os.Handler.(Handler.java:121)
WARN/System.err(593): at android.widget.Toast.(Toast.java:68)
WARN/System.err(593): at android.widget.Toast.makeText(Toast.java:231)
Thanks.
You can't make UI updates inside separate Thread, like Timer. You should use Handler object for UI update:
timer.scheduleAtFixedRate( new TimerTask() {
private Handler updateUI = new Handler(){
#Override
public void dispatchMessage(Message msg) {
super.dispatchMessage(msg);
fun1();
}
};
public void run() {
try {
updateUI.sendEmptyMessage(0);
} catch (Exception e) {e.printStackTrace(); }
}
}, 0,60000);
The easiest way (IMO) is:
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
final String message = "Hi";
MyActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MyActivity.this, message, Toast.LENGTH_SHORT).show();
}
});
}
});
The key being MyActivity.this.runOnUiThread(Runnable).
create a Handler and display toast in this
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
// Toast here
}
};
You need access to the Context of the application to be able to do this. Try creating your own class which takes the context as input parameter:
private class MyTimerTask extends TimerTask {
private Context context;
public MyTimerTask(Context context) {
this.context = context;
}
#Override
public void run() {
Toast.makeText(context, "Toast text", Toast.LENGTH_SHORT).show();
}
}
Then in your timer:
timer.scheduleAtFixedRate( new MyTimerTask(this), 0,60000);
I wanted to make a simple project that could display a Toast in a Timer.
The Timer would be started using a service. Then, the Timer starts when the service is started and stops when service is stopped.
Class 1
package com.example.connect;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button button1,button2;
private Handler mHandler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1=(Button)findViewById(R.id.button1);
button2=(Button)findViewById(R.id.button2);
}
public void Start(View v)
{
startService(new Intent(MainActivity.this , Connect_service.class));
}
public void Stop(View v)
{
stopService(new Intent(MainActivity.this , Connect_service.class));
}
}
Class 2
package com.example.connect;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class Connect_service extends Service{
Timer timer = new Timer();
TimerTask updateProfile = new CustomTimerTask(Connect_service.this);
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
timer.scheduleAtFixedRate(updateProfile, 0, 5000);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();
timer.cancel();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Class 3
package com.example.connect;
import java.util.TimerTask;
import android.content.Context;
import android.os.Handler;
import android.widget.Toast;
public class CustomTimerTask extends TimerTask {
private Context context;
private Handler mHandler = new Handler();
public CustomTimerTask(Context con) {
this.context = con;
}
#Override
public void run() {
new Thread(new Runnable() {
public void run() {
mHandler.post(new Runnable() {
public void run() {
Toast.makeText(context, "In Timer", Toast.LENGTH_SHORT).show();
}
});
}
}).start();
}
}
I'm trying to make my own toast with my own views.
I've successfully combined your approaches. The following code allows me to show toasts and change/remove views without crashing, just change the parameters of the MyTimerTask constructor to whatever you need to work on.
public void yourFunction(){
Timer timer = new Timer();
MyTimerTask mtc = new MyTimerTask(this.getContext(), tvNotice);
timer.schedule(mtc, 1000);
}
private class MyTimerTask extends TimerTask {
private TextView tv;
private Context context;
public MyTimerTask(Context pContext, TextView pTv) {
this.tv = pTv;
this.context = pContext;
}
#Override
public void run() {
updateUI.sendEmptyMessage(0);
}
private Handler updateUI = new Handler(){
#Override
public void dispatchMessage(Message msg) {
super.dispatchMessage(msg);
tv.setText("TextView Message");
Toast.makeText(context, "Toast Message", 0).show();
}
};
}
You have to call UIThread for showing Toast, not from timer thread.
Else call UI thread from that timer thread.
This link will help you,
http://developer.android.com/resources/articles/timed-ui-updates.html
and this
http://developer.android.com/guide/appendix/faq/commontasks.html#threading

Categories

Resources