GCM service not avalible - java

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.

Related

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)

BroadcastReceiver using 1 time

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 ...
}

Ringtone to specific contact

Edited:1
I'm making an app with sounds and implementing a bit of code I came across the following error to set the sound to a specific contact
this is the code :
Button b7 = (Button)findViewById(R.id.b7);
b7.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
{
if (click){
cp.showAtLocation(v, Gravity.CENTER, 0, 0);
cp.update(0,0,500,500);
click=false;
}else{
cp.dismiss();
click=true;
}}
return click;}});
b7.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v){
File folder = new File(Environment.getExternalStorageDirectory() + "/Bizzsound/");
boolean success = false;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (!success) {
} else {
}
File direct = new File("/sdcard/Bizzsound/");
if (!direct.exists()) {
direct.mkdirs();
}
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(R.raw.b1);
File dir1 = new File ("/sdcard/Bizzsound/");
File f1 = new File(dir1, String.format("b1.mp3"));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int size=0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
try {
FileOutputStream fos = new FileOutputStream(f1);
fos.write(buffer);
fos.flush();
fos.close();
bos.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
File k = new File("/sdcard/Bizzsound/", "b1.mp3");
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "b1.mp3");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(AudioColumns.ARTIST, "artist");
values.put(AudioColumns.IS_RINGTONE, true);
values.put(AudioColumns.IS_NOTIFICATION, true);
values.put(AudioColumns.IS_ALARM, true);
values.put(AudioColumns.IS_MUSIC, false);
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
mpButton1 = MediaPlayer.create(getBaseContext(),R.raw.b1);
mpButton1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mpButton1) {
// TODO Auto-generated method stub
mpButton1.start();
mpButton1.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mpButton1) {
mpButton1.release();
};
});
}
});
}});
}
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String id = c
.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
Uri localUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, id);
File k = new File("/sdcard/Bizzsound/", "b1.mp3");
ContentValues localContentValues = new ContentValues();
String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone.equalsIgnoreCase("1")) {
Cursor phones = getContentResolver().query
(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null, null);
phones.moveToFirst();
String cNumber = phones.getString(phones //error at this line
.getColumnIndex("b1.mp3"));
System.out.println("number is:" + cNumber);
}
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String SDCardRoot1 = (Environment.getExternalStorageDirectory() + "/b1.mp3");
localContentValues.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
localContentValues.put(MediaStore.MediaColumns.TITLE,"b1.mp3");
localContentValues.put(MediaStore.MediaColumns.MIME_TYPE,"audio/*");
localContentValues.put(MediaStore.Audio.Media.ARTIST, "");
localContentValues.put(MediaStore.Audio.Media.IS_RINGTONE, true);
localContentValues.put(AudioColumns.IS_NOTIFICATION, true);
localContentValues.put(AudioColumns.IS_ALARM, true);
localContentValues.put(AudioColumns.IS_MUSIC, false);
localContentValues.put(ContactsContract.Data.RAW_CONTACT_ID, id);
localContentValues.put(ContactsContract.Data.CUSTOM_RINGTONE, SDCardRoot1);
getContentResolver().update(localUri, localContentValues,
null, null);
Toast.makeText(this, "Ringtone assigned to: " + name, 0).show();
}
}
break;
}
}
}
Now the phone freezes when receiving the call from the contact and getting this error:
the process com.android.phone has been stopped
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.bizzsound1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.GET_TASKS"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:largeHeap="true" >
<activity
android:name="org.bizzsound1.MainActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="org.bizzsound1.menu"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="org.bizzsound1.MENU" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name="org.bizzsound1.Disclamer"
android:screenOrientation="portrait">
</activity>
<activity android:name="com.startapp.android.eula.EULAActivity"
android:theme="#android:style/Theme.Translucent"
android:configChanges="keyboard|keyboardHidden|orientation" />
<activity android:name="com.startapp.android.publish.list3d.List3DActivity"
android:taskAffinity="altervista.org.gapplication1.AppWall"
android:theme="#android:style/Theme" />
<activity android:name="com.startapp.android.publish.AppWallActivity"
android:theme="#android:style/Theme.Translucent" android:taskAffinity="altervista.org.gapplication1.AppWall"
android:configChanges="orientation|keyboardHidden" />
<activity android:name="com.google.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
</application>
</manifest>

Android GCM Work on ICS but not on gingerbread

I have a problem with the GCM service.
My app correctly work on android >= 4.0 device but not (e.g) on gingerbread.
I think that the problem it's the manifest but seem right
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.maptest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<permission android:name="com.example.maptest.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="com.example.maptest.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Network State Permissions to detect Internet status -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- Permission to vibrate -->
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<uses-library android:name="com.google.android.maps"/>
<activity
android:name=".RegisterActivity"
android:label="#string/app_name" >
</activity>
<activity
android:name="com.example.maptest.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.gcm.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="MapTest" />
</intent-filter>
</receiver>
<service android:name="com.example.maptest.GCMIntentService" android:enabled="true"/>
</application>
</manifest>
And my class
public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GCMIntentService";
public GCMIntentService() {
super(SENDER_ID);
Log.d(TAG,"CREATO IL Servizio");
}
/**
* Method called on device registered
**/
#Override
protected void onRegistered(Context context, String registrationId) {
Log.i(TAG, "Device registered: regId = " + registrationId);
displayMessage(context, "Your device registred with GCM");
Log.d("NAME", MainActivity.name);
ServerUtilities.register(context, MainActivity.name, MainActivity.email, registrationId);
/*TODO*/
MainActivity.regId=registrationId;
}
/**
* Method called on device un registred
* */
#Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "Device unregistered");
displayMessage(context, getString(R.string.gcm_unregistered));
ServerUtilities.unregister(context, registrationId);
}
/**
* Method called on Receiving a new message
* */
#Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("price");
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
/**
* Method called on receiving a deleted message
* */
#Override
protected void onDeletedMessages(Context context, int total) {
Log.i(TAG, "Received deleted messages notification");
String message = getString(R.string.gcm_deleted, total);
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
/**
* Method called on Error
* */
#Override
public void onError(Context context, String errorId) {
Log.i(TAG, "Received error: " + errorId);
displayMessage(context, getString(R.string.gcm_error, errorId));
}
#Override
protected boolean onRecoverableError(Context context, String errorId) {
// log message
Log.i(TAG, "Received recoverable error: " + errorId);
displayMessage(context, getString(R.string.gcm_recoverable_error,
errorId));
return super.onRecoverableError(context, errorId);
}
}
In the LogCat nothing it's displayed.
Can someone help me ?
Thank's!
If this is com.example.maptest your package name, it should be the one that you declare in your manifest file in
<category android:name="MapTest" />
to be something like this
<category android:name="com.example.maptest" />

Categories

Resources