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" />
Related
On button click I am opening activity(ActionListActivity) and sending intent to IntentService (later this service sends broadCast intent to ActionListActivity). But I am usually receiving only the first intent after launch. Is it real that intent is sent before the receiver is registred?
I want to get data providet by the intentService, and update my UI using it.
Scheme Activity->IntentService->BroadCastReceiver inside ActionListActivity
Activity:
private void selectDrawerItem(MenuItem menuItem)
{
switch (menuItem.getItemId()) {
case R.id.actions:{
Intent myIntent = new Intent(this, ActionListActivity.class);
this.startActivity(myIntent);
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.show();
Intent dataIntent = new Intent(this, DatabaseWorkIntentService.class);
dataIntent.putExtra(Utils.INTENT_SERVICE_INVOKE, Utils.READ_ACTIONS_DATA);
startService(dataIntent);
progressDialog.dismiss();
}
}
}
IntentService:
private void readActionData(){
Log.e("read actions data","data");
List<Action> actionList;
actionList = Action.listAll(Action.class);
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(Utils.READ_ACTIONS_DATA);
broadcastIntent.putParcelableArrayListExtra(Utils.READ_ACTIONS_DATA, (ArrayList<? extends Parcelable>) actionList);
sendBroadcast(broadcastIntent);
}
ActionListActivity:
public class ActionListActivity extends BaseActivity {
boolean mIsReceiverRegistered = false;
DataBroadcastReceiver receiver;
TextView someTv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.action_list_activity);
this.initToolbarAndDrawerWithReadableName(getString(R.string.our_actions));
someTv = (TextView)findViewById(R.id.someTv);
}
public void someTvTest(Action action){
someTv.append(action.getName());
Log.e("data",action.getName());
}
#Override
protected void onPause() {
super.onPause();
if (mIsReceiverRegistered) {
unregisterReceiver(receiver);
receiver = null;
mIsReceiverRegistered = false;
}
}
#Override
protected void onResume() {
super.onResume();
if (!mIsReceiverRegistered) {
if (receiver == null)
receiver = new DataBroadcastReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Utils.READ_ACTIONS_DATA);
receiver.setMainActivityHandler(this);
registerReceiver(receiver, filter);
mIsReceiverRegistered = true;
}
}
}
class DataBroadcastReceiver extends BroadcastReceiver{
ActionListActivity activity = null;
ArrayList<Action> list;
public void setMainActivityHandler(ActionListActivity main){
activity = main;
}
#Override
public void onReceive(Context context, Intent intent) {
Log.e("reciever","reciev");
list = intent.getParcelableArrayListExtra(Utils.READ_ACTIONS_DATA);
for (Action action:list){
if(activity!=null) {
activity.someTvTest(action);
}
}
}
}
You start activity and service async.
You need to start service inside ActionListActivity and wait for response.
I have a class which extends BroadcastReceiver. On receiving a SMS, I would like to pass information to my main activity class to display the text in a box (Append, if already text is present).
public class SmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
Intent i = new Intent(context, MainActivity.class);
i.putExtra("updatedString","Hello");
context.startActivity(i);
}
}
MainActivity.java
public class MainActivity extends Activity{
private TextView results;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle extras = getIntent().getExtras();
if(extras!=null){
results = (TextView) findViewById(R.id.results);
results.setVisibility(View.VISIBLE);
results.append(extras.getString("updatedString"));
}
}
I have only one activity class (MainActivity.java). However When i do this I get an exception Unable to pause Activity.
You have three ways:
1) You can define your broadcast inside your MainActivity like this:
in onCreate()
registerReceiver(smsReceiver, new IntentFilter(SMS_RECIEVED));
and define smsReciver in MainActivity
private BroadcastReceiver smsReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//you can update textBox here
handler.postDelayed(sendUpdatesToUI, 10);
}
};
define a runnable to update UI
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
update();
}
};
and update method
private void update(String text) {
textView.setText(textView.getText().toString() + text);
}
2) Register a receiver between your Activity and BroadCastReceiver
3) Start your Activity with new Intent to update current open Activity
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("Key", "text");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
UPDATE :
explain method 2
MainActivity.class
in onResume()
registerReceiver(broadcastReceiver, new IntentFilter(SmsReceiver.BROADCAST_ACTION));
in onDestroy()
unregisterReceiver(broadcastReceiver);
local broadCast (broadcastReceiver, in MainActivity.class)
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateUI(intent);
}
};
private void updateUI(Intent intent) {
String text = intent.getStringExtra("key");
textView.setText(textView.getText().toString() + text);
}
SmsReceiver.class
global attribute
public static final String BROADCAST_ACTION = "your.package.name.displayevent";
private final Handler handler = new Handler();
Intent intent;
Context context;
in onReceive()
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 10);
this.context = context;//you can retrieve context from onReceive argument
this.intent = new Intent(BROADCAST_ACTION);
define two method
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
display();
}
};
private void display() {
intent.putExtra("key", text);
context.sendBroadcast(intent);
}
Modify your code as below.
public class SmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
Intent i = new Intent(context, MainActivity.class);
i.putExtra("updatedString","Hello"); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP);
context.startActivity(i);
}
}
public class MainActivity extends Activity{
private TextView results;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle extras = getIntent().getExtras();
if(extras!=null){
results = (TextView) findViewById(R.id.results);
results.setVisibility(View.VISIBLE);
results.append(extras.getString("updatedString"));
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
//handle your intent here.Note this will be called even when activity first created.so becareful to handle intents correctly.
}
}
I want my activity class to receive an intent from broascast Receiver (example START_TALKING, STOP_TALKING). And when I receive that intent, I want to check what action was being passed. How can I do this. My receiver is in separate class, it's public.
Here's my code
public void onReceive(Context context, Intent intent)
{
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
KeyEvent event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_HEADSETHOOK:
if (action == KeyEvent.ACTION_DOWN)
// here I want to notify my activity class (e.g. startActivity? I don't know)
break;
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
// here I want to notify my activity class (e.g. startActivity? I don't know)
}
}
}
I really need your help guys tnx.
Here is my solution, in my project, hope it'll help you:
you should type this:
// put your action string in intent
Intent intent = new Intent("com.example.myproject.ADD_ITEM_BASKET");
// start broadcast
activity.sendBroadcast(intent);
public class Myclass extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// creating and register receiver
Receiver receiver = new Receiver();
IntentFilter intentFilterAdd = new IntentFilter("com.example.myproject.ADD_ITEM_BASKET");
IntentFilter intentFilterEdit = new IntentFilter("com.example.myproject.DELETE_ITEM_BASKET");
getActivity().registerReceiver(receiver, intentFilterAdd);
getActivity().registerReceiver(receiver, intentFilterDelete);
}
// your receiver class
class Receiver extends BroadcastReceiver
{
// catch messages from intent
#Override
public void onReceive(Context context, Intent intent) {
if("com.example.myproject.ADD_ITEM_BASKET".equals(intent.getAction().toString()))
{
// do something
}
else if("com.example.myproject.DELETE_ITEM_BASKET".equals(intent.getAction().toString()))
{
// do something
}
}
}
}
You can use putExtra() in your BroadcastReceiver's onReceive().
/**
* #author Skylifee7 on 23/06/2017.
* TemplateResultReceiver.java
*/
public class TemplateResultReceiver extends BroadcastReceiver {
private static final String TAG = "BleshTemplate";
public static final String EXTRA_MESSAGE = "TRANSACTION_MESSAGE";
Context mContext;
#Override
public void onReceive(Context context, Intent intent) {
mContext = context;
if (intent.getAction().equals(BleshConstant.BLESH_TEMPLATE_RESULT_ACTION)) {
String actionType = intent.getStringExtra(BleshConstant.BLESH_ACTION_TYPE);
String actionValue = intent.getStringExtra(BleshConstant.BLESH_ACTION_VALUE);
if (actionType != null && actionValue != null) {
switch (actionType) {
case "MENU": sendMessage(actionValue);
/*
You may want to increase the case possibilities here, like below:
case: "ADMOB"
case: "VIRTUAL_AVM"
case: "SMART_CAR_KEY"
*/
default: sendMessage(actionValue);
}
}
}
}
private void sendMessage(String actionValue) {
Intent intent = new Intent(mContext.getApplicationContext(),TransactionActivity.class);
intent.putExtra(EXTRA_MESSAGE, actionValue);
mContext.getApplicationContext().startActivity(intent);
}
}
And in your Activity class' onCreate() method:
/**
* #author Skylifee7 on 24/06/2017.
* TransactionActivity.java
*/
public class TransactionActivity extends AppCompatActivity {
private String bleshKey;
private String TAG = "Transaction_Activity";
private String amount;
private String isSuccessful; //may be cast to boolean type.
private double latitude, longitude;
private LocationRequest mLocationRequest;
protected GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
requestPermission();
initLocationService();
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
bleshKey = intent.getStringExtra(BleshTemplateResultReceiver.EXTRA_MESSAGE);
ImageButton paymentBtn = (ImageButton) findViewById(R.id.buttonPay);
final EditText editTextAmount = (EditText) findViewById(R.id.editTextAmount);
paymentBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
amount = editTextAmount.getText().toString();
callApiService();
}
});
}
}
You have to register the receiver... Follow this example..
public class MyActivity extends Activity {
private BroadcastReceiver myBroadcastReceiver =
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// your onreceive code here
}
});
...
public void onResume() {
super.onResume();
....
registerReceiver(myBroadcastReceiver, intentFilter);
}
public void onPause() {
super.onPause();
...
unregisterReceiver(myBroadcastReceiver);
}
...
}
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 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);
}