BroadcastReceiver using 1 time - java

Good evening, I have a simple program that activates the BroadcastReceiver to detect the number when I receive a call, the problem is that when I get the call, will write again in my database, and when I disconnect the call records again, summing writes 3 ​​times! and I only want 1, when it is playing!
Another problem is when the phone is ringing, writes logo in the database, (here is okay!) But it does not answer the call, it writes the call again!
the code is this:
my broadcast: its works!
public class MyBroadcastReceiver extends BroadcastReceiver {
String idtelemovel="1";
String phone_number;
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("Entrou no BroadCastReceiver!!! : ");
Bundle bundle = intent.getExtras();
phone_number = bundle.getString("incoming_number");
System.out.println("Phone Number : " + phone_number);
Log.i("zz", "Phone Number : " + phone_number);
new SummaryAsyncTask().execute((Void) null);
}
class SummaryAsyncTask extends AsyncTask<Void, Void, Boolean> {
private void postData(String phone_number) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.AAA.com/insert.php");
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("Street", phone_number));
nameValuePairs.add(new BasicNameValuePair("House", idtelemovel));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}
catch(Exception e)
{
Log.e("log_tag", "Error: "+e.toString());
System.out.print("*********fail*********");
}
}
#Override
protected Boolean doInBackground(Void... params) {
postData(phone_number);
return null;
}
}
}
Manifest:
<uses-sdk
android:minSdkVersion="18"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<receiver android:name=".MyBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
<activity
android:name="com.example.a.BroadcastReceiver"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity><service android:name=".MyServices" />
</application>
</manifest>

The broadcast intent also includes the call state (idle, ringing, offhook). You can read it with the key Telephony.EXTRA_STATE, then compare it with the possible values. For example:
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (TelephonyManager.EXTRA_STATE_RINGING.equals(state))
{
String phoneNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
// call your asynctask ...
}

Related

Can't read SMS on android

I can't seem to get a basic sms reading app to work on android. Not sure what am I missing here. I think I have all the basic minimum specified in the code, despite that it seems to be not working. The onReceive() of SmsReceiver is never invoked. All the required permissions are set.
Here are my files.
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//...
//...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestReadAndSendSmsPermission();
smsReceiver = new SmsReceiver() {
#Override
protected void onData(String data) {
//handle
}
};
IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
//intentFilter.setPriority(999);
registerReceiver(smsReceiver, intentFilter);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(smsReceiver);
}
private void requestReadAndSendSmsPermission() {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_SMS},1);
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.RECEIVE_SMS},1);
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.SEND_RESPOND_VIA_MESSAGE}, 1);
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.SEND_SMS}, 1);
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_NETWORK_STATE}, 1);
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CHANGE_NETWORK_STATE}, 1);
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.INTERNET}, 1);
}
//...
//...
}
SmsReceiver.java
public abstract class SmsReceiver extends BroadcastReceiver {
private static final String TAG = "SmsReceiver";
#Override
public void onReceive(Context context, Intent intent) {
if (context == null || intent == null) {
return;
}
String action = intent.getAction();
if (!action.equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) {
return;
}
//read sms
onData("sms received");
}
protected abstract void onData(String data);
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mysmsapp">
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.SEND_RESPOND_VIA_MESSAGE_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_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/Theme.MySMSApp">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
You are missing defining the receiver entry in AndroidManifest.xml file for your BroadcastReceiver named SmsReceiver please make the entry for it else OS will not know if you have a broadcast receiver waiting to be triggered.
Depending upon what is your use case it might be something like
<receiver
android:name=".SmsReceiver"
android:exported="true"
android:permission="com.google.android.gms.auth.api.phone.permission.SEND">
<intent-filter>
<action android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVED"/>
</intent-filter>
</receiver>
Or
<receiver
android:name=". SmsReceiver"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
Note: These receiver are sample receiver please use the correct one as per your use case, the main point is you are missing receiver entry in your manifest file
i use this code to read incoming message
public class SmsReceiver extends BroadcastReceiver {
private static final Uri smsuri = Apconsts.smsuri;
private static final String pdu_type = "pdus";
#Override
public void onReceive(Context context, Intent intent){
// Get the SMS message.
Bundle bundle = intent.getExtras();
SmsMessage[] msgs;
String format = bundle.getString("format");
// Retrieve the SMS message received.
Object[] pdus = (Object[]) bundle.get(pdu_type);
String body="";String adrs="";
if (pdus != null) {
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++){
if(Build.VERSION.SDK_INT < 23){ msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); }
else{ msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i], format); }
adrs=msgs[i].getOriginatingAddress();
body += ""+msgs[i].getMessageBody();
}
Toast.makeText(getApplicationContext(), "The message Body: "+body+"\nThe address: "+adrs, Toast.LENGTH_LONG).show();
}
}
}
and this receiver in manifest
<receiver android:name=".SmsReceiver"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>

