null pointer exception in startforeground service android - java

I am starting a foreground service and I am getting a null pointer exception. I'm not getting which is the null reference. I want to download the mp3 from server and show the progress in notification like google play-store does for each application downland.
Does new MyNotification(getApplicationContext() is null?
07-31 14:48:39.504 21210-21210/com.sunil.divine.mybhajans E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.sunil.divine.mybhajans, PID: 21210
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:106)
at service.DownloadingService.startForegroundService(DownloadingService.java:47)
at com.sunil.divine.mybhajans.List_songs.itemClick(List_songs.java:104)
at service.SunilAdaptor$MyViewHolder.onClick(SunilAdaptor.java:75)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Please don't close the question. Please explain to me the proper way to handle this.
Thanks.
Following is itemClick for each row in Listview
#Override
public void itemClick(View view, int position) {
Toast.makeText(this, "On ItemClick", Toast.LENGTH_LONG).show();
Intent intent=new Intent(this, DownloadingService.class);
switch (position){
case 0:
intent.putExtra("position","URL");
//List_songs.java:104 null pointer
new DownloadingService().startForegroundService(position);
break;
case 1:
intent.putExtra("position", "URL");
new DownloadingService().startForegroundService(position);
break;
}
}
following is the DownloadingService() class:
package service;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
import java.util.concurrent.Executor;
/**
* Created by Dell Vostro on 7/19/2015.
*/
public class DownloadingService extends Service {
#Override
public void onCreate() {
Log.w("Inside","--------------Oncreate method-----------");
Toast.makeText(getApplicationContext(),"Inside oncreate",Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.w("Inside","--------------onStartCommand method-----------"+startId);
String url= (String) intent.getExtras().get("position");
String param[]={url};
//task to download the mp3
new DownloadFilesTask(this,startId).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,param);
// Toast.makeText(getApplicationContext(),"Inside onStartCommand"+pos,Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
}
public void startForegroundService(int position){
//DownloadingService.java:47 null pointer here
startForeground(position,new MyNotification(getApplicationContext()).createNotification(position));
}
}
following is class to generate notification:
package service;
import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import com.sunil.divine.mybhajans.R;
/**
* Created by Dell Vostro on 7/30/2015.
*/
public class MyNotification {
private int position;
private Context context;
private NotificationManager mNotifyManager;
private NotificationCompat.Builder mBuilder;
public MyNotification() {
}
public MyNotification(Context context) {
this.context=context;
}
public android.app.Notification createNotification(int position) {
mNotifyManager =
(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(context);
mBuilder.setContentTitle("Song Download")
.setContentText("Download in progress")
.setSmallIcon(R.mipmap.ic_launcher);
// Sets the progress indicator to a max value, the
// current completion percentage, and "determinate"
// state
mBuilder.setProgress(100, new DownloadFilesTask().getCalculatedProgress(), false);
// Displays the progress bar for the first time.
mNotifyManager.notify(position, mBuilder.build());
return mBuilder.build();
}
// Update the progress bar
public void updateNotification(int calculatedProgress,int startId){
mBuilder.setProgress(100, calculatedProgress, false);
mNotifyManager.notify(startId, mBuilder.build());
}
}

Well, your issue is that's not how you start a service in the foreground. You should read about Android Services, their lifecycle, and how to start a service. Your code contains several fundamental mistakes.
Take a look at this example for how to launch a foreground service
In terms of what's specifically wrong with your code, the simplest explanation is that, you should start an intent that starts the service then within the service (while it is running and has correct context), call startforeground. Instead, you create an object and call startforeground from within your application.

Related

java.lang.IllegalArgumentException: Cannot find an axis to label. A valid axis to label should have size larger than 1 in TensorFlow lite model

I'm building an image classifier android app to classify cat and dog images by using my own Tensor Flow model built using Python.I generated the meta data for my model and added to android studio by using ML Model plugin which is under beta.I automatically generates code for the given model with meta-data so that it is easy to integrate with Android app.
I used Sigmoid function at outputlayer of the file and by label file has
Here is my model meta data
This is the sample code
Here is my code it picks image from gallery and convert to Bitmap and send it to model.But when i call the predict function by passing bitmap image the app crashes with this error.How to solve this error and why does it occur.
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=Intent { dat=content://com.google.android.apps.photos.contentprovider/-1/1/content://media/external/images/media/35/ORIGINAL/NONE/image/jpeg/2016858078 flg=0x1 clip={text/uri-list {...}} }} to activity {com.enigmabits.myapplication/com.enigmabits.myapplication.MainActivity}: java.lang.IllegalArgumentException: Cannot find an axis to label. A valid axis to label should have size larger than 1.
at android.app.ActivityThread.deliverResults(ActivityThread.java:5015)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5056)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.IllegalArgumentException: Cannot find an axis to label. A valid axis to label should have size larger than 1.
at org.tensorflow.lite.support.label.TensorLabel.getFirstAxisWithSizeGreaterThanOne(TensorLabel.java:214)
at org.tensorflow.lite.support.label.TensorLabel.<init>(TensorLabel.java:105)
at com.enigmabits.myapplication.ml.DogvsCat$Outputs.getProbabilityAsCategoryList(DogvsCat.java:100)
at com.enigmabits.myapplication.MainActivity.predictImage(MainActivity.java:91)
at com.enigmabits.myapplication.MainActivity.onActivityResult(MainActivity.java:73)
at android.app.Activity.dispatchActivityResult(Activity.java:8310)
at android.app.ActivityThread.deliverResults(ActivityThread.java:5008)
MainActivity.java
package com.enigmabits.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.Image;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import com.enigmabits.myapplication.ml.DogvsCat;
import org.tensorflow.lite.support.image.TensorImage;
import org.tensorflow.lite.support.label.Category;
import java.io.IOException;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button pickbutton;
Button predictbutton;
ImageView img;
private static final int PICK_IMAGE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pickbutton = findViewById(R.id.pickbtn);
predictbutton = findViewById(R.id.predictbtn);
img = findViewById(R.id.imageView);
pickbutton.setOnClickListener(this);
predictbutton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.predictbtn:
{
break;
}
case R.id.pickbtn:
{ openGallery();
break;
}
}
}
private void openGallery() {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE){
//img.setImageURI(data.getData());
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),data.getData());
img.setImageBitmap(bitmap);
predictImage(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
void predictImage(Bitmap b)
{
try {
DogvsCat model = DogvsCat.newInstance(this);
// Creates inputs for reference.
TensorImage image = TensorImage.fromBitmap(b);
// Runs model inference and gets result.
DogvsCat.Outputs outputs = model.process(image);
List<Category> probability = outputs.getProbabilityAsCategoryList();
predictbutton
// Releases model resources if no longer used.
model.close();
} catch (IOException e) {
Log.d("error",e.getLocalizedMessage());
}
}
}
I get error when this line is excecuted
List<Category> probability = outputs.getProbabilityAsCategoryList();

