my app crashes without any error message at googleApiClient.connect(). It never gets to onConnectionFailed. Here's what I have:
at MainActivity
public class MainMenu extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
public static final int REQUEST_LEADERBOARD = 1;
public static int SCREEN_WIDTH;
public static int SCREEN_HEIGHT;
private GoogleApiClient googleApiClient;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
SCREEN_WIDTH = metrics.widthPixels;
SCREEN_HEIGHT = metrics.heightPixels;
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(Games.API).addScope(Games.SCOPE_GAMES)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
public void newGame(View view) {
Intent intent = new Intent(MainMenu.this, Game.class);
startActivity(intent);
finish();
}
public void highScore(View view) {
if (isSignedIn()) {
startActivityForResult(Games.Leaderboards.getLeaderboardIntent(googleApiClient,
String.valueOf(R.string.leaderboard_id)), REQUEST_LEADERBOARD);
}
else {
System.out.println("not sign in");
}
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
System.out.println("failed");
}
#Override
protected void onStart() {
super.onStart();
googleApiClient.connect(); //here it crashed
}
private boolean isSignedIn() {
return (googleApiClient != null && googleApiClient.isConnected());
}
}
What I've done:
I have generated signed APK, I have sha1 key. I published the app for alpha testing.
manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="my.package"
android:versionCode="2"
android:versionName="1.1">
<uses-sdk android:minSdkVersion="1"/>
<application android:icon="#drawable/ic_launcher" android:label="#string/app_name"
android:theme="#style/Theme.AppCompat.NoActionBar"
android:isGame="true" >
<meta-data
android:name="com.google.android.gms.games.APP_ID"
android:value="#string/app_id" />
<meta-data
android:name="my.package.version"
android:value="com.google.android.gms.version" />
<activity android:name=".activities.MainMenu">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".activities.Game"/>
<activity android:name=".activities.GameOver"/>
<activity android:name=".activities.HighScore"/>
</application>
</manifest>
I'm testing it on device with Google Play Service installed. Could you help me?
You should add the internet permission to your manifest.
<uses-permission android:name="android.permission.INTERNET"/>
If you need more help, you should show the error stacktrace.
Hope it helps you!
The solution is simple
<meta-data
android:name="my.package.version"
android:value="com.google.android.gms.version" />
is nonsense.
it should be:
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
Related
I am attempting to create a custom PrintService plugin for Android, and I have everything except for that it is not showing up in the list of printers under 'All Printers', and says 'Cannot add printers' under my print service if I click "Add printer" manually. I downloaded this print service which does show up in the list of printers, but I can't figure out what is different in their code versus mine.
My PrintService class:
public class MyPrintService extends PrintService {
PrinterInfo mThermalPrinter;
#Override
public void onCreate() {
mThermalPrinter = new PrinterInfo.Builder(generatePrinterId("USB"),
"USB Printer", PrinterInfo.STATUS_IDLE).build();
}
#Override
protected void onPrintJobQueued(PrintJob printJob) {
Intent intent = new Intent(MyPrintService.this, MainActivity.class);
intent.putExtra("data", printJob.getDocument().getData());
printJob.start();
startActivity(intent);
}
#Nullable
#Override
protected PrinterDiscoverySession onCreatePrinterDiscoverySession() {
return new ThermalPrinterDiscoverySession(mThermalPrinter);
}
#Override
protected void onRequestCancelPrintJob(PrintJob printJob) {
printJob.cancel();
}
}
class ThermalPrinterDiscoverySession extends PrinterDiscoverySession {
private PrinterInfo printerInfo;
ThermalPrinterDiscoverySession(PrinterInfo printerInfo) {
PrinterCapabilitiesInfo capabilities =
new PrinterCapabilitiesInfo.Builder(printerInfo.getId())
.addMediaSize(PrintAttributes.MediaSize.ISO_A5, true)
.addResolution(new PrintAttributes.Resolution("1234","Default",200,200), true)
.setColorModes(PrintAttributes.COLOR_MODE_MONOCHROME, PrintAttributes.COLOR_MODE_MONOCHROME)
.build();
this.printerInfo = new PrinterInfo.Builder(printerInfo)
.setCapabilities(capabilities)
.build();
}
#Override
public void onStartPrinterDiscovery(List<PrinterId> priorityList) {
List<PrinterInfo> printers = new ArrayList<PrinterInfo>();
printers.add(printerInfo);
addPrinters(printers);
}
#Override
public void onStopPrinterDiscovery() {
}
#Override
public void onValidatePrinters(List<PrinterId> printerIds) {
}
#Override
public void onStartPrinterStateTracking(PrinterId printerId) {
}
#Override
public void onStopPrinterStateTracking(PrinterId printerId) {
}
#Override
public void onDestroy() {
}
}
Thanks!
Turns out that it was an issue with the AndroidManifest.xml.
The manifest needs to be as follows:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dubtel.print_service">
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
r
<service
android:name=".MyPrintService"
android:permission="android.permission.BIND_PRINT_SERVICE">
<intent-filter>
<action android:name="android.printservice.PrintService" />
</intent-filter>
<meta-data
android:name="android.printservice"
android:resource="#xml/printservice" />
</service>
<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>
<!--
ATTENTION: This was auto-generated to add Google Play services to your project for
App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information.
-->
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
I want to send data from my Wear to the PhoneApp. I created a phone app with this AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="sh.evolutio.car">
<uses-feature
android:name="android.software.leanback"
android:required="true" />
<application
android:allowBackup="false"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<service android:name=".services.ListenerService" >
<intent-filter>
<action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
<action android:name="com.google.android.gms.wearable.DATA_CHANGED" />
<!-- <data android:scheme="wear" android:host="*" android:pathPrefix="/updatecar" /> -->
</intent-filter>
</service>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
my ListenerService:
package sh.evolutio.car.services;
import android.content.Intent;
import android.util.Log;
import com.google.android.gms.wearable.MessageEvent;
import com.google.android.gms.wearable.WearableListenerService;
public class ListenerService extends WearableListenerService {
private static final String TAG = "ListenerService";
private static final String MESSAGE_PATH = "/updatecar";
#Override
public void onCreate() {
Log.d(TAG, "ListenerService created");
}
#Override
public void onMessageReceived(MessageEvent messageEvent) {
Log.d(TAG, "onMessageReceived");
if (messageEvent.getPath().equals(MESSAGE_PATH)) {
Log.d(TAG, "good message");
} else {
Log.d(TAG, "bad message");
}
}
}
my MainActivity with this onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
startService(new Intent(MainActivity.this, ListenerService.class));
}
When I start the App on my phone I got in the Logcat:
26131-26131/sh.evolutio.car D/ListenerService: ListenerService created
When I send with the wearapp some data to my phone, my ListenerService didn't fire the onMessageReceived method..
Here is my AndroidManifest from the wearapp:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="sh.evolutio.carwear">
<uses-feature android:name="android.hardware.type.watch" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#android:style/Theme.DeviceDefault">
<uses-library
android:name="com.google.android.wearable"
android:required="true" />
<meta-data
android:name="com.google.android.wearable.standalone"
android:value="false" />
<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>
The MainActivity from the wearapp looks like this:
package sh.evolutio.carwear;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.wearable.activity.WearableActivity;
import android.util.Log;
import android.view.View;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.wearable.MessageApi;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.Wearable;
public class MainActivity extends WearableActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static String TAG = "MainActivity";
private static final String MESSAGE_PATH = "/updatecar";
Node mNode; // the connected device to send the message to
GoogleApiClient mGoogleApiClient;
private boolean mResolvingError = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Connect the GoogleApiClient
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
sendMessage("test");
// Enables Always-on
setAmbientEnabled();
}
#Override
protected void onStart() {
super.onStart();
if (!mResolvingError) {
mGoogleApiClient.connect();
}
}
/**
* Resolve the node = the connected device to send the message to
*/
private void resolveNode() {
Log.d(TAG, "resolveNode");
Wearable.NodeApi.getConnectedNodes(mGoogleApiClient)
.setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() {
#Override
public void onResult(NodeApi.GetConnectedNodesResult nodes) {
for (Node node : nodes.getNodes()) {
Log.d(TAG, "resolvedNode: " + node);
mNode = node;
}
}
});
}
#Override
public void onConnected(Bundle bundle) {
resolveNode();
}
#Override
public void onConnectionSuspended(int i) {}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "connectionResult: " + connectionResult);
}
/**
* Send message to mobile handheld
*/
private void sendMessage(String Key) {
if (mNode != null && mGoogleApiClient!= null && mGoogleApiClient.isConnected()) {
final String messageKey = Key;
Log.d(TAG, "isConnected: " + mGoogleApiClient.isConnected());
Log.d(TAG, "connected to: " + mNode.getId());
Task<Integer> sendTask = Wearable.getMessageClient(MainActivity.this).sendMessage(mNode.getId(), MESSAGE_PATH, messageKey.getBytes());
sendTask.addOnSuccessListener(new OnSuccessListener<Integer>() {
#Override
public void onSuccess(Integer integer) {
Log.d(TAG, "onSuccess: " + integer);
}
});
sendTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: " + e.getMessage());
}
});
Wearable.MessageApi.sendMessage(mGoogleApiClient, mNode.getId(), MESSAGE_PATH, messageKey.getBytes()).setResultCallback(
new ResultCallback<MessageApi.SendMessageResult>() {
#Override
public void onResult(#NonNull MessageApi.SendMessageResult sendMessageResult) {
if (sendMessageResult.getStatus().isSuccess()) {
Log.v(TAG, "Message: { " + messageKey + " } sent to: " + mNode.getDisplayName());
} else {
// Log an error
Log.v(TAG, "ERROR: failed to send Message");
}
}
}
);
}
}
}
When I the message got send, i got this in the logcat from the wearapp:
sh.evolutio.carwear D/MainActivity: isConnected: true
sh.evolutio.carwear D/MainActivity: connected to: 778d0d53
sh.evolutio.carwear V/MainActivity: Message: { forward } sent to: HUAWEI Mate 10 Pro
sh.evolutio.carwear D/MainActivity: onSuccess: 17282
so the message was sent to my Mate 10 Pro. But why my Mate 10 Pro App can't receive the Message? Where is my mistake? I didn't find it.
In your mobile activity, do not start the service manually.
The service will be started automatically by Android on reception of the message.
And you need to uncomment your data pathPrefix definition in the AndroidManifest.
My LocalBroadcastManager callback function dosen' receive messeges. Can someone tell my why?
I try to do it on my Samsung Galaxy S3 mini (4.1.2 -Jelly Bean, API 16).
SenderClass:
public static final String BROADCAST = "com.android.SOME_BROADCAST";
private Context context;
public SenderClass(Context context) {
this.context = context;
//...
Intent intent = new Intent(BROADCAST);
//intent.putExtra(EXTRA_SOMEEXTRA, "some extra");
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
//just to keep it simple i do it here
}
MainActivity
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive"); //this is never called!
}
};
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume()");
LocalBroadcastManager.getInstance(this).registerReceiver(
broadcastReceiver,
new IntentFilter(SenderClass.BROADCAST)
);
}
#Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause()");
LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);
}
edit: here the manifest
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android....">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".Activities.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".Services.MyService"
android:enabled="true"
android:exported="false"></service>
</application>
</manifest>
Try this step:-
Register your broadcast in onCreate and Unregister broadcast in onDestroy of Activity.
Thanks,
It may helpful for you.
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)
I am making a very simple app in which I want that a service should run infinitely just like Whatsapp service runs in background, even if the app is removed from Recent Apps by swiping out.
Below is my code.
AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.net.gs.servicetesting" >
<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>
<service
android:name=".MyService"
android:process=":com">
<intent-filter>
<action
android:name="com.net.gs.servicetesting.MyService" />
</intent-filter>
</service>
</application>
</manifest>
MyService.java:
public class MyService extends Service {
private String TAG = "MyService";
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG,"Service Strated");
return START_STICKY;
}
#Override
public void onDestroy() {
Log.d(TAG,"Service Destoryed");
super.onDestroy();
}
}
MainActivity.java:
public class MainActivity extends ActionBarActivity {
String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "Activity Strated");
startService(new Intent(MyService.class.getName()));
}
}
In your Service#onStartCommand method store the starting intent to a field variable, let's say mIntent.
Then implement the Service#onTaskRemoved method like this:
#Override
#TargetApi(14)
public void onTaskRemoved(Intent rootIntent) {
startService(mIntent);
}