Null pointer exception - Service SMS with Text To Speech - java

I want to make an application with can say a text with a TextToSpeach when I receive a SMS.
For that I have a Service, a Receiver and a class SaidThis.
See my code :
My service :
package fr.dabernat.smsreceiver;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class Service extends IntentService {
private Handler handler;
public static String text;
public Service() {
super("Service");
}
#Override
public void onCreate() {
super.onCreate();
handler = new Handler();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
if (!extras.isEmpty()) {
SaidThis test = new SaidThis();
test.SpeakText();
//showNotification();
//SaidThis test = new SaidThis(this);
//test.text("J'ai honte de moi");
}
Receiver.completeWakefulIntent(intent);
}
}
My Receiver :
package fr.dabernat.smsreceiver;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
public class Receiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that Service will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
Service.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
My class SaidThis :
package fr.dabernat.smsreceiver;
import android.speech.tts.TextToSpeech;
import java.util.Locale;
/**
* Created by Damien on 19/09/2014.
*/
public class SaidThis extends Service implements TextToSpeech.OnInitListener, TextToSpeech.OnUtteranceCompletedListener {
TextToSpeech tts;
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
tts.setLanguage(Locale.FRANCE);
}
}
#Override
public void onUtteranceCompleted(String s) {
stopSelf();
}
public void SpeakText(){
tts.speak(text,TextToSpeech.QUEUE_FLUSH, null);
}
}
My Android Manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="fr.dabernat.smsreceiver" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".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>
<receiver
android:name=".Receiver" >
<intent-filter>
<!-- A CHANGER POUR "ECOUTER" UN AUTRE BROADCAST -->
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<service android:name=".Service" />
</application>
</manifest>
Errors :
10-08 10:44:51.980 1371-1371/fr.dabernat.smsreceiver E/dalvikvm﹕ >>>>> Normal User
10-08 10:44:51.980 1371-1371/fr.dabernat.smsreceiver E/dalvikvm﹕ >>>>> fr.dabernat.smsreceiver [ userId:0 | appId:10309 ]
10-08 10:44:52.080 1371-1412/fr.dabernat.smsreceiver E/AndroidRuntime﹕ FATAL EXCEPTION: IntentService[Service]
Process: fr.dabernat.smsreceiver, PID: 1371
java.lang.NullPointerException
at fr.dabernat.smsreceiver.SaidThis.SpeakText(SaidThis.java:34)
at fr.dabernat.smsreceiver.Service.onHandleIntent(Service.java:36)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.os.HandlerThread.run(HandlerThread.java:61)
I think the problem come from my service but I don't know where.
I try to find some answer on the web before but I don't find any solution to my problem.

Your tts object is not initialized anywhere, therefore it's null.
You have to initialize it: tts = new TextToSpeech() somewhere, before you use it in your SpeakText() method.
I assume onInit() method would be a good fit for initializing your object.

Related

Fetch the location of a device no matter what state the app is inAlways detect the location from my corporate application