Why Messages not received from gcm

I tried to register my device into GCM service.
that's worked, I get register id of my device and store that on my server.
but when I send message to my device nothing affected and device can not recive message.
Response on google at send message:
{u'failure': 0, u'canonical_ids': 0, u'success': 1, u'multicast_id': 8319562714448073760L, u'results': [{u'message_id': u'0:1445751667241995%f044e3acf9fd7ecd'}]}
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ir.ac.buqaen.rc"
android:versionCode="5"
android:versionName="1.4">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="23"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.VIBRATE"/>
<permission
android:name="ir.ac.buqaen.rc.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="ir.ac.buqaen.rc.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<application
android:name=".network.AppController"
android:label="#string/app_name"
android:icon="#drawable/icon"
android:theme="#style/Theme.Main"
android:allowBackup="true">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:configChanges="keyboardHidden|orientation|screenSize"/>
<activity
android:name=".SplashActivity"
android:label="#string/app_name"
android:theme="#style/Theme.AppCompat.Light.NoActionBar.FullScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".gcm.MessageActivity"/>
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<!-- Receives the registration id. -->
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="ir.ac.buqaen.rc" />
</intent-filter>
</receiver>
<service android:name=".GCMIntentService" />
</application>
</manifest>
ServerUtilities.java
public final class ServerUtilities {
private static final String TAG = "GCM";
public static void register(final Context context, final String regId){
final MySharedPreferences sp = new MySharedPreferences(context);
long teacher_id = sp.sharedPreferences.getLong("teacher_id", -1);
TeacherHelper teacherHelper = new TeacherHelper(context);
teacherHelper.teacher = teacherHelper.findById(teacher_id);
Map<String, String> params = new HashMap<String, String>();
Log.d("regid", "---- regId:" + regId);
params.put("reg_id", regId);
params.put("name", teacherHelper.teacher.getStringName());
params.put("email", teacherHelper.teacher.getStringEmail());
params.put("user_id", teacherHelper.teacher.getStringUsername());
params.put("device_id", Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID));
CustomRequest request = new CustomRequest(context, Globals.UrlGCMRegister, params, new CustomRequest.ResponseAction() {
#Override
public void onResponseAction(JSONObject data) throws JSONException {
try {
int vc = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
if (data.getBoolean("status")) {
sp.saveToPreferences("gcm" + vc, data.getJSONObject("value").getString("id"));
sp.saveToPreferences("gcm_reg_id", regId);
GCMRegistrar.setRegisteredOnServer(context, true);
} else if (data.getString("msg").equals("already registered")) {
sp.saveToPreferences("gcm" + vc, data.getJSONObject("value").getString("id"));
GCMRegistrar.setRegisteredOnServer(context, true);
sp.saveToPreferences("gcm_reg_id", regId);
} else {
Log.e(TAG, "registering device failed");
}
} catch (JSONException e) {
Log.e("Response Error _ " + context.getClass().getSimpleName(), "----" + e.getMessage());
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
});
AppController.getInstance().addToRequestQueue(request, "request gcm");
}
/**
* Unregister this account/device pair within the server.
*/
public static void unregister(final Context context, final String regId) {
final MySharedPreferences sp = new MySharedPreferences(context);
Map<String, String> params = new HashMap<String, String>();
params.put("reg_id", regId);
CustomRequest request = new CustomRequest(context, Globals.UrlGCMUnRegister, params, new CustomRequest.ResponseAction() {
#Override
public void onResponseAction(JSONObject data) throws JSONException {
if (data.getBoolean("status")) {
int vc = 1;
try {
vc = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
sp.editor.remove("gcm" + vc);
sp.editor.remove("gcm_reg_id");
sp.editor.commit();
GCMRegistrar.setRegisteredOnServer(context, false);
}
}
});
AppController.getInstance().addToRequestQueue(request, "request gcm");
}
}
GCMIntentService.java
public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GCMIntentService";
public GCMIntentService() {
super(Globals.SENDER_ID);
}
#Override
protected void onRegistered(Context context, String registrationId) {
ServerUtilities.register(context, registrationId);
}
#Override
protected void onUnregistered(Context context, String registrationId) {
ServerUtilities.unregister(context, registrationId);
}
#Override
protected void onMessage(Context context, Intent intent) {
Log.i("tes", "~~~" + intent.getExtras());
Log.i(TAG, "Received message");
MessageHelper messageHelper = new MessageHelper(context);
try {
JSONObject data = new JSONObject(intent.getExtras().getString("message"));
messageHelper.message = new Message(
null, data.getInt("type"), data.getInt("status"), data.getString("content"),
data.getString("title"), data.getString("date")
);
messageHelper.Save();
createNotification(context, messageHelper.message);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(Context context, String errorId) {
Log.i(TAG, "Received error: " + errorId);
}
#Override
protected boolean onRecoverableError(Context context, String errorId) {
Log.i(TAG, "Received recoverable error: " + errorId);
return super.onRecoverableError(context, errorId);
}
private void createNotification(Context context, Message message) {
Intent notificationIntent;
notificationIntent = new Intent(this, Message.class);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationIntent.putExtra("message_id", message.id);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, message.id.intValue(), notificationIntent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.bu_logo)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.bu_logo))
.setTicker(getString(R.string.new_message))
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setSound(Uri.parse("android.resource://ir.ac.buqaen.rc/raw/notification"))
.setContentTitle(message.title)
.setContentText(message.getContentText(context));
Notification notification = builder.build();
notificationManager.notify(message.id.intValue(), notification);
}
}
MainActivity
try {
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(getApplicationContext());
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(getApplicationContext());
// Get GCM registration id
final String regId = GCMRegistrar.getRegistrationId(getApplicationContext());
// Check if regid already presents
if (regId.equals("")) {
// Registration is not present, register now with GCM
GCMRegistrar.register(getApplicationContext(), Globals.SENDER_ID);
} else {
// Try to register again if device is not registered on GCM
if (!GCMRegistrar.isRegisteredOnServer(getApplicationContext())) {
ServerUtilities.register(getApplicationContext(), regId);
}
}
} catch (Exception e) {
e.printStackTrace();
}
I dont khow why this code not worked! I use this code in another project and get messages on my app, but this code in this application on receive messages.
Can problem from my package name? :)
ir.ac.buqaen.rc
Please help me hoe to fix this problem.
According to Set up a GCM Client App on Android
For existing apps that extend a WakefulBroadcastReceiver, Google
recommends migrating to GCMReceiver and GcmListenerService. To
migrate:
In the app manifest, replace your GcmBroadcastReceiver with "com.google.android.gms.gcm.GcmReceiver", and replace the current
service declaration that extends IntentService to the new
GcmListenerService
Remove the BroadcastReceiver implementation from your client code
Refactor the current IntentService service implementation to use GcmListenerService
Then, you can refer to my following manifest file. Hope this helps!
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gcmclient" >
<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="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="com.example.gcm.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<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.REGISTRATION" />
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.example.gcm" />
</intent-filter>
</receiver>
<service android:name=".service.GcmService" android:exported="false">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<service android:name=".service.LoggingService" android:exported="false" />
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:clearTaskOnLaunch="false"
android:finishOnTaskLaunch="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

