I am trying to implement custom bradcastreciever. but my when i register it return null in my intent. I don't know what is going wrong here
?
My activity is here
private MyReciever mReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.mReceiver = new MyReciever();
Intent result=registerReceiver(this.mReceiver, new IntentFilter(
"com.example.Broadcast"));
int status = result.getIntExtra("HighScore",0);
System.out.println(status+" Yahoo");
setContentView(R.layout.activity_main);
for (int i = 0; i < 10; i++) {
try {
if (i == 7) {
// MyReciever mr=new MyReciever();
Intent intent = new intent();
intent.setAction("com.example.Broadcast");
intent.putExtra("HighScore", 1000);
sendStickyBroadcast(intent);
break;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
unregisterReceiver(mReceiver);
}
and Reciever is
public class MyReciever extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
//int data= intent.getIntExtra("HighScore",0);
Toast.makeText(context, "Highest Score", Toast.LENGTH_LONG).show();
}
}
I have given permission in android mainfest file
<uses-permission android:name="android.permission.BROADCAST_STICKY"/>
It will return null because nothing will have been broadcast for that action yet by the time you call registerReceiver().
Declare your receiver in the manifest file
<receiver
android:name=".MyReceiver"
</receiver>
Related
i am working with Recognizing the User's Current Activity from http://developer.android.com/training/location/activity-recognition.html
i used folow code to create new ActivityRecognitionClient:
public class GPSLocationService extends Service implements ConnectionCallbacks, OnConnectionFailedListener {
private String TAG = "[ServiceDetect]";
//
private ActivityRecognitionClient mActivityRecognitionClient ;
private PendingIntent mPendingIntent ;
#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
if (checkGooglePlayAvaible()) {
startTrack();
}
return START_STICKY;
}
#Override
public void onConnected(Bundle bundle) {
// TODO Auto-generated method stub
// code detetc user acitivity here
getActivityRecognitionClient().requestActivityUpdates((2 * 60 * 1000), createPendingRequest());
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
mActivityRecognitionClient = null;
mPendingIntent.cancel();
mPendingIntent = null;
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try{
connectionResult.startResolutionForResult((Activity) this.getApplicationContext(), 0);
} catch (IntentSender.SendIntentException e) {
// it happens if the resolution intent has been canceled,
// or is no longer able to execute the request.e
e.printStackTrace();
}
} else {
// Google Play services has no idea how to fix the issue
// it rarely happens for the location service
}
}
public void startTrack() {
try {
if (!getActivityRecognitionClient().isConnected() || !getActivityRecognitionClient().isConnecting() ) {
Log.v(TAG, "getActivityRecognitionClient is not connected");
getActivityRecognitionClient().connect();
}
}
public PendingIntent createPendingRequest() {
if (null != mPendingIntent) {
} else {
Intent intent = new Intent(getApplicationContext(), ServiceFour.class);
mPendingIntent = PendingIntent.getService(getApplicationContext(), 2, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
return mPendingIntent;
}
/**
* check googleplayservices is avaible or not
*
* #return true if is avaible flase if not
*/
public boolean checkGooglePlayAvaible() {
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
return true;
}
return false;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mIsRemove = false;
}
private ActivityRecognitionClient getActivityRecognitionClient() {
if (mActivityRecognitionClient == null) {
mActivityRecognitionClient = new ActivityRecognitionClient(getApplicationContext(), this, this);
}
return mActivityRecognitionClient;
}
So with it every 2 min User's Current Activity will be send to service four. in my service four(Intent service) :
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
if (ActivityRecognitionResult.hasResult(intent)) {
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
//
if (result != null) {
//
Log.d("Aha", "he he");
} else {
Log.d("Ohno", "T_T");
}
}
It work fine but when i uninstall app. and install again all ActivityRecognitionResult in servicefour is null it just can be work fine again if i restart device. I don't know how to fix this . Please help me and thanks for reading.
Here is your problem:
E/GooglePlayServicesUtil(18189): The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.
Your GooglePlayServices are not working.
Make sure you included them properly (post your Gradle files etc).
I will post my code for Recognizing the User's Current Activity but with newest api .
public class GPSLocationService extends Service implements ConnectionCallbacks, OnConnectionFailedListener {
private String TAG = "[ServiceDetect]";
//
private PendingIntent mActivityRecognitionPendingIntent;
// Stores the current instantiation of the activity recognition client
private GoogleApiClient mApiClient;
#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
if (checkGooglePlayAvaible()) {
startTrack();
}
return START_STICKY;
}
#Override
public void onConnected(Bundle bundle) {
// TODO Auto-generated method stub
// -------------------------------------
// to remove ActivityRecognition call
// ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates
//----------------------------
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mApiClient, 2 * 60 * 1000,
createPendingRequest());
//
mApiClient.disconnect();
stopSelf();
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
Log.d(TAG, "onConnectionFailed");
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
Log.d(TAG, "onConnectionSuspended");
mApiClient.connect();
}
public void startTrack() {
if (mApiClient == null) {
mApiClient = new GoogleApiClient.Builder(getApplicationContext()).addApi(ActivityRecognition.API)
.addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
}
if (!mApiClient.isConnected() || !mApiClient.isConnecting()) {
mApiClient.connect();
}
}
public PendingIntent createPendingRequest() {
if (null != mActivityRecognitionPendingIntent) {
} else {
Intent intent = new Intent(getApplicationContext(), ServiceFour.class);
mActivityRecognitionPendingIntent = PendingIntent.getService(getApplicationContext(), 2, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
return mActivityRecognitionPendingIntent;
}
public boolean checkGooglePlayAvaible() {
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
return true;
}
return false;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
And now in my servicefour . I receive ActivityRecognitionResult :
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
Bundle bundle = intent.getExtras();
if (ActivityRecognitionResult.hasResult(intent)) {
if (bundle.containsKey("com.google.android.location.internal.EXTRA_ACTIVITY_RESULT")) {
String activityRecognitionResult = bundle
.getParcelable("com.google.android.location.internal.EXTRA_ACTIVITY_RESULT") + "";
Log.d(TAG, "activityRecognitionResult " + activityRecognitionResult +" (^.,,.^)");
}
}
Can any one tell me how to stop the service when the app get closed.
In my project the service is still running in background even though the application got closed.Here i've given my sources for reference.
Suggestions please.
Thanks for your precious time!..
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(this, MyService.class));
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(this, MyService.class);
PendingIntent pintent = PendingIntent
.getService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// Start service every 20 seconds
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
10* 1000, pintent);
}
}
MyService.java
public class MyService extends Service {
String result_data = "";
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, "The new Service was Created", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
// For time consuming an long tasks you can launch a new thread here...
Toast.makeText(this, " Service Started", Toast.LENGTH_LONG).show();
Authentication_Class task = new Authentication_Class();
task.execute();
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
public class Authentication_Class extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... params)
{
// TODO Auto-generated method stub
try {
Call_service();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private void Call_service() throws Exception{
// TODO Auto-generated method stub
System.setProperty("http.keepAlive", "false");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
String URL = "";
String METHOD_NAME = "";
String NAMESPACE = "";
String SOAPACTION = "";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
// Add parameters if available
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransportSE = new HttpTransportSE(URL,15000);
try {
httpTransportSE.call(SOAPACTION, envelope);
SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
result_data = String.valueOf(result);
System.out.println(">>-- RESPONSE : " +result_data);
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
}
}
}
Use this in your onDestroy() method in the activity where you are finishing your last activity like this:
#Override
protected void onDestroy() {
super.onDestroy();
AppLog.Log(TAG, "On destroy");
stopService(new Intent(getApplicationContext(), MyService .class));
}
I am working on a app that runs in the background and listens to incoming calls.
For this I have created a service which calls TelephonyManager.listen in the onHandleIntent method.
Unfortunately although the constructor of the phonestatelistener is invoked, its onPhoneStateChanged method is not getting invoked.
Making the same call from a activity works fine. I am confused what the issue might be. I have searched many similar posts but none of them have answered my question satisfactorily. Hence I am posting this question.
Following is my service and phonelistener implementation:
public class PhoneListenersService extends IntentService{
TelephonyManager tm;
CallStateListener callstatelistener;
public PhoneListenersService() {
super("PhoneListenersService");
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
int count=0;
do
{
TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
TelephonyMgr.listen(new TeleListener(), PhoneStateListener.LISTEN_CALL_STATE);
Log.d("Count", ""+count++);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
while(count<100);
}
class TeleListener extends PhoneStateListener {
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
// CALL_STATE_IDLE;
Toast.makeText(getApplicationContext(), "CALL_STATE_IDLE",
Toast.LENGTH_LONG).show();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
// CALL_STATE_OFFHOOK;
Toast.makeText(getApplicationContext(), "CALL_STATE_OFFHOOK",
Toast.LENGTH_LONG).show();
break;
case TelephonyManager.CALL_STATE_RINGING:
// CALL_STATE_RINGING
Toast.makeText(getApplicationContext(), incomingNumber,
Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "CALL_STATE_RINGING",
Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
}
}
Please help me.
Thanks!
Left with no option, I have changed my approach. I use Broadcast Receiver with Intent Service to listen for incoming calls. Following is the code if it helps someone:-
public class PhoneListenersService extends IntentService{
TelephonyManager tm;
BroadcastReceiver receiver;
IntentFilter filter;
public PhoneListenersService() {
super("PhoneListenersService");
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
//Intent
Filter filter=new IntentFilter();
filter.addAction("android.intent.action.PHONE_STATE");
//Create instance of BroadcastReceiver
receiver=new BroadcastReceiver()
{
#Override
public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
Bundle bundle = intent.getExtras();
if (bundle == null)
return;
// Incoming call
String state =
bundle.getString(TelephonyManager.EXTRA_STATE);
if ((state != null) &&
(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING)))
{
phoneNumber =
bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
//if phoneNumber is not blank get location details
if(!phoneNumber.isEmpty())
{
//Do work here
}
}
}
};
registerReceiver(receiver, filter);
} }
Regards.
I was trying to do a service sample program and i am getting following exception
09-10 20:57:57.871: E/AndroidRuntime(280): FATAL EXCEPTION: main 09-10
20:57:57.871: E/AndroidRuntime(280): java.lang.RuntimeException:
Unable to instantiate service com.example.demoservice.DownloadService:
java.lang.InstantiationException:
com.example.demoservice.DownloadService
I have seen many solutions to this type of execption like passing string to constructor etc.But those solutions didnt solved this issue.
Code sample is given below
public class MainActivity extends Activity {
TextView textView ;
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle bundle = intent.getExtras();
if(bundle != null){
String filepath = bundle.getString(DownloadService.FILEPATH);
int result = bundle.getInt(DownloadService.RESULT);
if(result == Activity.RESULT_OK){
Toast.makeText(context, "Sucess" + filepath, Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, "Sucess", Toast.LENGTH_SHORT).show();
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.status);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View v){
Intent i = new Intent(this, DownloadService.class);
i.putExtra(DownloadService.FILENAME, "index.html");
i.putExtra(DownloadService.URL, "http://www.vogella.com/index.html");
startService(i);
textView.setText("Service started");
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
registerReceiver(receiver, new IntentFilter(DownloadService.NOTIFICATION));
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(receiver);
}
}
Service class
public class DownloadService extends IntentService{
private int result = Activity.RESULT_CANCELED;
public static final String URL = "urlpath";
public static final String FILENAME = "filename";
public static final String FILEPATH = "filepath";
public static final String RESULT = "result";
public static final String NOTIFICATION = "com.vogella.android.service.receiver";
public DownloadService(String name) {
super("DownloadService");
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
String urlpath = intent.getStringExtra(URL);
String filename = intent.getStringExtra(urlpath);
File output = new File(Environment.getExternalStorageDirectory(), filename);
if(output.exists()){
output.delete();
}
InputStream input = null;
FileOutputStream fout = null;
try {
java.net.URL url = new java.net.URL(urlpath);
input = url.openConnection().getInputStream();
InputStreamReader reader = new InputStreamReader(input);
fout = new FileOutputStream(output.getPath());
int next = -1;
while((next = reader.read())!= -1){
fout.write(next);
}
result = Activity.RESULT_OK;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(input != null){
try {
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fout != null){
try {
fout.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
publishResult( output.getAbsoluteFile(), result);
}
private void publishResult(File absoluteFile, int result2) {
// TODO Auto-generated method stub
Intent intent = new Intent(this,DownloadService.class);
intent.putExtra(FILEPATH, absoluteFile);
intent.putExtra(RESULT, result2);
sendBroadcast(intent);
}
}
I am running app using Emulator.Is it possible to run this problem in emulator,because writing to external directory
Can anyone help me?
Use
public DownloadService() {
super("DownloadService");
// TODO Auto-generated constructor stub
}
Instead of
public DownloadService(String name) {
super("DownloadService");
// TODO Auto-generated constructor stub
}
UPDATE:
You have to declare a default constructor which calls the public IntentService (String name) super constructor of the IntentService class you extend. ie. In simple words, you need to provide no-argument constuctor for your service ,without which android wont be able to instantiate your service.
you start the intentservice using startService(your_intent); And as per the documentation
You should not override onStartCommand() method for your
IntentService. Instead, override onHandleIntent(Intent), which the
system calls when the IntentService receives a start request.
IntentService
I am trying to start a service from a thread which I hava initialized with getApplicationContext() but context.startService returns null. I can't figure out why.
Thanks in advance.
Mainlogic.java
public class MainLogic extends Thread {
Context context;
public MainLogic(Context context) {
this.context = context;
}
ArrayList<Messenger> mClients = new ArrayList<Messenger>();
Messenger bluetoothService;
Messenger mMessanger = new Messenger(new MainHandler());
private class MainHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MessageType.NEW_HEARTH_RATE: {
//stuff
break;
}
case MessageType.REGISTER: {
mClients.add(msg.replyTo);break;
}
case MessageType.UNREGISTER: {
mClients.remove(msg.replyTo);break;
}
case MessageType.START_BLUETOOTH_SERVICE: {
startBluetoothService();
break;
}
default:
break;
}
}
}
private ServiceConnection bluetoothConnection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
Message msg = Message.obtain();
msg.what = MessageType.CONNECTION_ENDED;
msg.replyTo = mMessanger;
try {
bluetoothService.send(msg);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
bluetoothService = new Messenger(service);
Message msg = Message.obtain();
msg.replyTo = mMessanger;
msg.what = MessageType.CONNECTION_ESTABLISHED;
try {
bluetoothService.send(msg);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public void startBluetoothService() {
//This is where i start the service
Intent intent = new Intent(context, BluetoothService.class);
ComponentName name= context.startService(intent);
//name equals null after startService
boolean bind=context.bindService(new Intent(context, BluetoothService.class),
//bind equals false after bindService
bluetoothConnection, Context.BIND_AUTO_CREATE);
}
#Override
public void run() {
while(true){
}
}
public Messenger getMessanger() {
return mMessanger;
}
}
BluetoothService.java:
public class BluetoothService extends Service {
private NumberGenerator nGenerator;
final Messenger mMessenger = new Messenger(new BluetoothServiceHandler());
ArrayList<Messenger> mClients = new ArrayList<Messenger>();
private final class BluetoothServiceHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
//random messaging
}
default:
break;
}
}
}
#Override
public void onCreate() {
HandlerThread thread = new HandlerThread("BluetoothService",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Message msg = Message.obtain();
msg.arg1 = startId;
msg.what = MessageType.START_NUMBERGENERATOR;
try {
mMessenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
return START_STICKY;
}
#Override
public void onDestroy() {
Message msg = Message.obtain();
msg.what = MessageType.BLUETOOTH_SERVICE_STOPED;
try {
mMessenger.send(msg);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return mMessenger.getBinder();
}
}
And this is how I start the thread:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainLogic mainLogic=new MainLogic(this.getApplicationContext());
mainLogic.setPriority(Thread.MAX_PRIORITY);
mainLogic.start();
mainMessenger=mainLogic.getMessanger();
Message message= Message.obtain();
message.what=MessageType.REGISTER;
message.replyTo=actMessenger;
try {
mainMessenger.send(message);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
Update 1: Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.bugra.bluetoothcomponent"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<service android:name="BluetoothService" />
<activity
android:name="com.bugra.bluetoothcomponent.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The problem is probably in the manifest declaration. You must have an exception when trying to start this service telling you that it is not found. You should put the fully qualified name of your service (with the package name), or at least a dot "." in front of the name if your Service is in the root package. Your manifest line should look like this:
<service android:name=".BluetoothService" />
Or:
<service android:name="com.bugra.bluetoothcomponent.BluetoothService" />