Android Notification from non-activity class - java

I want to call the notify() method which is in MainActivity from another class. This is how I did it:
public class MyAlarmService extends Service{
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
#SuppressWarnings("static-access")
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
String title = "title";
String message = "message";
new MainActivity().Notify(title, message);
...
MainActivity:
public class MainActivity extends Activity {
NotificationManager manager;
Notification myNotication;
#Override
protected void onCreate(Bundle savedInstanceState) {
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
...
public void Notify(String notificationTitle, String notificationMessage){
Intent intent = new Intent("com.xxxx.app.MainActivity");
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 1, intent, 0);
Notification.Builder builder = new Notification.Builder(MainActivity.this);
builder.setAutoCancel(false);
builder.setTicker("this is ticker text");
builder.setContentTitle("Notification");
builder.setContentText("Text");
builder.setSmallIcon(R.drawable.infoicon);
builder.setContentIntent(pendingIntent);
builder.setOngoing(true);
builder.setSubText("This is subtext...");
builder.setNumber(100);
builder.build();
myNotication = builder.getNotification();
manager.notify(11, myNotication);
}
...
But I get an error message:
FATAL EXCEPTION: main
Process: com.xxxx.app, PID: 10311
java.lang.RuntimeException: Unable to start service com.xxxx.app.MyAlarmService#636e513 with Intent { cmp=com.xxxx.app/.MyAlarmService }: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3027)
at android.app.ActivityThread.-wrap17(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1442)
at android.os.Handler.dispatchMessage(Handler.java:102)
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.content.Context.getPackageName()' on a null object reference
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:133)
at android.app.PendingIntent.getActivity(PendingIntent.java:305)
at android.app.PendingIntent.getActivity(PendingIntent.java:272)
at com.xxxx.app.MainActivity.Notify(MainActivity.java:304)
at com.xxxx.app.MyAlarmService.onStart(MyAlarmService.java:41)
at android.app.Service.onStartCommand(Service.java:459)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3010)
at android.app.ActivityThread.-wrap17(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1442) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
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) 

You can do the same in following ways:
1) Copy that Notify method into the service and call it wherever you need order to trigger notification, Notification Service needs Context either Activity or service)
2) You can communicate to the activity from the service through broadcast receivers
3) You can do by using aidl

Trigger the notification in the Service class inside the onStart() method, and start the service from the MainActivity class using an Intent. Also, don't forget to declare your service in the manifest.
Here's the code to start the service from activity:
Intent intent = new Intent(this, MyAlarmService.class);
startService(intent);

Related

How to get Activity/getWindow() from services java class?

I'm trying to run a function that requires passing it a screen capture. When I run this from the main activity, I can run the code like this:
SendScreenFunction(getWindow().getDecorView().getRootView(), getApplicationContext());
I'm not trying to call this function from a service and I can't access the getWindow() function because it requires an activity (which isn't available in the service). I was looking around online and someone suggested a function to get the activity so I can use the function. My current code looks like this:
public class ASTasks extends Service {
// This method run only one time. At the first time of service created and running
#Override
public void onCreate() {
HandlerThread thread = new HandlerThread("ServiceStartArguments",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
Log.d("onCreate()", "After service created");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Entered Timer!", Toast.LENGTH_SHORT).show();
Activity main_activity = getActivity(getApplicationContext());
try {
Log.i("Services", "Before crash");
SendScreenFunction(main_activity.getWindow().getDecorView().getRootView(), getApplicationContext());
Log.i("Services", "After crash");
} catch (IOException e) {
e.printStackTrace();
}
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// We don't provide binding
return null;
}
public void SendScreenFunction(View view, Context context){
// Function goes here
}
public static Activity getActivity(Context context) {
if (context == null) return null;
if (context instanceof Activity) return (Activity) context;
if (context instanceof ContextWrapper) return getActivity(((ContextWrapper)context).getBaseContext());
return null;
}
}
Unfortunately, that solution doesn't seem to work and it's crashing. The Logcat error is shown below:
Process: com.example.ASservice:remote, PID: 15966
java.lang.RuntimeException: Unable to start service com.example.ASservice.ASTasks#6e7fed5 with Intent { cmp=com.example.ASservice/.ASTasks }: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window android.app.Activity.getWindow()' on a null object reference
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:5110)
at android.app.ActivityThread.access$2100(ActivityThread.java:310)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2319)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:226)
at android.os.Looper.loop(Looper.java:313)
at android.app.ActivityThread.main(ActivityThread.java:8680)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:567)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window android.app.Activity.getWindow()' on a null object reference
at com.example.ASservice.ASTasks.onStartCommand(ASTasks.java:41)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:5092)
at android.app.ActivityThread.access$2100(ActivityThread.java:310) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2319) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loopOnce(Looper.java:226) 
at android.os.Looper.loop(Looper.java:313) 
at android.app.ActivityThread.main(ActivityThread.java:8680) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:567) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135) 
Any ideas on the best way to take the screen capture from within the service (or even a way to pass a flag back to main to process it there)?
Any suggestions would be greatly appreciated. Thanks!

