How to start new service in run() of Thread? - android

How To start new service in Thread...
Thread is running continuously but the startservice() method in run() is not gets started...
Please Help Me.
The code is as follows.....
package com.example.demo;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class Act extends Service {
/** Called when the activity is first created. */
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(Act.this,"In On Create",Toast.LENGTH_SHORT).show();
Intent i=new Intent(getApplicationContext(),HelloService.class);
startService(i);
Toast.makeText(Act.this,"In End Create",Toast.LENGTH_SHORT).show();
updateTimeTask.start();
}
private Thread updateTimeTask = new Thread() {
public void run() {
Intent i=new Intent(getApplicationContext(),HelloService.class);
startService(i); //This Service not gets started
}
};
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}

You must have a Pending Intent for this:
// start something with Intent
Intent widgetUpdate = new Intent(SomeClass.this,
SomeService.class);
widgetUpdate.putExtra("Something", something);
// make this pending intent unique
widgetUpdate.setData(Uri.withAppendedPath(
Uri.parse(mUriSchemaId + "://widget/id/"),
String.valueOf(appWidgetId)));
PendingIntent newPending = PendingIntent.getService(
getApplicationContext(), 0, widgetUpdate,
PendingIntent.FLAG_UPDATE_CURRENT);
remoteview.setOnClickPendingIntent(R.id.someview,
newPending);

Related

How to run a service periodically without opening the app