NoClassFound com.google.android.gms.gcm.GcmReceiver on Nexus 5->Android 5.1.1

I am trying to modify and implement GCM (hmkode) in eclipse.I have imported project in eclipse and performed the necessary steps for setup.
http://hmkcode.com/android-google-cloud-messaging-tutorial/
After going through GCM sample on developer.google.com .The link says google includes GcmReceiver class by default.I removed old GcmBroadcastReceiver from hmkode sample and changed GcmMessageHandler to extend GcmListenerService instead of IntentService(in hmkode/original code).
Link:
https://developers.google.com/cloud-messaging/android/client
Problem:
When I try to send message to the client the client crashes with following exception in logcat
E/AndroidRuntime(20573): java.lang.RuntimeException: Unable to instantiate receiver com.google.android.gms.gcm.GcmReceiver: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.gcm.GcmReceiver" on path: DexPathList[[zip file "/data/app/com.hmkcode.android.gcm-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
E/AndroidRuntime(20573):
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2590)
My Class structure-
public class GcmMessageHandler extends GcmListenerService {
String mes;
private Handler handler;
public GcmMessageHandler() {
super();
}
//com.hmkcode.android.gcm.
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
handler = new Handler();
}
public void showToast(){
handler.post(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),mes , Toast.LENGTH_LONG).show();
}
});
}
}
Activity class
public class MainActivity extends Activity implements OnClickListener {
Button btnRegId;
EditText etRegId;
GoogleCloudMessaging gcm;
String regid;
String PROJECT_NUMBER = "164502923904";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRegId = (Button) findViewById(R.id.btnGetRegId);
etRegId = (EditText) findViewById(R.id.etRegId);
btnRegId.setOnClickListener(this);
}
public void getRegId(){
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
}
regid = gcm.register(PROJECT_NUMBER);
msg = "Device registered, registration ID=" + regid;
Log.i("GCM", msg);
} catch (IOException ex)
{
msg = "Error :" + ex.getMessage();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
etRegId.setText(msg + "\n");
}
}.execute(null, null, null);
}
#Override
public void onClick(View v) {
getRegId();
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hmkcode.android.gcm"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<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="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="com.hmkcode.android.gcm.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.hmkcode.android.gcm.permission.C2D_MESSAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
>
<activity
android:name="com.hmkcode.android.gcm.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:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.hmkcode.android.gcm" />
</intent-filter>
</receiver>
<service android:name="com.hmkcode.android.gcm.GcmMessageHandler" />
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
Also gcm.jar has been added as dependency and exported.
If you use Eclipse with regular android gcm jar, u need to add com.google.android.gcm.GcmReceiver instead of com.google.android.gcm.GCMBroadcastReceiver. This worked for me (at least temporarily)

GCM service not avalible

I follow the example of http://hmkcode.com/android-google-cloud-messaging-tutorial/ , every thing is fine but its alway response SERVICE_NOT_AVALIBLE
The device time is correctly setup, package name is correct,too.
could anyone help me in this case
my MainActivity.java
Button btnRegId;
EditText etRegId;
GoogleCloudMessaging gcm;
String regid;
String PROJECT_NUMBER = "943411953393";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRegId = (Button) findViewById(R.id.btnGetRegId);
etRegId = (EditText) findViewById(R.id.etRegId);
btnRegId.setOnClickListener(this);
}
public void getRegId(){
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
}
regid = gcm.register(PROJECT_NUMBER);
msg = "Device registered, registration ID=" + regid;
Log.i("GCM", msg);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
etRegId.setText(msg + "\n");
}
}.execute(null, null, null);
}
#Override
public void onClick(View v) {
getRegId();
}
My AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gmc"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="14" />
<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="com.google.android.c2dm.permission.RECEIVE" />
<permission
android:name="com.example.gmc.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.gmc.permission.C2D_MESSAGE" />
<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=".GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.example.gmc" />
</intent-filter>
</receiver>
<service android:name=".GcmMessageHandler" />
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
try this
#Override
protected String doInBackground(Void... params) {
String msg = "";
int backoff = 2000;
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
}
}
catch (IOException ex) {
ex.printStackTrace()
}
for(int i=0;i<5;i++){
try {
regid = gcm.register(PROJECT_NUMBER);
msg = "Device registered, registration ID=" + regid;
Log.i("GCM", msg);
break;
}
catch (IOException ex) {
msg = "Error :" + ex.getMessage();
backoff =backoff * 2;
Thread.sleep(backoff);
}
}
return msg;
}
you need to try several attempts increasing the wait time for each try.

