Android Unable to instantiate activity: Didn't find class on path - java

I've imported project into eclipse and when I try to run it, then this exception is thrown:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.polygraf/com.polygraf.activity.Dashboard}: java.lang.ClassNotFoundException: Didn't find class "com.polygraf.activity.Dashboard" on path: /data/app/com.polygraf-1.apk
I've tried to clean the project, then check if all class names and manifest are ok, but still can't find why this happens. Can you help me a little please?
Dashbard class:
public class Dashboard extends FragmentActivity {
private static final String WELCOME_TYPE = "WELCOME_TYPE";
private static final String HELP_TYPE = "HELP_TYPE";
public static final String ADRESS_CONTENT = "ADRESS_CONTENT";
public static final String DOC_NAME = "DOC_NAME";
private Transcript mContent;
private ISettableContent mListOfDocument;
private String mAddress;
private String mDocName;
public Dashboard() {
}
/** Called with the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
boolean content = false;
// View gc = (NoSaveStateFrameLayout)
// findViewById(R.id.content_fragment);
//
Fragment frContent = getSupportFragmentManager().findFragmentById(R.id.content_fragment);
mContent = ((IGetContent) frContent).getContent();
TranscriptSetting cc = Polygraf.getInstance().getContentSetting();
Fragment frDocumentsList = getSupportFragmentManager().findFragmentById(R.id.documents);
mListOfDocument = (ISettableContent) frDocumentsList;
cc.registerContent(mListOfDocument);
if (getIntent().hasExtra(ADRESS_CONTENT)) {
mAddress = getIntent().getStringExtra(ADRESS_CONTENT);
mDocName = getIntent().getStringExtra(DOC_NAME);
mContent.setAddress(mAddress, mDocName);
content = true;
} else if (getIntent().hasExtra(WELCOME_TYPE)) {
content = true;
prepareVisibilityBtnTranscript();
} else if (getIntent().hasExtra(HELP_TYPE)) {
content = true;
mContent.showHelp();
}
if (content) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.hide(frDocumentsList);
ft.commit();
// because on diferent layouts for small and large device
// some views missing, so the test is inportant
View contentLayout = findViewById(R.id.contentLayout);
if (contentLayout != null) {
contentLayout.setVisibility(View.VISIBLE);
}
prepareVisibilityBtnWelcome();
// cp.setContent(mContent);
}
cc.registerContent(mContent);
// cp.setListener(cc);
}
.
.
.
}
And manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="17" />
<application
android:name=".Polygraf"
android:allowBackup="true"
android:hardwareAccelerated="true"
android:icon="#drawable/icon"
android:label="#string/skeleton_app"
android:theme="#android:style/Theme.Black.NoTitleBar" >
<activity
android:name="com.polygraf.activity.Dashboard"
android:configChanges="orientation|keyboard" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<!-- This places this activity into the main app list. -->
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.polygraf.activity.SettingActivity"
android:label="#string/skeleton_app" />
<activity
android:name="com.polygraf.activity.ContentActivity"
android:label="#string/skeleton_app" >
</activity>
<activity
android:name="com.polygraf.activity.PlayVideo"
android:configChanges="orientation|keyboard"
android:label="#string/skeleton_app" />
</application>

I suppose you're using Eclipse. Your activity is there alright, but Eclipse didn't include the support package in the APK ... If you look above your error in stacktrace you will notice the root of your problem: "Unable to find FragmentActivity". Or you can unpack the apk, undex it and you will see the compatibility package classes were not included.
To fix this, right-click your project, properties, build path and go to export tab. There make sure "Android private libraries" are checked. A clean and rebuild should put you on track ...

After i spend a while on this problem, the solution that i found is a conflict between importing Properties > Android - appcompat_v7 and appcompat_v4 that was added in the libs folder. After i remove the appcompat_v4 the error no longer appear.
I hope that answer can help in the future someone.

You should import new appcompat_v7 from sdk and use it as a built path,it works for me.

Related

Android- Sending MMS Programmatically Without Being Default App

The MMS portion of the Android SDK is largely not exposed, and consequently there is really one main 3rd party library that helps out with this. The sample project included in the library will not send MMS, however, a fork of the project does.
When I download the latter project, I can run the sample and send an MMS without having to set the application as the default application. However, when I integrate the code into my own application MMS will only send if I make my app the default messaging app. I have read that Android 4.4+ does not support MMS without being a default app, but why is it that the sample project I'm deriving my code from works without being default? The only difference I really notice is that the minimum SDK is 14 versus my project which is 18.
Here is the main code from my project:
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hacknow2">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.RECEIVE_MMS" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.provider.Telephony.SMS_RECEIVED" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:name=".init.App"
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=".phase1.PermissionsActivity"/>
<activity android:name=".phase2.youtube.YoutubeActivity" />
<activity android:name=".phase2.posting.PostingActivity" />
<activity
android:name=".phase2.ui.main.SelectionActivity"
android:label="#string/title_activity_selection"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.SEND" />
<action android:name="android.intent.action.SENDTO" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="sms" />
<data android:scheme="smsto" />
<data android:scheme="mms" />
<data android:scheme="mmsto" />
</intent-filter>
</activity>
<activity android:name=".phase1.OpeningActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".phase3.mms.KitSmsSentReceiver"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_DELIVER" />
</intent-filter>
</receiver>
<receiver
android:name=".phase3.mms.KitMmsSentReceiver"
android:permission="android.permission.BROADCAST_WAP_PUSH">
<intent-filter>
<action android:name="android.provider.Telephony.WAP_PUSH_DELIVER" />
<data android:mimeType="application/vnd.wap.mms-message" />
</intent-filter>
</receiver>
<receiver
android:name="com.klinker.android.send_message.MmsSentReceiver"
android:taskAffinity="com.klinker.android.messaging.MMS_SENT" />
<receiver
android:name="com.klinker.android.send_message.MmsReceivedReceiver"
android:taskAffinity="com.klinker.android.messaging.MMS_RECEIVED" />
<service android:name="com.android.mms.transaction.TransactionService" />
<service
android:name=".phase3.mms.HeadlessSmsSendService"
android:exported="true"
android:permission="android.permission.SEND_RESPOND_VIA_MESSAGE">
<intent-filter>
<action android:name="android.intent.action.RESPOND_VIA_MESSAGE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="sms" />
<data android:scheme="smsto" />
<data android:scheme="mms" />
<data android:scheme="mmsto" />
</intent-filter>
</service>
</application>
</manifest>
MMSManager, singleton that manages sending MMS
public class MMSManager {
private static final String TAG = "MMSManager";
private static ThreadPoolExecutor mThreadManager;
private static MMSManager INSTANCE;
private static BlockingQueue<Runnable> decodeWorkQueue;
private static int NUMBER_OF_CORES =
Runtime.getRuntime().availableProcessors();
private Settings mSettings;
private Context mContext;
private MMSManager(Context c) {
mContext = c;
initSettings();
initLogging();
// A queue of Runnables
decodeWorkQueue = new LinkedBlockingQueue<Runnable>();
// setting the thread factory
mThreadManager = new ThreadPoolExecutor(NUMBER_OF_CORES, NUMBER_OF_CORES,
50, TimeUnit.MILLISECONDS, decodeWorkQueue);
BroadcastUtils.sendExplicitBroadcast(c, new Intent(), "test action");
}
//See https://stackoverflow.com/questions/14057273/android-singleton-with-global-context
private static synchronized MMSManager getSync() {
if (INSTANCE == null) INSTANCE = new MMSManager(App.get());
return INSTANCE;
}
public static MMSManager getInstance(Context c) {
if (INSTANCE == null) {
INSTANCE = getSync();
}
return INSTANCE;
}
private void initSettings() {
mSettings = Settings.get(mContext);
if (TextUtils.isEmpty(mSettings.getMmsc()) &&
Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
initApns();
}
}
private void initApns() {
ApnUtils.initDefaultApns(mContext, new ApnUtils.OnApnFinishedListener() {
#Override
public void onFinished() {
mSettings = Settings.get(mContext, true);
}
});
}
private void initLogging() {
com.klinker.android.logger.Log.setDebug(true);
com.klinker.android.logger.Log.setPath("messenger_log.txt");
com.klinker.android.logger.Log.setLogListener(new OnLogListener() {
#Override
public void onLogged(String tag, String message) {
//logAdapter.addItem(tag + ": " + message);
android.util.Log.d("MMS_Manager " + tag, "onLogged: " + message);
}
});
}
//Not sure what exception might pop up but it's being handled anyway...
public void sendMMS(String phoneNumber, Bitmap bm) {
mThreadManager.execute(new Runnable() {
#Override
public void run() {
Log.d("ThreadPool/MMSManager", "Trying to send MMS.");
com.klinker.android.send_message.Settings sendSettings = new com.klinker.android.send_message.Settings();
sendSettings.setMmsc(mSettings.getMmsc());
sendSettings.setProxy(mSettings.getMmsProxy());
sendSettings.setPort(mSettings.getMmsPort());
sendSettings.setUseSystemSending(true);
Transaction transaction = new Transaction(mContext, sendSettings);
Message message = new Message(null, phoneNumber);
if (bm != null)
message.setImage(bm);
transaction.sendNewMessage(message, Transaction.NO_THREAD_ID);
}
});
}
}
The fragment that calls MMSManager methods, located in its parent, SelectionActivity:
public class SendDialog extends DialogFragment {
private static final int MY_PERMISSIONS_REQUEST_SEND_SMS = 1000;
private ArrayList<String> mPhoneNumbers;
private DMessage mMessage;
private OnFinished mCompletionListener;
private MMSManager mMMSManager;
private Bitmap mBitmap;
private static String[] mMediaTypes;
public SendDialog(ArrayList<String> phoneNumbers, DMessage m, OnFinished listener){
mPhoneNumbers = phoneNumbers;
mMessage = m;
mCompletionListener = listener;
}
public SendDialog(ArrayList<String> phoneNumbers, DMessage m, Bitmap b, OnFinished listener){
mPhoneNumbers = phoneNumbers;
mMessage = m;
mCompletionListener = listener;
mBitmap = b;
}
public interface OnFinished{
void complete(boolean success);
}
private String getCautionMessage(){
int numContacts = 0;
if(mPhoneNumbers!=null && mPhoneNumbers.size()>0) {
for (String number :
mPhoneNumbers) {
numContacts++;
}
}
return "Are you sure you'd like to send the highlighted post to " + numContacts + " people?";
}
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
mMediaTypes = getResources().getStringArray(R.array.postoptions);
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(getCautionMessage())
.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
sendBulkTexts();
dismiss();
}
})
.setNegativeButton(R.string.Cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mCompletionListener.complete(false);
}
});
// Create the AlertDialog object and return it
return builder.create();
}
private boolean isMMS(){
return mMessage.getMediaType().equals(mMediaTypes[2]);//mediaTypes[2] == "Image"
}
/**
* Converts phone number to only numbers.
* I.e. (XXX)-XXX-XXXX to XXXXXXXXXX
*/
private static String phoneNumberFormatter(String unformatted) {
return unformatted.replaceAll("\\D+", "");
}
private void sendBulkTexts(){
for (String number :
mPhoneNumbers) {
try {
String formattedNumber = phoneNumberFormatter(number);
if(!isMMS()) {
//Send a Youtube video or text
sendSMS(formattedNumber, mMessage.getBody());
}
else{
if(mMMSManager==null)//instantiate MMSManager and load bitmap
mMMSManager = MMSManager.getInstance(getActivity());
if(mBitmap!=null)
mMMSManager.sendMMS(formattedNumber, mBitmap);
}
}
catch(Exception e){
Toast.makeText(getActivity(), "Could not send text to " + number + ".", Toast.LENGTH_LONG).show();
Log.e("SendDialog", "sendBulkTexts: ", e);
mCompletionListener.complete(false);
}
}
Toast.makeText(getActivity(), "Finished sending texts.", Toast.LENGTH_LONG).show();
mCompletionListener.complete(true);
}
private void sendSMS(String phoneNumber, String message) throws Exception{
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null, null);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
sendBulkTexts();
} else {
Toast.makeText(getActivity(),
"Permission for sending SMSs denied.", Toast.LENGTH_LONG).show();
mCompletionListener.complete(false);
return;
}
}
}
}
}
I added following lines after message is declared and it seems to work.
message.setFromAddress(Utils.getMyPhoneNumber(mContext));
message.setSave(false);
Uri uri = Uri.parse("content://mms-sms/conversations/");
message.setMessageUri(uri);
I'm not sure what the fork is doing but I suspect it is not using the system messaging libraries but using the Klinker libraries to send the message. That's what's allowing it to send messages without setting the app as default.
To get it to work without system libraries, you need to setSave as false. Then you need to provide a URI for it to work. The FromAddress may or may not be needed.
I have found the answer.
Apparently, in 2019 Google changed their rules such that you cannot add an app to the Google Play store that sends SMS/MMS directly from your app if it is not the default messaging app without some sort of strong justification. All you are allowed to do is create an intent with your SMS and MMS and pass it to the Android OS to use your default messaging app.
My recommendation is to avoid trying to write SMS/MMS using native APIs (unless you are absolutely confident you are a rare exception to Google Play's terms) and use a third-party service like Twilio to handle this for you.

Google Maps, Map is loading, but not completely

I have a problem with my Android Studio app using Google Maps, the problem being that my map doesn't completely load. I do get the fully loaded world map, but that's as far as it goes.
The functionality of the app itself works great, I am able to type in whatever country/city/address that I want, and stick a marker to that location (Which in my simple mind tells me that I have all the permissions that I require to utilize the functions I want for this application).
I have been browsing for solutions for hours, but everything I have found, I already have enabled and/or working. I use my Samsung Galaxy S7 phone to run my app and have had no problems so far with Android Studio.
I guess this is just a "cosmetic" issue, but still one I would like to solve.
What I have tried:
Clearing the cache on my device of, Google Play Services, Google Play Store
Getting new API keys from google
Different map layouts MAP_TYPE_NORMAL, MAP_TYPE_HYBRID <- The hyrbid layout does not load at all.
My internet connection, Wifi/Wireless (I have a fast internet connection using either, I doubt that's the problem)
Pictures to better describe what happens:
Starting the app with custom markers.
Zooming in.
Final zoom, with markers in the correct spot.
My code:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
EditText searchText;
public GoogleMap mMap;
private static final float DEFAULT_ZOOM = 15.0f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
try {
if (mMap == null) {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
} catch (Exception e) {
e.printStackTrace();
}
searchText = (EditText) findViewById(R.id.input_search);
init();
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
Toast.makeText(this, "Map is ready", Toast.LENGTH_SHORT).show();
}
//init the search
public void init()
{
searchText.setOnEditorActionListener(new TextView.OnEditorActionListener()
{
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
{
if(actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE)
{
geoLocate();
}
return false;
}
});
}
private void geoLocate()
{
String searchString = searchText.getText().toString();
Geocoder geocoder = new Geocoder(MapsActivity.this);
List<Address> list = new ArrayList<>();
try
{
list = geocoder.getFromLocationName(searchString, 1);
}
catch(Exception e)
{
e.printStackTrace();
}
if(list.size() > 0)
{
Address address = list.get(0);
LatLng position = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(position).title(searchText.getText().toString()));
mMap.moveCamera(CameraUpdateFactory.newLatLng(position));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(position, DEFAULT_ZOOM));
}
}
}
My AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<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">
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<!--android:value="#string/google_maps_key" />-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="*Api*" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
My google_maps_api.xml file:
<resources>
<string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">*Api*</string>
</resources>
I obviously discluded the API_KEY's with Api.
This is my first post on stackoverflow so any feedback regarding the quality of my post is welcome as well.
Can you confirm that you have setup you Android Google Maps SDK API Key in the google developer console, If not then please Enable Google Maps Android API in google developer console with your application identifier and SHA1 fingerprint? The map won't show until the key is authorised for the particular debug/production build of your app.