How to move reusable functionalities to a generic class and invoke another activity from there?

I am new to Android development and I am facing an issue in invoking an activity from a generic class where I have a reusable function.
I have MainActivity where I need to check if the application has Network connectivity and then check if the user is already signed in.
If the user is signed in I need to open the Rate activity otherwise I will open the Login activity.
I thought I can keep the logic that checks the Network connectivity and shows the popup reusable and move it to a Global class as below
public class Global extends AppCompatActivity {
public static boolean hasConnectivity = false;
public static boolean userSignedIn = false;
String TAG = "Debug Log - Helper";
Context context;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
context = this;
}
private void networkConnectionErrorDialog(final Context context, final Class targetClass){
Log.d(TAG, "Show Alert Dialog");
new AlertDialog.Builder(context)
.setTitle(R.string.connection_error_title)
.setMessage(R.string.connection_error_message)
.setIcon(R.drawable.warning)
.setPositiveButton(
R.string.try_again,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, "Trying Again");
isNetworkAvailable(context, targetClass);
}
}).show();
}
protected void isNetworkAvailable(Context context, Class targetClass) {
if(NetworkUtil.isConnected(context)){
Log.d(TAG, "Has connectivity");
if(targetClass != null){
Log.d(TAG, targetClass.toString());
Intent targetIntent = new Intent(context, targetClass);
startActivity(targetIntent);
}
hasConnectivity = true;
return;
}else{
Log.d(TAG, "Has no connectivity");
hasConnectivity = false;
networkConnectionErrorDialog(context, targetClass);
}
}
}
I pass in the targetClass as Login.class or Rate.class (based on user signed in state) from the MainActivity where isNetworkAvailable() is invoked.
I am getting the following error. Could someone help me fix the issue and help me understand if my approach needs improvement?
java.lang.RuntimeException: Unable to resume activity {com.solitontech.dayatsoliton/com.solitontech.dayatsoliton.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3581)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3621)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2862)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
at android.app.Activity.startActivityForResult(Activity.java:4488)
at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
at android.app.Activity.startActivityForResult(Activity.java:4445)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
at android.app.Activity.startActivity(Activity.java:4806)
at android.app.Activity.startActivity(Activity.java:4774)
at com.solitontech.dayatsoliton.Global.isNetworkAvailable(Global.java:50)
at com.solitontech.dayatsoliton.MainActivity.onResume(MainActivity.java:68)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1355)
at android.app.Activity.performResume(Activity.java:7117)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3556)
It looks like your application is experiencing a null pointer exception in your activity's onResume method. If you had called startActivityForResult, make sure that the data in
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{..}
is non null before processing it.
As for your question about starting an activity from your helper class Global, you can define a function like this.
private static void goToActivity(Context context, Class<?> activityClass){
Intent intent = new Intent(context, activityClass);
context.startActivity(intent);
}
You can call this method as below.
goToActivity(context,TargetActivity.class);
Good luck.
Intent targetIntent = new Intent(context, targetClass);
startActivity(targetIntent);
above code is wrong. You should pass your current activity and target activity here.
Intent intent = new Intent(CurrentActivity.this, TargetingActivity.class);
startActivity(intent);
As a example :
If you want to start ActivtyB form ActivtyA
Intent intent = new Intent(ActivityA.this, ActivityD.class);
startActivity(intent);
1st try to correct this error. then you can find some others.