I would like to get the location of corporate devices using a corporate application.
I've had success with locating the device when the application is in foreground but doesn't seem to work when the app is in the background or killed.
I tried to use push notification to start a service or broadcastReceiver when the app is closed or in background but nothing works.
Is there a way to fetch the location of a device no matter what state the app is in?
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.c7lab.fotodinamico">
<!--
io.flutter.app.FlutterApplication is an android.app.Application that
calls FlutterMain.startInitialization(this); in its onCreate method.
In most cases you can leave this as-is, but you if you want to provide
additional functionality it is fine to subclass or reimplement
FlutterApplication and put your custom class here.
-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name="io.flutter.app.FlutterApplication"
android:icon="#mipmap/ic_launcher"
android:label="Corporate Application">
<receiver android:name=".MyLocationService"></receiver>
<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:launchMode="singleTop"
android:theme="#style/LaunchTheme"
android:windowSoftInputMode="adjustResize">
<meta-data
android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
android:value="true" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<service
android:name="com.example.crm_agenti.MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
</manifest>
MyLocationService.class
package com.c7lab.fotodinamico;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.util.Log;
import com.google.android.gms.location.LocationResult;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import static android.content.Context.MODE_PRIVATE;
public class MyLocationService extends BroadcastReceiver {
public static final String ACTION_PROCESS_UPDATE = "com.c7lab.fotodinamico.UPDATE_LOCATION";
private static final String TAG = "MyLocationService";
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "MYSERVICE WORK?");
SharedPreferences prefs = context.getSharedPreferences("FlutterSharedPreferences", MODE_PRIVATE);
String shared = prefs.getString("flutter.jsonData", null);
JsonObject ed = new JsonObject();
Gson g = new Gson();
if(shared != null) {
ed = new JsonParser().parse(shared).getAsJsonObject();
}
String usr = "no-usr";
if(ed.get("usr") != null) {
usr = ed.get("usr").getAsString();
}
if(intent != null) {
final String action = intent.getAction();
if(ACTION_PROCESS_UPDATE.equals(action)) {
LocationResult result = LocationResult.extractResult(intent);
if(result != null) {
Location location = result.getLastLocation();
double latitude = location.getLatitude();
double longitude = location.getLongitude();
String location_string = new StringBuilder(""+latitude).append(" - ").append(longitude).toString();
Log.v(TAG,location_string);
}
}
}
}
}
MainActivity.class
package com.c7lab.fotodinamico;
import android.Manifest;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.WindowManager.LayoutParams;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity {
private static final String TAG = "MainActivity";
private Handler mainHandler = new Handler();
static MainActivity instance;
LocationRequest locationRequest;
FusedLocationProviderClient fusedLocationProviderClient;
public static MainActivity getInstance() {
return instance;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
//scheduleJob();
getWindow().addFlags(LayoutParams.FLAG_SECURE);
Dexter.withActivity(this)
.withPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
updateLocation();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
Toast.makeText(MainActivity.this, "Accetta permessi posizione.", Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
}
}).check();
}
#Override
protected void onStop() {
// call the superclass method first
super.onStop();
}
private void updateLocation() {
buildLocationRequest();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest, getPendingIntent());
}
private PendingIntent getPendingIntent() {
Intent intent = new Intent(this, com.c7lab.fotodinamico.MyLocationService.class);
intent.setAction(com.c7lab.fotodinamico.MyLocationService.ACTION_PROCESS_UPDATE);
return PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
}
private void buildLocationRequest() {
locationRequest = new LocationRequest();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(5000);
locationRequest.setFastestInterval(3000);
locationRequest.setSmallestDisplacement(10f);
}
}
I have tried multiple solutions written on this site!
A lot of issues.
1)Don't use getLastLocation. This only works if the device already knows the location. Instead, use requestSingleUpdate to actually turn on the location hardware. This required you to use a real service, as a BroadcastReceiver would be killed too quickly. The BR can start the service though.
2)You need a foreground service, not a background service.
3)IN modern android, the user can choose to grant location only when the app is open and block all background access. Possibly a device policy owner can override this, not sure. But if it can't, you're screwed.

Android Notification Listener Service starting by itself