Android java.net.SocketException: socket failed: EACCES (Permission denied) while inserting value into sql server through Web service

In my project I am trying to insert user details in to sql server by calling the webservice,while i am connecting to the webservice, java.net.SocketException: socket failed: EACCES (Permission denied) warning appear in logcat, below is my code. I can't insert the values into the sql server.
RegisterToServer.java
public class RegisterToServer extends AsyncTask<UserDetails, Void, Void> {
String SOAP_ACTION1 = "http://tempuri.org/RegisterUser";
String NAMESPACE = "http://tempuri.org/";
String METHOD_NAME1 = "RegisterUser";
String URL="http://192.168.0.100/panictest/WebService2.asmx";
private String TAG = "RegisterUser";
String responseString;
String responseStatus = "SUCCESS";
Context context;
#Override
protected Void doInBackground(UserDetails... params) {
Log.i(TAG, "doInBackground");
RegToServer(params[0]);
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.i(TAG, "onPostExecute");
}
#Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
// Display the progress bar
}
#Override
protected void onProgressUpdate(Void... values) {
Log.i(TAG, "onProgressUpdate");
}
private void RegToServer(UserDetails user) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
request.addProperty("mobileNumber", user.getMobilNumber());
request.addProperty("userName", user.getUserName());
request.addProperty("address", user.getAddress());
Log.i("TAG","Inside regtoserver before webservice call"+user.getAddress());
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION1, envelope);
Object response = (Object) envelope.getResponse();
Log.i("GET ROAD TAX", "Websevice called");
} catch (Exception e) {
e.printStackTrace();
}
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.panicbutton"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<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>
</application>
</manifest>
Try adding:
<uses-permission android:name="android.permisson.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.GET_ACCOUNTS"></uses-permission>
<uses-permission android:name="android.permission.READ_PROFILE"></uses-permission>
<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Categories

Resources