Null Error attempting to create an intent in AsyncTask

Apologizes if this is a stupid question but I'm attempting to create a Intent to the next activity in AsynTask after it has pulled a user from my AWS Database. Note that this class is HomeActivity and the next one is GroupActivity. Below I have the button that will run the AsynTask:
Button groupPageBtm = findViewById(R.id.groupPage);
groupPageBtm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LoadGroupUser loadGroupUser = new LoadGroupUser(HomeActivity.this);
loadGroupUser.execute(makeUserIDString.uniqueIDCreater(userProfile));
}
});
Here is my AsynTask subclass:
class LoadGroupUser extends AsyncTask<String, Void, GroupDO>{
private DynamoDBMapper dynamoDBMapper;
Activity activity;
public LoadGroupUser(Activity mActivity){
this.activity = mActivity;
}
Intent groupLoadIntent = new Intent(activity, GroupActivity.class);
#Override
protected GroupDO doInBackground(String... groupPresidentGroups) {
AmazonDynamoDBClient dynamoDBClient = new AmazonDynamoDBClient(AWSMobileClient.getInstance().getCredentialsProvider());
this.dynamoDBMapper = DynamoDBMapper.builder()
.dynamoDBClient(dynamoDBClient)
.awsConfiguration(AWSMobileClient.getInstance().getConfiguration())
.build();
GroupDO groupPresDO = dynamoDBMapper.load(GroupDO.class, groupPresidentGroups[0]);
Log.i("loadedPresident: ", groupPresDO.getGroupId().toString());
return null;
}
#Override
protected void onPostExecute(GroupDO groupDO) {
super.onPostExecute(groupDO);
groupLoadIntent.putExtra("groupPresident", groupDO.getGroupPresident().toString());
activity.startActivity(groupLoadIntent);
Log.i("groupPresident", groupDO.getGroupPresident().toString());
}
}
Error Message:
-12 17:02:59.424 10503-10503/com.ronone.securesender E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ronone.securesender, PID: 10503
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ComponentName.<init>(ComponentName.java:130)
at android.content.Intent.<init>(Intent.java:5780)
at com.ronone.securesender.LoadGroupUser.<init>(HomeActivity.java:188)
at com.ronone.securesender.HomeActivity$1.onClick(HomeActivity.java:77)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
The problem is here:
public LoadGroupUser(Activity mActivity){
this.activity = mActivity;
}
Intent groupLoadIntent = new Intent(activity, GroupActivity.class);
The field initializer runs before the constructor, so activity is still null. Do this instead:
Intent groupLoadIntent;
public LoadGroupUser(Activity mActivity){
this.activity = mActivity;
groupLoadIntent = new Intent(activity, GroupActivity.class);
}
But note that you're potentially leaking your activity by having a strong reference to it in an AsyncTask. That's a whole other topic. Search this site for "AsyncTask activity leak."

android.app.ActivityThread.getApplicationThread()' on a null object reference