Im trying to make an app that getting all notifications and do the task. But my problem is NotifycationListener service starting automaticly even i didnt call the start service. Its starting as soon as I allow the app notification access on my phone. So service starting somehow and I cant stop it. Im already try simple services they working correctly. But this one with the NotificationListener is really painful. I just want to start and stop this service by my command.
Service start by itself when I allow this (screenshot)
MainActivity
package com.example.alperen.nservice2;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button startB,stopB;
Intent intent;
int count=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startB=(Button)findViewById(R.id.button);
stopB=(Button)findViewById(R.id.button2);
startB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent = new Intent(MainActivity.this,MyService.class);
startService(intent);
}
});
stopB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stopService(intent);
}
});
}
}
MyService Class
package com.example.alperen.nservice2;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
public class MyService extends NotificationListenerService{
#Override
public void onCreate() {
super.onCreate();
System.out.println("********* SERVICE STARTED ***********");
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
System.out.println("***** notification *****");
String pack,title,text;
Bundle extras;
try {
pack = sbn.getPackageName();
extras = sbn.getNotification().extras;
title = extras.getString("android.title").toString();
text = extras.getCharSequence("android.text").toString();
}catch (Exception e)
{
System.out.println("**** HATA NOTIFYSERVICE CLASS ****");
pack="empty1";
title="empty1";
text="empty1";
System.out.println("**** "+pack+" ****");
}
Log.i("Package",pack);
Log.i("Title",title);
Log.i("Text",text);
Toast.makeText(this,"title: "+title+" text: "+text,Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
System.out.println("***** destroyed *****");
super.onDestroy();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.alperen.nservice2">
<uses-permission android:name="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"
tools:ignore="ProtectedPermissions" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyService"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
></service>
</application>
And the tricky part is in the Manifest. When I delete intent-filter part and run the app. It doesn't want to notification access anymore and it doesn't start by itself. I can start and stop the service from the MainActivity with buttons. But this time the app not getting the notification.
// just delete this lines
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
This is an intended behavior.
When you grant notification access permission (or restart the phone) then SYSTEM is binding to your NotificationListenerService in order to send notification data.
If you override your services onBind method and log it, you will see it's being called.

Android, Background service is not starting

I am implementing a simple application executing a background service, I am not able to start the service, following is my Manifest & Code, the service class is properly resolved ( reading resources ), inheriting from IntentService ( and implementing the req methods ) doesn't resolve the problem as-well...
Why does the Background service doesn't start?
any help will be appreciated.
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.newcomp.vagent"
android:versionCode="1"
android:versionName="1.0"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="20" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<receiver android:name="com.newcomp.Infrastructure.BootStarter" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".CaptureService"
android:exported="true"
android:process=":captureService" >
</service>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
Service code:
package com.newcomp.vagent;
import android.app.IntentService;
import android.app.Service;
import android.content.Intent;
import android.R.*;
import android.os.IBinder;
import java.io.IOException;
import fi.iki.elonen.NanoHTTPD;
public class CaptureService extends Service {
public CaptureService() {
//super("Capture Service");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
}
Activity code:
package com.newcomp.vagent;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
final String strSvcName = getResources().getString(R.string.startup_service);
//setContentView(R.layout.main);
Toast.makeText(getBaseContext(), String.format("Hello from '%s'", strSvcName), Toast.LENGTH_LONG).show();
Class cls = null;
try {
cls = getClassLoader().loadClass(strSvcName);
startService(new Intent(this, cls));// Starts the service
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//finish();
}
}
The problem was simple, the service was actually starting but since android:process=":captureService" was specified it was starting on a separate process, one that is not connected by the debugger, either specifcally connecting to the service process, OR, omitting android:process=":captureService" resolve the problem.

Parse Push "No Activity Found" on opening Push Notification

I made an app using Parse as backend. I am able to get the notification but when i tap on it, the app crashes.
Here are the java and XML files.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="chipset.lugmnotifier">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<permission
android:name="chipset.lugmnotifier.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="chipset.lugmnotifier.permission.C2D_MESSAGE" />
<application
android:name=".resources.ParseInitApplication"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<meta-data
android:name="com.parse.push.notification_icon"
android:resource="#drawable/ic_notification" />
<activity
android:name=".HomeActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".AdminActivity"
android:label="#string/title_activity_admin"
android:parentActivityName=".HomeActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".HomeActivity" />
</activity>
<service android:name="com.parse.PushService" />
<receiver android:name="com.parse.ParseBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
<receiver
android:name="com.parse.ParsePushBroadcastReceiver"
android:exported="false">
<intent-filter>
<action android:name="com.parse.push.intent.RECEIVE" />
<action android:name="com.parse.push.intent.DELETE" />
<action android:name="com.parse.push.intent.OPEN" />
</intent-filter>
</receiver>
<receiver
android:name="com.parse.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="chipset.lugmnotifier" />
</intent-filter>
</receiver>
</application>
</manifest>
ParseInitApplication.java
import android.app.Application;
import android.util.Log;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseInstallation;
import com.parse.ParsePush;
import com.parse.SaveCallback;
import static chipset.lugmnotifier.resources.Constants.APPLICATION_ID;
import static chipset.lugmnotifier.resources.Constants.CLIENT_KEY;
public class ParseInitApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
Parse.initialize(this, APPLICATION_ID, CLIENT_KEY);
ParsePush.subscribeInBackground("", new SaveCallback() {
#Override
public void done(ParseException e) {
if (e != null) {
Log.d("com.parse.push", "successfully subscribed to the broadcast channel.");
} else {
Log.e("com.parse.push", "failed to subscribe for push", e);
}
}
});
ParseInstallation.getCurrentInstallation().saveInBackground();
}
}
HomeActivity.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.method.PasswordTransformationMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import com.parse.FindCallback;
import com.parse.ParseAnalytics;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import org.duncavage.swipetorefresh.widget.SwipeRefreshLayout;
import java.util.List;
import chipset.lugmnotifier.resources.Functions;
import chipset.lugmnotifier.resources.NotificationListViewAdapter;
import de.keyboardsurfer.android.widget.crouton.Crouton;
import de.keyboardsurfer.android.widget.crouton.Style;
import static chipset.lugmnotifier.resources.Constants.KEY_CLASS_NOTIFICATION;
import static chipset.lugmnotifier.resources.Constants.KEY_DETAIL;
import static chipset.lugmnotifier.resources.Constants.KEY_TITLE;
import static chipset.lugmnotifier.resources.Constants.PASSWORD;
public class HomeActivity extends Activity {
ListView notificationsListView;
SwipeRefreshLayout notificationSwipeRefreshLayout;
Functions functions = new Functions();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ParseAnalytics.trackAppOpened(getIntent());
notificationSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.notificationSwipeRefreshLayout);
notificationsListView = (ListView) findViewById(R.id.notificationListView);
notificationSwipeRefreshLayout.setColorScheme(R.color.alizarin, R.color.emerald, R.color.peterRiver, R.color.sunFlower);
notificationSwipeRefreshLayout.setActionBarSwipeIndicatorText(R.string.swipe_to_refresh);
notificationSwipeRefreshLayout.setActionBarSwipeIndicatorRefreshingText(R.string.loading);
notificationSwipeRefreshLayout.setActionBarSwipeIndicatorBackgroundColor(
getResources().getColor(R.color.alizarin));
notificationSwipeRefreshLayout.setActionBarSwipeIndicatorTextColor(
getResources().getColor(R.color.clouds));
notificationSwipeRefreshLayout.setActionBarSwipeIndicatorRefreshingTextColor(
getResources().getColor(R.color.clouds));
notificationSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new FetchData().getNotifications();
}
});
new FetchData().getNotifications();
}
private class FetchData {
public void getNotifications() {
if (functions.isConnected(getApplicationContext())) {
notificationSwipeRefreshLayout.setRefreshing(true);
ParseQuery<ParseObject> query = ParseQuery.getQuery(KEY_CLASS_NOTIFICATION);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> parseObjects, ParseException e) {
notificationSwipeRefreshLayout.setRefreshing(false);
final String[] title = new String[parseObjects.size()];
final String[] detail = new String[parseObjects.size()];
if (e == null) {
for (int i = 0; i < parseObjects.size(); i++) {
title[i] = parseObjects.get(i).getString(KEY_TITLE);
detail[i] = parseObjects.get(i).getString(KEY_DETAIL);
}
notificationsListView.setAdapter(new NotificationListViewAdapter(getApplicationContext(), title, detail));
notificationsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Crouton.showText(HomeActivity.this, title[i] + " - " + detail[i], Style.INFO);
}
});
} else {
Crouton.showText(HomeActivity.this, e.getMessage(), Style.ALERT);
}
}
});
} else {
notificationSwipeRefreshLayout.setRefreshing(false);
Crouton.showText(HomeActivity.this, "No internet connection", Style.ALERT);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_admin) {
final EditText passwordEditText = new EditText(HomeActivity.this);
passwordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
AlertDialog.Builder builder = new AlertDialog.Builder(HomeActivity.this);
builder.setTitle("Admin Panel");
builder.setMessage("Enter the admin password");
builder.setView(passwordEditText);
builder.setPositiveButton("LOGIN", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (passwordEditText.getText().toString().equals(PASSWORD)) {
startActivity(new Intent(HomeActivity.this, AdminActivity.class));
} else {
Crouton.showText(HomeActivity.this, "Incorrect Password", Style.ALERT);
}
}
});
builder.setNeutralButton("CANCEL", null);
builder.create();
builder.show();
}
return super.onOptionsItemSelected(item);
}
}
StackTrace (of the crash)
10:46:02.302 15739-15739/chipset.lugmnotifier E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: chipset.lugmnotifier, PID: 15739
java.lang.RuntimeException: Unable to start receiver com.parse.ParsePushBroadcastReceiver: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat= flg=0x1000c000 (has extras) }
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2414)
at android.app.ActivityThread.access$1700(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1272)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat= flg=0x1000c000 (has extras) }
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1632)
at android.app.Instrumentation.execStartActivitiesAsUser(Instrumentation.java:1481)
at android.app.ContextImpl.startActivitiesAsUser(ContextImpl.java:1080)
at android.content.ContextWrapper.startActivitiesAsUser(ContextWrapper.java:344)
at android.content.ContextWrapper.startActivitiesAsUser(ContextWrapper.java:344)
at android.app.TaskStackBuilder.startActivities(TaskStackBuilder.java:221)
at android.app.TaskStackBuilder.startActivities(TaskStackBuilder.java:232)
at android.app.TaskStackBuilder.startActivities(TaskStackBuilder.java:208)
at com.parse.TaskStackBuilderHelper.startActivities(TaskStackBuilderHelper.java:19)
at com.parse.ParsePushBroadcastReceiver.onPushOpen(ParsePushBroadcastReceiver.java:202)
at com.parse.ParsePushBroadcastReceiver.onReceive(ParsePushBroadcastReceiver.java:108)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2407)
            at android.app.ActivityThread.access$1700(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1272)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5001)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)