GCM Android 4.0.4 cant get message

I followed the example from developers.google.com and create simple services for retrieve Token and messages from GCM.
Class for token receive
public class RegistrationIntentService extends IntentService {
private static final String TAG = "RegIntentService";
private static final String[] TOPICS = {"global"};
private String projectNumber = "gcm-test-xxxxx";
public RegistrationIntentService() {
super(TAG);
}
#Override
protected void onHandleIntent(Intent intent) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
try {
InstanceID instanceID = InstanceID.getInstance(this);
String token = instanceID.getToken(projectNumber,
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
sendRegistrationToServer(token);
subscribeTopics(token);
sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply();
} catch (IOException e) {
Log.d(TAG, "Failed to complete token refresh", e);
sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false).apply();
}
Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE);
LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
private void subscribeTopics(String token) {
}
private void sendRegistrationToServer(String token) throws IOException {
GcmPubSub pubSub = GcmPubSub.getInstance(this);
for (String topic : TOPICS) {
pubSub.subscribe(token, "/topics/" + topic, null);
}
}
}
This class works fine, I can retrieve token and do what i want with it.
I am starting this class as a service from MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, RegistrationIntentService.class));
}
}
Also i have class for retrieving messages from GCM. This class don't work at all.
public class MyGcmListenerService extends GcmListenerService {
String TAG = "MyGcmListenerService";
#Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
Log.d(TAG, "From: " + from);
Log.d(TAG, "Message: " + message);
}
}
All this stuff was registered in manifest.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="gcm_test.app">
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/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="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="gcm_test.app" />
</intent-filter>
</receiver>
<service
android:name=".gcm.MyGcmListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE"/>
</intent-filter>
</service>
<service
android:name=".gcm.RegistrationIntentService"
android:exported="false">
</service>
</application>
</manifest>
I send messages with postman.
POST https://android.googleapis.com/gcm/send
headers
Content-Type:application/json
Authorization:key= keyFromGoogleDevelopersConsole
{
"to" : "/topics/global",
"data":{
"message": "Hello world!!!"
}
}
After send I receive 200 OK and message ID, but phone did not receive any messages.
What I am doing is wrong? How receive my messages?
I have changed SenderID to numbers from Developers Console but it did not help me. Aslo I have noticed Errors in debug console:
11-21 17:32:58.014 31813-31813/gcm_test.app E/dalvikvm﹕ Could not find class 'android.app.Notification$BigTextStyle', referenced from method com.google.android.gms.common.GooglePlayServicesUtil.zza
11-21 17:32:58.024 31813-31813/gcm_test.app E/dalvikvm﹕ Could not find class 'android.os.UserManager', referenced from method com.google.android.gms.common.GooglePlayServicesUtil.zzap
11-21 17:32:58.027 31813-31813/gcm_test.app E/dalvikvm﹕ Could not find class 'android.app.AppOpsManager', referenced from method com.google.android.gms.common.GooglePlayServicesUtil.zzb
I thought this service that retrives the messages need somehow register or start. But when I run it like simple service it crashes.
It looks like you are not registering with the correct Sender ID. The documentation explains that the Sender ID is the numerical Project Number listed at the Google Developers Console for your app's project. The string you are using for Sender ID, gcm-test-xxxxx, looks like the Project ID.
On the Dashboard page at the Developers Console, your project data will include a line like this:
ID: jade-segment-123 (#123123123123)
For this example, the Sender ID is 123123123123.
Update:
Note also that you are not using the URL shown in the documentation:
https://gcm-http.googleapis.com/gcm/send

Application Class Null Pointer Exception

I am creating an Android app and wish to store a variable in the Application class. The variable signifies which Activity is currently in focus.
I aim to set this variable in onResume() and reset it in onPause(). Both methods are called as the app initialises. The software crashes on the basis of a Null Pointer Excepetion whenever I run my code, at lines where I try to modify the variable in the Application class. As far as I am aware, it appears to me as though the Application class is null even though I have tested the code and know it call the Application class' onCreate().
Am I correct in assuming it is connected to the Application Class not being completely created? Or is it connected to my instantiation of it all? I'm reasonably new to Android and haven't dealt with the Application class before - as far as I can see, I've followed the guides and tutorials correctly. I'm hoping it's a simple mistake.
Any and all advice is greatly appreciated!
MainActivity.java
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
//[... other initialisations...]
// Tells software what window is in focus.
// Reference to Application class
private MyApplicationClass app = (MyApplicationClass)getApplication();
private static final int outOfFocus = 0;
private static final int inFocus = 1;
#Override
protected void onResume() {
super.onResume();
//[... other code...]
app.setActivityFocusIndicator(inFocus); //Crashes here
}
#Override
protected void onPause() {
super.onPause();
//[... other code...]
app.setActivityFocusIndicator(outOfFocus); //Crashes here
}
}
MyApplicationClass.java
public class MyApplicationClass extends Application {
private int activityFocusIndicator;
/* activityFocusIndicator is here to indicate which activity is in focus.
* 0 = Nothing in focus (written when pausing.)
* 1 = MainActivity
* 2 = ...
* ...
*/
public void setActivityFocusIndicator(int activityFocusIndicator) {
this.activityFocusIndicator = activityFocusIndicator;
}
public int getActivityFocusIndicator() {
return activityFocusIndicator;
}
#Override
public void onCreate() {
super.onCreate();
Log.d("App", "App was created."); // This line is reached.
}
}
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.someApp"
android:versionCode="1"
android:versionName="1.0" >
<uses-feature android:name="android.hardware.bluetooth_le"
android:required="true"/>
<uses-sdk
android:minSdkVersion="18"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/TabTheme"
android:name="com.example.someName.MyApplicationClass" >
<activity
android:name="com.example.someName.MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:launchMode="singleInstance" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
...
</activity>
<!-- ... [other activities declared]... -->
<service
android:name=".BluetoothService"/>
</application>
</manifest>
I can post the LogCat if asked.
I don't see the point of this line :
private MyApplicationClass app = (MyApplicationClass)getApplication();
This variable is probably initialized before the reference returned by getApplication() is initialized, and therefore remains null.
Instead of using it, replace each acess to app with a local variable.
For example:
protected void onResume() {
super.onResume();
//[... other code...]
MyApplicationClass app = (MyApplicationClass)getApplication();
app.setActivityFocusIndicator(inFocus);
}