The microhonePopUp method will work in MainActivity, but I'd like for it to work from another class (MediaButtonIntentReceiver). The problem is with startActivityForResult(intent, REQUEST_CODE); - but I don't know how to resolve it.
in the MainActivity class
public void microphonePopUp(){
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Voice your answer");
startActivityForResult(intent, REQUEST_CODE);
}
in the MediaButtonIntentReceiver class
public class MediaButtonIntentReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (KeyEvent.KEYCODE_HEADSETHOOK == event.getKeyCode()) {
MainActivity test = new MainActivity();
test.microphonePopUp();
}
}
}
}
12-09 11:20:14.803 19556-19556/com.timtennyson.priceaddition
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.timtennyson.priceaddition, PID: 19556
java.lang.RuntimeException: Unable to start receiver
com.timtennyson.priceaddition.MediaButtonIntentReceiver:
java.lang.NullPointerException: Attempt to invoke virtual method
'android.app.ActivityThread$ApplicationThread
android.app.ActivityThread.getApplicationThread()' on a null object
reference
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3641)
at android.app.ActivityThread.access$2000(ActivityThread.java:221)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1876)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'android.app.ActivityThread$ApplicationThread
android.app.ActivityThread.getApplicationThread()' on a null object
reference
at android.app.Activity.startActivityForResult(Activity.java:4283)
at android.app.Activity.startActivityForResult(Activity.java:4230)
at
android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:842)
at
com.timtennyson.priceaddition.MainActivity.microphonePopUp(MainActivity.java:103)
at
com.timtennyson.priceaddition.MediaButtonIntentReceiver.onReceive(MediaButtonIntentReceiver.java:27)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3634)
at android.app.ActivityThread.access$2000(ActivityThread.java:221) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1876) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:158) 
at android.app.ActivityThread.main(ActivityThread.java:7224) 
at java.lang.reflect.Method.invoke(Native Method)
NEVER create an instance of an activity, service, or provider yourself.
If your objective is to listen for ACTION_MEDIA_BUTTON broadcasts while MainActivity is visible:
Move MediaButtonIntentReceiver to be a nested class inside of MainActivity
Get rid of test from onReceive(), and just call microphonePopUp() (which I assume is a method on MainActivity)
Register your MediaButtonIntentReceiver using registerReceiver() in onStart() of MainActivity, and use unregisterReceiver() in onStop()
If your objective is to listen ACTION_MEDIA_BUTTON broadcasts at other points in time — by registering your receiver in the manifest — while you can do that, you cannot use microphonePopUp() from that receiver.

Error java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService

I'm creating a simple Android Class that update a variable with the most recent value readed from some specific sensors (Light, temp and more), which I access it(sensor value) by getData() method, but i'm getting an error. I hope u can help me!
Here is my generic sensor class.
MySensor
public class mySensor extends Service implements SensorEventListener {
private SensorManager mSensorManager =null;
private Sensor s=null;
float data = 0;
public void onCreate(){
super.onCreate();
mSensorManager= (SensorManager) getSystemService(Context.SENSOR_SERVICE);
}
public mySensor(int type){
//HERE I'M GETTING THE ERROR
s= mSensorManager.getDefaultSensor(type);
}
public String getData(){
return String.valueOf(data);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_LIGHT) {
data = event.values[0];
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
protected void onResume() {
mSensorManager.registerListener((SensorEventListener) this, s, SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause() {
// super.onPause();
mSensorManager.unregisterListener((SensorEventListener) this);
}
}
Here is the log
...
E/AndroidRuntime: FATAL EXCEPTION: main
Process: project.luke.com.sensorreader, PID: 25297
java.lang.RuntimeException: Unable to start activity ComponentInfo{project.luke.com.sensorreader/project.luke.com.sensorreader.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.hardware.Sensor android.hardware.SensorManager.getDefaultSensor(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2460)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2522)
at android.app.ActivityThread.access$800(ActivityThread.java:169)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5546)
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:967)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.hardware.Sensor android.hardware.SensorManager.getDefaultSensor(int)' on a null object reference
at project.luke.com.sensorreader.mySensor.<init>(mySensor.java:39)
at project.luke.com.sensorreader.MainActivity.onCreate(MainActivity.java:32)
at android.app.Activity.performCreate(Activity.java:5975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2522) 
at android.app.ActivityThread.access$800(ActivityThread.java:169) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421) 
at android.os.Handler.dispatchMessage(Handler.java:111) 
at android.os.Looper.loop(Looper.java:194) 
at android.app.ActivityThread.main(ActivityThread.java:5546) 
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:967) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762) 
In my MainActivity class I simple call mLight=new mySensor(Sensor.TYPE_LIGHT); but this trigger the error, cause mSensorManager=null, always.
From your MainActivity:
Intent intent = new Intent(this, mySensor.class);
intent.putExtra("type", Sensor.TYPE_LIGHT);
and within your service:
#Override
public IBinder onBind(Intent intent) {
mSensorManager= (SensorManager) getSystemService(Context.SENSOR_SERVICE);
int type = intent.getExtras().get("type");
s= mSensorManager.getDefaultSensor(type);
return null;
}
then you can remove:
public mySensor(int type){
...
}
and eventually the code you wrote within the onCreate.

Categories