hi I am developing an application where I need to get the unread SMS from my phone. I need to check my inbox once a fixed amount of time. I have written the code to retrieve the unread SMS. I have included a timer which checks the unread SMS every 30 seconds. But the problem is it checks only when the app is open. I need to check even when the app is not open. Please provide any suggestions and modification I need to make. Below is my code.
MainActivity
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends ActionBarActivity {
MyReceiver myReceiver;
ListView lViewSMS;
ArrayList datapassed;
//private static final String TAG_SUCCESS = "success";
//String URL = "http://10.10.234.232/test_android/index2.php";
// JSONParser jsonParser = new JSONParser();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lViewSMS = (ListView) findViewById(R.id.listViewSMS);
//String []r;
// r=new String[2];
// if (r != null) {
//#SuppressWarnings("unchecked")
//ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, fetchInbox());
//lViewSMS.setAdapter(adapter);/
//AttemptLogin attemptLogin = new AttemptLogin();
//attemptLogin.execute(r[0],r[1]);
// #SuppressWarnings("unchecked")
// ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, datapassed);
//lViewSMS.setAdapter(adapter);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
//Register BroadcastReceiver
//to receive event from our service
myReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(MyService.MY_ACTION);
registerReceiver(myReceiver, intentFilter);
//Start our own service
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Intent intent = new Intent(MainActivity.this, MyService.class);
startService(intent);
}
},
0,
30000);
super.onStart();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
unregisterReceiver(myReceiver);
super.onStop();
}
private class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
datapassed = arg1.getStringArrayListExtra("DATAPASSED");
// #SuppressWarnings("unchecked")
// ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, datapassed);
// lViewSMS.setAdapter(adapter);
Toast.makeText(MainActivity.this,
"Triggered by Service!\n"
+ "Data passed: " + datapassed,
Toast.LENGTH_LONG).show();
}
}
}
MyService.java
import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.IBinder;
import java.util.ArrayList;
public class MyService extends Service {
final static String MY_ACTION = "MY_ACTION";
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
MyThread myThread = new MyThread();
myThread.start();
return super.onStartCommand(intent, flags, startId);
}
public class MyThread extends Thread{
#Override
public void run() {
// TODO Auto-generated method stub
try {
//Thread.sleep(5000);
Intent intent = new Intent();
intent.setAction(MY_ACTION);
if(fetchInbox()!=null) {
intent.putExtra("DATAPASSED", fetchInbox());
sendBroadcast(intent);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stopSelf();
}
}
ArrayList fetchInbox (){
final Uri SMS_INBOX = Uri.parse("content://sms/inbox");
//Retrieves all SMS (if you want only unread SMS, put "read = 0" for the 3rd parameter)
Cursor cursor = getContentResolver().query(SMS_INBOX, null,"read=0", null, null);
ArrayList sms = new ArrayList();
//Get all lines
String read=" ";
String body=" ";
String[] arr = new String[2];
while (cursor.moveToNext()) {
//Gets the SMS information
String address = cursor.getString(cursor.getColumnIndex("address"));
String person = cursor.getString(cursor.getColumnIndex("person"));
String date = cursor.getString(cursor.getColumnIndex("date"));
String protocol = cursor.getString(cursor.getColumnIndex("protocol"));
read = cursor.getString(cursor.getColumnIndex("read"));
String status = cursor.getString(cursor.getColumnIndex("status"));
String type = cursor.getString(cursor.getColumnIndex("type"));
String subject = cursor.getString(cursor.getColumnIndex("subject"));
body = cursor.getString(cursor.getColumnIndex("body"));
sms.add(address+"\n"+person+"\n"+body+"\n");
//Do what you want
// else
// {
// AttemptLogin attemptLogin = new AttemptLogin();
// attemptLogin.execute("", "");
//}
}
//return arr;
//return body;
return sms;
}
}
you can Use AlarmManager Class in Android to run the service periodically.
AlarmManager alarmMgr= (AlarmManager)
context.getSystemService(Context.ALARM_SERVICE);
int timeInterval=300*1000;//in milliseconds
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
Intent intent = new Intent(context, YourService.class);
alarmIntent = PendingIntent.getService(context, 0, intent, 0);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), timeInterval, alarmIntent);`
You may use AlarmManeger class https://developer.android.com/training/scheduling/alarms.html for Example
Calendar calendar = Calendar.getInstance();
long repeatInterval = 30000;
AlarmManager am = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(getActivity(), MyReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(getActivity(), 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), repeatInterval , pi);
Where repeatInterval time, in milliseconds.
onReceive() is called when the MyReceiver is receiving an Intent broadcast.
You need to do this repeat code inside your Service instead of your Activity
So you start your service once :
#Override
protected void onStart() {
// TODO Auto-generated method stub
//Register BroadcastReceiver
//to receive event from our service
myReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(MyService.MY_ACTION);
registerReceiver(myReceiver, intentFilter);
//Start our own service
Intent intent = new Intent(MainActivity.this, MyService.class);
startService(intent);
super.onStart();
}
And in your Service
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
MyThread myThread = new MyThread();
myThread.start();
}
}, 0, 30000);
return super.onStartCommand(intent, flags, startId);
}
Also remove stopSelf(); from your MyThread
And one try passing context received in Broadcast and not of your Activity
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends ActionBarActivity {
MyReceiver myReceiver;
ListView lViewSMS;
ArrayList datapassed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lViewSMS = (ListView) findViewById(R.id.listViewSMS);
Calendar calendar = Calendar.getInstance();
long repeatInterval = 30000;
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(this, MyServiceReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), repeatInterval, pi);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
//Register BroadcastReceiver
//to receive event from our service
myReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(MyService.MY_ACTION);
registerReceiver(myReceiver, intentFilter);
//Start our own service
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Intent intent = new Intent(MainActivity.this, MyService.class);
startService(intent);
}
},
0,
30000);
super.onStart();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
unregisterReceiver(myReceiver);
super.onStop();
}
private class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
datapassed = arg1.getStringArrayListExtra("DATAPASSED");
// #SuppressWarnings("unchecked")
// ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, datapassed);
// lViewSMS.setAdapter(adapter);
Toast.makeText(MainActivity.this,
"Triggered by Service!\n"
+ "Data passed: " + datapassed,
Toast.LENGTH_LONG).show();
}
}
}
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
public class MyServiceReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ComponentName comp = new ComponentName(context.getPackageName(), MyService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
}
}
Try above code

Is it possible to call a BroadcastReceiver from the same Activity where the receiver is written?

I have a BroadcastReceiver class in my Activity. I want to start a Fragment from the receiver class. Can i call that from the same Activity where the receiver is written?
Try something like this... And if your using your custom Broadcast Receiver then replace BroadcastReceiver this class with your receiver's class.
public class Demo extends AppCompatActivity {
private final IntentFilter filter = new IntentFilter();
private BroadcastReceiver networkStateReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onResume() {
super.onResume();
// Defining broadcast receiver in onResume()
networkStateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Do what you want
}
};
// Registering receiver with intent filter, here intent filter can be changed
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(networkStateReceiver, filter);
}
#Override
protected void onPause() {
super.onPause();
// Unregister receiver in onStop to avoid any runtime exception
unregisterReceiver(networkStateReceiver);
}
}
Yes you can do it using LocalBroadCastManger
import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class LocalBroadcastExampleActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.log_list);
Button buttonStartService = (Button)findViewById(R.id.button_ok);
buttonStartService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Register MessageService in Manifest to work
startService(new Intent(LocalBroadcastExampleActivity.this, MessageService.class));
}
});
}
#Override
protected void onPause() {
// Unregister since the activity is paused.
LocalBroadcastManager.getInstance(this).unregisterReceiver(
mMessageReceiver);
super.onPause();
}
#Override
protected void onResume() {
// Register to receive messages.
// We are registering an observer (mMessageReceiver) to receive Intents
// with actions named "custom-event-name".
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter("custom-event-name"));
super.onResume();
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
public class MessageService 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) {
// TODO Auto-generated method stub
sendMessage();
return super.onStartCommand(intent, flags, startId);
}
// Send an Intent with an action named "custom-event-name". The Intent
// sent should
// be received by the ReceiverActivity.
private void sendMessage() {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "This is my message!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
}

Activity is never called

I am working on an android application where an action is triggered after specific interval of time again and again when there is an Intent.FLAG_ACTIVITY_NEW_TASK Broadcast message received.
I have the following code in UpdateService.java:
package com.missnoob.screentimeout;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class UpdateService extends Service {
#Override
public void onCreate() {
super.onCreate();
// REGISTER RECEIVER THAT HANDLES SCREEN ON AND SCREEN OFF LOGIC
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onStart(Intent intent, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
Log.v("ScreenTimeOut","Broadcast Received");
Toast.makeText(getApplicationContext(), "Broadcast Received", Toast.LENGTH_LONG).show();
//This part is not working
Intent i = new Intent(this, Notification.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//This part is not working
}
else
{
// YOUR CODE
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
And the following code in Notification.java:
package com.missnoob.screentimeout;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.shadow.screentimeout.R;
public class Notification extends Activity {
/** Called when the activity is first created. */
Timer timer;
Toast toast;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer = new Timer();
toast = Toast.makeText(getApplicationContext(), "15 seconds after",Toast.LENGTH_SHORT);
timer.scheduleAtFixedRate(new TimerTask()
{
#Override
public void run() {
toast.show();
Log.v("ScreenTimeOut","Toast showed");
}
}, 0, 5000);
}
}
In UpdateService.java
Intent i = new Intent(this, Notification.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
never gets triggered.
You are missing startActivity(i)
Intent i = new Intent(this, Notification.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
Also you cannot have
toast.show();
in timer as it runs on a different thread and you can update ui only on the ui thread.
Instead use a Handler. You can find an example #
Android Thread for a timer
You have not called startActivity(i).
See Start Another Activity (android developer website).
You are didn't call startActivity(i), thats why your activity is never caled, all you have to do is like this :
Intent i = new Intent(this, Notification.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);

Trigger Multiple Services

I have two problems regarding Android Services.
First, I would like to know which is less computationally expensive? Threads or Services?
Secondly, In my main android application I have tried to trigger 2 services:
Intent intent = new Intent("android.intent.action.MAIN");
intent.setComponent(ComponentName
.unflattenFromString("com.mrlite.service1"));
intent.addCategory("android.intent.category.LAUNCHER");
startService(intent);
intent.setComponent(ComponentName
.unflattenFromString("com.mrlite.service2"));
intent.addCategory("android.intent.category.LAUNCHER");
startService(intent);
Service1:
package com.mrlite.service1;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class Service1Activity extends Service {
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
//Intent intent = new Intent("android.intent.action.MAIN");
//String value = getIntent().getExtras().getString("1")
Log.e(getClass().getSimpleName(), "Service 1 Started");
}
#Override
public void onDestroy()
{
super.onDestroy();
Log.e(getClass().getSimpleName(), "Service 1 Destroyed");
}
}
Service 2:
package com.mrlite.service2;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class Service2Activity extends Service {
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
// Intent intent = new Intent("android.intent.action.MAIN");
// String value = getIntent().getExtras().getString("1")
Log.e("Service 2", "Service 2 Started");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("Service 2", "Service 2 Destroyed");
}
}
Whenever I try to execute this code, only service 1 is called. Service 2 is never called.
How to trigger 2 services simultaneously?
Is there a reason why you are starting your services that way? Why not do it this way:
Intent intent = new Intent(this, Service1Activity.class);
startService(intent);
intent = new Intent(this, Service2Activity.class);
startService(intent);
The reason it probably doesn't work the way you're doing it is because android.intent.action.MAIN can only be assigned to one class.

How can we call an activity through service in 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.

Categories

Resources