I want to open HomeActivity on notification tap. Any help will be appreciated. If any other file is required, please let me know I'll add it.
Quoting from below post by Ahmad Raza
Exception when opening Parse push notification
You can extend ParsePushBroadcastReceiver and override onPushOpen method.
public class Receiver extends ParsePushBroadcastReceiver {
#Override
public void onPushOpen(Context context, Intent intent) {
Log.e("Push", "Clicked");
Intent i = new Intent(context, HomeActivity.class);
i.putExtras(intent.getExtras());
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
Use it in manifest, (Instead of using ParsePushBroadcastReceiver)
<receiver
android:name="your.package.name.Receiver"
android:exported="false" >
<intent-filter>
<action android:name="com.parse.push.intent.RECEIVE" />
<action android:name="com.parse.push.intent.DELETE" />
<action android:name="com.parse.push.intent.OPEN" />
</intent-filter>
</receiver>
After a long effort, it worked for me:
ParsePushApplication.java
public class ParsePushApplication extends Application {
#Override
public void onCreate(){
super.onCreate();
Parse.initialize(this, "App_Key", "Client_Key");
ParseInstallation.getCurrentInstallation().saveInBackground();
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ParseAnalytics.trackAppOpenedInBackground(getIntent());
try {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
String jsonData = extras.getString("com.parse.Data");
JSONObject json;
json = new JSONObject(jsonData);
String pushStore = json.getString("alert");
Toast.makeText(MainActivity.this, pushStore, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Receiver.java
public class Receiver extends ParsePushBroadcastReceiver {
private static final String TAG = "MyNotificationsReceiver";
#Override
public void onPushOpen(Context context, Intent intent) {
Log.e("Push", "Clicked");
Intent i = new Intent(context, MainActivity.class);
i.putExtras(intent.getExtras());
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="your.package.name">
<!-- IMPORTANT: Change "your.package.name" to match your app's package name. -->
<application
android:name=".ParsePushApplication"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.parse.push.notification_icon"
android:resource="#drawable/push_icon"/>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.parse.PushService" />
<receiver android:name="com.parse.ParseBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
<receiver
android:name="your.package.name.Receiver"
android:exported="false" >
<intent-filter>
<action android:name="com.parse.push.intent.RECEIVE" />
<action android:name="com.parse.push.intent.DELETE" />
<action android:name="com.parse.push.intent.OPEN" />
</intent-filter>
</receiver>
<receiver android:name="com.parse.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<!--
IMPORTANT: Change "your.package.name" to match your app's package name.
-->
<category android:name="your.package.name" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!--
IMPORTANT: Change "your.package.name.permission.C2D_MESSAGE" in the lines below
to match your app's package name + ".permission.C2D_MESSAGE".
-->
<permission android:protectionLevel="signature"
android:name="your.package.name.permission.C2D_MESSAGE" />
<uses-permission android:name="com.zeeroapps.parsetutorial_cli.permission.C2D_MESSAGE" />
</manifest>

Background service doesn't work

I am trying to create an Android app in Android Studio.
The app is mainly a background service to send some information to the server around every 15 seconds or so.
I have created an empty activity, boot receiver and a service class, but it doesn't work.
Could somebody help me, and explain why it doesn't work.
The relevant files:
MainActivity.java
package nl.robinvandervliet.robinsapp.app;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
public class MainActivity extends ActionBarActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
finish();
}
}
BootReceiver.java
package nl.robinvandervliet.robinsapp.app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BootReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
context.startService(new Intent(context, RobinsService.class));
}
}
RobinsService.java
package nl.robinvandervliet.robinsapp.app;
import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class RobinsService extends Service
{
private Runnable runnable = new Runnable()
{
#Override
public void run()
{
//Opening connection to the server.
while (true)
{
//Sending some data to the server.
//Sleeping for around 15 seconds.
}
//Dead code, should never reach this place.
}
};
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onCreate()
{
new Thread(runnable).start();
Notification notification = new Notification.Builder(getApplicationContext()).setContentTitle("MyService is running!").setContentTitle("(more information later)").build();
startForeground(1, notification);
Toast.makeText(getApplicationContext(), "Service created!", Toast.LENGTH_LONG).show();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="nl.robinvandervliet.robinsapp.app" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="nl.robinvandervliet.robinsapp.app.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>
<receiver android:name="nl.robinvandervliet.robinsapp.app.BootReceiver" android:enabled="true" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name="nl.robinvandervliet.robinsapp.app.RobinsService" android:exported="false" />
</application>
<uses-permission android:name="android.permission.BATTERY_STATS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
</manifest>
Thanks, Robin.
Since you haven't implemented some parts yet I assume you just want it to run when you boot your device. Maybe take a look here. Adding an extra action in the manifest might solve your problem.

Categories