NullPointerException getPackageName() on bindService

I'm trying to create a remote service for an android app. I've more or less copied the code from the Android Developers website, retooling it for my purposes. When I get to the bindService step, though, I get a NullPointerException on android.content.Context.getPackageName(). What am I doing wrong?
I've used an in process service with an earlier version of the app, but it wasn't enough for what I wanted from it. The service itself remained the same between the two, other than the necessary changes in code. I've looked at all the results on here, but they were either not related or didn't help me any.
I've tried moving the calls from onCreate to onStart. No difference. onCreate for the BinderActivity never executed. I tried startService instead of bindService, but it gave me the same error. I've checked that this, the intent, and mConnection were all non-null (they are). I know that the service isn't started, but I'm using Context.BIND_AUTO_CREATE (which is supposed to start it if it's not). Short of waving a dead chicken over the problem, I'm not sure what else to do here.
My MainActivity:
package com.example.trainchecker;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.os.Message;
import android.os.Messenger;
import java.io.*;
import java.util.ArrayList;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BinderActivity ba = new BinderActivity();
ba.BindService();
}
}
This is the BinderActivity, where the magic is supposed to happen. Instead, the error does:
package com.example.trainchecker;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.os.Message;
import android.os.Handler;
import android.os.Messenger;
public class BinderActivity extends Activity {
public Messenger ms = null;
private MainActivity ma;
class IncomingHandler extends Handler{
#Override
public void handleMessage(Message msg){
super.handleMessage(msg);
}
}
final Messenger mm = new Messenger(new IncomingHandler());
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
Log.d("MCon","Sentinel Online");
ms = new Messenger(service);
try {
Message msg = Message.obtain(null,TCService.MSG_REGISTER_CLIENT);
msg.replyTo = mm;
ms.send(msg);
} catch (RemoteException e){ e.printStackTrace();}
}
public void onServiceDisconnected(ComponentName className) {
Log.d("MCon","Sentinel Offline");
try {
Message msg = Message.obtain(null,2);
msg.replyTo = mm;
ms.send(msg);
} catch (RemoteException e){ e.printStackTrace();}
}
};
public void BindService() {
bindService(new Intent(this, TCService.class), mConnection, Context.BIND_AUTO_CREATE);
}
}
And, finally, the service itself. Not much there, but it's mine:
package com.example.trainchecker;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import java.util.ArrayList;
import android.os.Message;
import android.os.Messenger;
public class TCService extends Service {
ArrayList<Messenger> mc = new ArrayList<>();
#Override
public IBinder onBind(Intent i) {
Log.d("TCS", "Binding Now");
return mm.getBinder();
}
static final int MSG_REGISTER_CLIENT = 1;
class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
mc.add(msg.replyTo);
break;
case 2:
mc.remove(msg.replyTo);
break;
default:
super.handleMessage(msg);
}
}
}
final Messenger mm = new Messenger(new IncomingHandler());
}
Here is the error in it's entirety:
09-15 11:39:04.518 15448-15448/com.example.trainchecker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.trainchecker, PID: 15448
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.trainchecker/com.example.trainchecker.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.access$900(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:171)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:133)
at android.content.ComponentName.<init>(ComponentName.java:128)
at android.content.Intent.<init>(Intent.java:4468)
at com.example.trainchecker.BinderActivity.BindService(BinderActivity.java:58)
at com.example.trainchecker.MainActivity.onCreate(MainActivity.java:65)
at android.app.Activity.performCreate(Activity.java:6285)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.access$900(ActivityThread.java:150) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:171) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Programmatically instantiating an Activity instance doesn't trigger lifecycles therefore your context isn't valid there. Pass it to your BindService() call. Technically speaking your BinderActivity doesn't need to exist and can live in your MainAcitivity or a service.

