Activity is never called - android

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);

Related

Service not working properly

I'm supposed to add a timer to my service class that prints a message to LogCat every 10 seconds. Nothing in the service class is printing once I call the startService method and I have no idea why.. Any ideas?
package com.murach.reminder;
import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class ReminderActivity extends Activity implements OnClickListener {
private Button startServiceButton;
private Button stopServiceButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminder);
startServiceButton = (Button) findViewById(R.id.startServiceButton);
stopServiceButton = (Button) findViewById(R.id.stopServiceButton);
startServiceButton.setOnClickListener(this);
stopServiceButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent serviceIntent = new Intent(this, ReminderService.class);
switch (v.getId()) {
case R.id.startServiceButton:
// put code to start service and display toast here
startService(serviceIntent);
Toast.makeText(this, "Service started", Toast.LENGTH_SHORT).show();
break;
case R.id.stopServiceButton:
// put code to stop service and display toast here
stopService(serviceIntent);
Toast.makeText(this, "Service stopped", Toast.LENGTH_SHORT).show();
break;
}
}
}
package com.murach.reminder;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import java.util.Timer;
import java.util.TimerTask;
public class ReminderService extends Service
{
private Timer timer;
public void onCreate()
{
Log.d("Reminder", "Service created");
startTimer();
}
#Override
public IBinder onBind(Intent intent)
{
Log.d("Reminder", "No binding for this activity");
return null;
}
public void onDestroy()
{
Log.d("Reminder", "Service destroyed");
stopTimer();
}
private void startTimer() {
TimerTask task = new TimerTask() {
public void run() {
Log.d("Reminder", "Timer task executed");
}
};
timer = new Timer(true);
int delay = 1000 * 10;
int interval = 1000 * 10;
timer.schedule(task, delay, interval);
}
private void stopTimer()
{
if (timer != null)
{
timer.cancel();
}
}
}
And here is how I register the service in the Manifest (in a service element, it wouldn't let me type it out completely)
android:name="com.murach.reminder.ReminderService"
The package names do not match. There is a spelling mistake in the word murach in your Manifest declaration.

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);
}
});
}
}
}

Creating an android service

I'm trying to create a service which will start by the user request in the application.
After the user will choose an update interval, the service will run in the operation system background, and will send a non-relevant message.
I've tried to write the service according to the example for Service class API.
For some reason, I figured in debug (when running doBindService() method) that mUpdateBoundService is getting null.
My second question is whether I can use "Toast" inform message outside an application ? (As kind of a desktop notification).
Can anyone help ? Here is my short code:
UpdateService.java
package android.update;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;
public class UpdateService extends Service {
private NotificationManager mNM;
private final IBinder mBinder = new UpdateBinder();
private int updateInterval;
public class UpdateBinder extends Binder {
UpdateService getService() {
return UpdateService.this;
}
}
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Timer timer = new Timer();
timer.schedule(new UpdateTimeTask(), 100, updateInterval);
}
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
class UpdateTimeTask extends TimerTask {
public void run() {
showNotification();
}
}
public void showNotification() {
Toast.makeText(this, "Hi", 10);
}
#Override
public IBinder onBind(Intent intent) {
updateInterval = intent.getExtras().getInt(getString(R.string.keyUpdateInterval));
return mBinder;
}
}
UpdateActivity.java
package android.update;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class UpdateActivity extends Activity {
private UpdateService mUpdateBoundService;
private boolean mIsBound = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClickStartUpdateService(View view) {
switch (view.getId()) {
case R.id.btnStartUpdateService:
doBindService();
//Toast.makeText(this,"Service Started",Toast.LENGTH_LONG).show();
mUpdateBoundService.showNotification();
break;
}
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mUpdateBoundService = ((UpdateService.UpdateBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
mUpdateBoundService = null;
}
};
private void doBindService() {
Intent updateActivityIntent = new Intent(UpdateActivity.this,
UpdateService.class);
EditText txtUpdateInterval = (EditText) findViewById(R.id.txtUpdateInterval);
int interval = Integer.parseInt(txtUpdateInterval.getText().toString());
updateActivityIntent.putExtra(getString(R.string.keyUpdateInterval), interval);
bindService(updateActivityIntent, mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
void doUnbindService() {
if (mIsBound) {
unbindService(mConnection);
mIsBound = false;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
doUnbindService();
}
}
Your toast is not showing because you are not telling it to. Try:
public void showNotification() {
Toast.makeText(this, "Hi", 10).show();
}
For your service issue, I think that you do not properly understand how services & activities work together. A service can run independently of a service, or you can have a service whose lifecycle matches that of a given activity. From your code, it is not clear which of these models you are following. Your implementation will cause the service to wake periodically, but only while your activity is running. If the user switches to another activity, your service will no longer be woken.
If you want a service to wake periodically independently of the activity, then you need to run your timer event in the service itself. Better still use an Alarm to wake your service: Register an Alarm with AlarmManager which will fire an Intent at a future point (or regular intervals, if you prefer), and extend your service from IntentService, override onHandleIntent() and add the necessary Intent Filter to your Service entry in the manifest.

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

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);

starting/stopping service multiple times not working

I am writing a simple service application, below is the code of Activity and Service..,when I am calling startService(), and stopService() its working fine for the one time,in my case it has to give notification..from next time onwards if call again startService(), and stopService() its not giving desired results...
---------- this is my activity class -------------
package com.mypack.serviceex;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class serviceex extends Activity implements Button.OnClickListener{
/** Called when the activity is first created. */
Button bt1,bt2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt1 = (Button) findViewById(R.id.Button01);
bt2 = (Button) findViewById(R.id.Button02);
bt1.setOnClickListener(this);
bt2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if( v == bt1)
{
Intent i = new Intent(serviceex.this,myservice.class);
Log.i("err","onClick(View v....");
startService(i);
}
else if(v == bt2)
{
Intent i = new Intent(serviceex.this,myservice.class);
Log.i("err","else if(v == bt2)........");
stopService(i);
}
}
}
--------- this is my service -------------
package com.mypack.serviceex;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class myservice extends Service
{
private NotificationManager nmgr;
public void onCreate()
{
super.onCreate();
nmgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Log.i("err","onCreate..........");
Thread th = new Thread(null,new incls(),"service...");
}
public void onStart(Intent intent,int sid)
{
super.onStart(intent, sid);
Log.i("err","onStart........");
}
public void onDestroy()
{
super.onDestroy();
Log.i("err","onDestroy..........");
displayMessage("Stopping Service");
}
public void displayMessage(String str)
{
Log.i("err.","displayMessage.....");
Notification nf = new Notification(R.drawable.icon,str,System.currentTimeMillis());
PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this,myservice.class), 0);
nf.setLatestEventInfo(this, "Service...", str, pi);
nmgr.notify(R.string.uid, nf);
}
private class incls implements Runnable
{
public void run()
{
Log.i("err","public void run()..........");
System.out.println("In Runnn");
}
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
None of your methods are #Overrideing the class methods. You have to annote them with #Override. Also, on 2.1 you should use onStartCommand() instead of onStart(). And also note that calling startService() multiple times will only call onCreate() once

Categories

Resources