getGSMSignalStrength() Always Returns 99

I know there is another question on here relating to this, but I don't think it applies to me, as I'm pretty sure I use GSM (isGSM() returns true). In any case, getCdmaDbm returns -1 for me anyway. I am using Android 4.1.1 and an HTC One X. Here is my code (most of which isn't mine):
MainActivity:
package com.example.receptionlookup;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends Activity {
TelephonyManager Tel;
MyPhoneStateListener MyListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Update the listener, and start it */
MyListener = new MyPhoneStateListener();
Tel = ( TelephonyManager )getSystemService(Context.TELEPHONY_SERVICE);
Tel.listen(MyListener ,PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/* Called when the application is minimized */
#Override
protected void onPause()
{
super.onPause();
Tel.listen(MyListener, PhoneStateListener.LISTEN_NONE);
}
/* Called when the application resumes */
#Override
protected void onResume()
{
super.onResume();
Tel.listen(MyListener,PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
}
/* —————————– */
/* Start the PhoneState listener */
/* —————————– */
private class MyPhoneStateListener extends PhoneStateListener
{
/* Get the Signal strength from the provider, each tiome there is an update */
#Override
public void onSignalStrengthsChanged(SignalStrength signalStrength)
{
super.onSignalStrengthsChanged(signalStrength);
Toast.makeText(getApplicationContext(), "Go to Firstdroid!!! GSM Cinr = "
+ String.valueOf(signalStrength.getGsmSignalStrength()), Toast.LENGTH_SHORT).show();
}
};/* End of private Class */
}
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.receptionlookup"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.receptionlookup.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
</manifest>
Does anyone know what the problem is? If I go to Settings->About->Network, I can see the signal strength there. Isn't there some way to just read this value? I've tried several third party apps, and none of them are able to read my signal strength either. I've also tried the proprietary getGSMSignalBar() method, but I get a NoSuchMethodException.
As you can read in the 3GPP 127 007 8.5 the implementation of the at+csq is optional (the command which suppose to give the signal strength). Apparently HTC hide this value from 3rd party applications and they probably have another way to achieve that value for display in their own proprietary Settings application.
The fact that other applications also cannot get that information justifies my case.
This issue is tightly related to yours - thay said that HTC is one of the OEMs that does not worth the modem related developing time.
Try this:
Class signalStrengthClass = signalStrength.getClass();
try {
Method method = signalStrengthClass.getMethod(
"getGsmSignalBar", null);
method.setAccessible(true);
Integer bars = (Integer) method.invoke(signalStrength,
(Object[]) null);
}
} catch (Exception e) {
e.printStackTrace();
}

Categories