java.lang.RuntimeException: An error occurred while executing doInBackground() Singleton android error

Ihave a problem in sending image from and Android application to API . I am getting "java.lang.RuntimeException: An error occurred while executing doInBackground()" error. Please advice me on what to do. Thanks.
RecognizeConceptsActivity.java
package com.example.statistic.api.v2.activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.ViewSwitcher;
import com.example.statistic.R;
import com.example.statistic.api.v2.App;
import com.example.statistic.api.v2.ClarifaiUtil;
import com.example.statistic.api.v2.adapter.RecognizeConceptsAdapter;
import java.util.Collections;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import clarifai2.api.ClarifaiResponse;
import clarifai2.dto.input.ClarifaiImage;
import clarifai2.dto.input.ClarifaiInput;
import clarifai2.dto.model.ConceptModel;
import clarifai2.dto.model.output.ClarifaiOutput;
import clarifai2.dto.prediction.Concept;
import static android.view.View.GONE;
import static android.view.View.VISIBLE;
public final class RecognizeConceptsActivity extends BaseActivity {
public static final int PICK_IMAGE = 100;
// the list of results that were returned from the API
#BindView(R.id.resultsList)
RecyclerView resultsList;
// the view where the image the user selected is displayed
#BindView(R.id.image2)
ImageView imageView;
// switches between the text prompting the user to hit the FAB, and the loading spinner
#BindView(R.id.switcher)
ViewSwitcher switcher;
// the FAB that the user clicks to select an image
#BindView(R.id.fab)
View fab;
#NonNull
private final RecognizeConceptsAdapter adapter = new RecognizeConceptsAdapter();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onStart() {
super.onStart();
resultsList.setLayoutManager(new LinearLayoutManager(this));
resultsList.setAdapter(adapter);
}
#OnClick(R.id.fab)
void pickImage() {
startActivityForResult(new Intent(Intent.ACTION_PICK).setType("image/*"), PICK_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
switch(requestCode) {
case PICK_IMAGE:
final byte[] imageBytes = ClarifaiUtil.retrieveSelectedImage(this, data);
if (imageBytes != null) {
onImagePicked(imageBytes);
}
break;
}
}
private void onImagePicked(#NonNull final byte[] imageBytes) {
// Now we will upload our image to the Clarifai API
setBusy(true);
// Make sure we don't show a list of old concepts while the image is being uploaded
adapter.setData(Collections.<Concept>emptyList());
new AsyncTask<Void, Void, ClarifaiResponse<List<ClarifaiOutput<Concept>>>>() {
#Override
protected ClarifaiResponse<List<ClarifaiOutput<Concept>>> doInBackground(Void... params) {
// The default Clarifai model that identifies concepts in images
final ConceptModel generalModel = App.get().clarifaiClient().getDefaultModels().generalModel();
// Use this model to predict, with the image that the user just selected as the input
return generalModel.predict()
.withInputs(ClarifaiInput.forImage(ClarifaiImage.of(imageBytes)))
.executeSync();
}
#Override
protected void onPostExecute(ClarifaiResponse<List<ClarifaiOutput<Concept>>> response) {
setBusy(false);
if (!response.isSuccessful()) {
showErrorSnackbar(R.string.error_while_contacting_api);
return;
}
final List<ClarifaiOutput<Concept>> predictions = response.get();
if (predictions.isEmpty()) {
showErrorSnackbar(R.string.no_results_from_api);
return;
}
adapter.setData(predictions.get(0).data());
imageView.setImageBitmap(BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length));
}
private void showErrorSnackbar(#StringRes int errorString) {
Snackbar.make(
root,
errorString,
Snackbar.LENGTH_INDEFINITE
).show();
}
}.execute();
}
#Override
protected int layoutRes() { return R.layout.activity_recognize; }
private void setBusy(final boolean busy) {
runOnUiThread(new Runnable() {
#Override
public void run() {
switcher.setDisplayedChild(busy ? 1 : 0);
imageView.setVisibility(busy ? GONE : VISIBLE);
fab.setEnabled(!busy);
}
});
}
}
App.java
public class App extends Application {
// In a real app, rather than attaching singletons (such as the API client instance) to your Application instance,
// it's recommended that you use something like Dagger 2, and inject your client instance.
// Since that would be a distraction here, we will just use a regular singleton.
private static App INSTANCE;
#NonNull
public static App get() {
final App instance = INSTANCE;
if (instance == null) {
throw new IllegalStateException("App has not been created yet!");
}
return instance;
}
#Nullable
private ClarifaiClient client;
#Override
public void onCreate() {
INSTANCE = this;
client = new ClarifaiBuilder(getString(R.string.clarifai_api_key))
// Optionally customize HTTP client via a custom OkHttp instance
.client(new OkHttpClient.Builder()
.readTimeout(30, TimeUnit.SECONDS) // Increase timeout for poor mobile networks
// Log all incoming and outgoing data
// NOTE: You will not want to use the BODY log-level in production, as it will leak your API request details
// to the (publicly-viewable) Android log
.addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
#Override
public void log(String logString) {
Timber.e(logString);
}
}).setLevel(HttpLoggingInterceptor.Level.BODY))
.build()
)
.buildSync(); // use build() instead to get a Future<ClarifaiClient>, if you don't want to block this thread
super.onCreate();
// Initialize our logging
Timber.plant(new Timber.DebugTree());
}
#NonNull
public ClarifaiClient clarifaiClient() {
final ClarifaiClient client = this.client;
if (client == null) {
throw new IllegalStateException("Cannot use Clarifai client before initialized");
}
return client;
}
}
This is the logcat error
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.statistic, PID: 3451
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:325)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.lang.IllegalStateException: App has not been created yet!
at com.example.statistic.api.v2.App.get(App.java:28)
at com.example.statistic.api.v2.activity.RecognizeConceptsActivity$1.doInBackground(RecognizeConceptsActivity.java:105)
at com.example.statistic.api.v2.activity.RecognizeConceptsActivity$1.doInBackground(RecognizeConceptsActivity.java:101)
at android.os.AsyncTask$2.call(AsyncTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
at java.lang.Thread.run(Thread.java:761) 
Please advice me on what to do. Thanks

How to make a service remain alive if the application is destroy from the memory

The main thing i just want to do is that i have to check on me webservice when my application is closed when it gets any alert on webservice then it shows notification or activity.
I read about services and make an example but when i remove the application from recent apps then some time the service is restarted or some the service got killed to.
Code:
package com.usamaakmal.startedservice;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.widget.Toast;
public class NewService extends Service {
public NewService() {
}
int i = 0;
Handler handler = new Handler();
Thread runnable = new Thread() {
#Override
public void run() {
i++;
Toast.makeText(getBaseContext(), "Hello World! " + i, Toast.LENGTH_SHORT).show();
handler.postDelayed(this,1000);
}
};
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
handler.postDelayed(runnable,2000);
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
}
Removing app from recent apps list kills app process. Returning START_STICKY from onStartCommand() means you want the system to restart the service after it was killed (either because you removed the app from recents list or system killed service because it ran out of resources).
If you want to keep your service (and it's process) alive you will need foreground service.
System tries to keep foreground services alive as long as possible.
See: Running service in foreground

Android - why the app crash when the service receive a call and the app is closed?

I am making an app that make something happen when the phone gets a call, so after a lot of searching I discover that I can use a BroadcastReceiver and a Service so I created a Service called PhoneStateService:
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.telephony.TelephonyManager;
import android.widget.Toast;
public class PhoneStateService extends Service {
private static BroadcastReceiver broadcastReceiver;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
registerBroadcastReceiver();
}
#Override
public void onDestroy() {
unregisterReceiver(broadcastReceiver);
broadcastReceiver = null;
}
private void registerBroadcastReceiver() {
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
if(stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING)){
new PhoneStateHandler().onIncomingCallStarted(context);
}
}
};
IntentFilter filter = new IntentFilter(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(broadcastReceiver, filter);
}
}
This is the code for starting PhoneStateService(inside MainActivity):
if(PermissionChecker.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PermissionChecker.PERMISSION_GRANTED) {
startService(new Intent(getApplicationContext(), PhoneStateService.class));
}
part from the Manifest file:
<service android:name=".Service.PhoneStateService" />
When the phone gets a call and the app is running (it's still didn't Destroy) everything is working good but after I close the app and the phone gets a call the app crash and give me the message that the app has stop working.
please tell me what is the problem, I didn't find answer.
Edit:
The Exception:
09-11 10:26:30.598 29461-29461/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.multiplies.multiring, PID: 29461
java.lang.RuntimeException: Error receiving broadcast Intent { act=android.intent.action.SCREEN_OFF flg=0x50000010 } in com.multiplies.multiring.Service.PhoneStateService$1#1924f18
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:891)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at com.multiplies.multiring.Service.PhoneStateService$1.onReceive(PhoneStateService.java:36)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:881)
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Edit:
I did what some people said:
String stateStr = intent.getExtras() != null ? intent.getExtras().getString(TelephonyManager.EXTRA_STATE) : "";
put the this doesn't fix the problem.
I thought it won't work because if the intent.getExtras() is returning null, then the if statement won't work because it's returning null and it's want TelephonyManager.EXTRA_STATE_RINGING:
if(stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING)){
new PhoneStateHandler().onIncomingCallStarted(context);
}
but thank you for your help.
HUGE EDIT:
part of the Manifest:
<service android:name=".PhoneState.PhoneStateService" />
<receiver android:name=".PhoneState.PhoneStateBroadcast">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
PhoneStateBroadcast:
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.util.Log;
public class PhoneStateBroadcast extends BroadcastReceiver {
Context context;
public void onReceive(Context context, Intent intent) {
this.context = context;
try {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
switch (telephonyManager.getCallState()) {
case TelephonyManager.CALL_STATE_RINGING:
context.startService(new Intent(context, PhoneStateService.class));
break;
}
} catch (Exception e) {
Log.e("Phone Receive Error", " " + e);
}
}
}
PhoneStateService:
import android.app.IntentService;
import android.content.Intent;
public class PhoneStateService extends IntentService {
public PhoneStateService(String name) {
super(name);
}
#Override
protected void onHandleIntent(Intent intent) {
new PhoneStateHandler().onIncomingCallStarted(getApplicationContext());
}
}
after this edit I am still getting crash.
For some reason the extra's are empty. You are doing intent.getExtras().XXX but intent.getExtras() returns null, calling .XXX on it throws an error.
Changing
String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
into
String stateStr = intent.getExtras() != null ? intent.getExtras().getString(TelephonyManager.EXTRA_STATE) : "";
will stop the crash from happening, but you might want to look into what the reason is why you expect extra's but there aren't any in the intent.
instead of Running a service All the time, make it a BroadcastReciever which is fired whenever the call state is changed.(Running service for a long period of time is not a good practice) thus by using Broadcast receiver, your service would run exactly when you want.
public class PhoneStateService extends BroadcastReceiver{
public void onReceive(Context context, Intent intent) {
mContext = context;
try {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
String deviceId=tm.getDeviceId();
switch (tm.getCallState()) {
case TelephonyManager.CALL_STATE_RINGING: // incoming call
//do something on Incoming call event
break;
case TelephonyManager.CALL_STATE_IDLE: //call Ends
//do something on Idle phone state i.e set your logic if an incoming call is complete then this block would execute.
}
} catch (Exception e) {
Log.e("Phone Receive Error", " " + e);
}
}
}
Then add this broadcastReciever to your Manifest under application tag
<receiver android:name="orbitsys.com.prospect_call.CallerState">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>

Categories