javascript

java

python

c#

android

node.js

c++

reactjs

php

html

jquery

css

.net

ios

git

ruby-on-rails

sql

c

string

ruby

android.database.CursorIndexOutOfBoundsException:已请求索引0,大小为0

我正在使用自定义适配器扩展游标适配器以在listview中显示数据,以显示特定的电话号码,我已将id传递给数据库类中的方法,但它正在显示

errorandroid.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0 

在将调试器放置在该方法中之后

num = cursor.getString(cursor.getColumnIndex("ContactNumber"));

谁能帮我解决这个问题。这是代码:

public String getNumberFromId(int id) 
{
    String num;
    db= this.getReadableDatabase();
    Cursor cursor = db.query(scheduletable, new String[] { "ContactNumber" },"_id="+id, null, null, null, null);
    cursor.moveToFirst();
    num = cursor.getString(cursor.getColumnIndex("ContactNumber")); 
    cursor.close();
    db.close();
    return num;
}
trans by 2020-02-29T16:50:12Z

值等于dimens.xml中的match_parent或fill_parent?

基于此处的“ XML属性”部分,我在wrap_content中指定以下内容:

<dimen name="match_parent">-1dp</dimen>
<dimen name="main_left_menu_user_account_width">@dimen/match_parent</dimen>
<dimen name="main_left_menu_user_account_height">@dimen/match_parent</dimen>

然后,在布局中使用这两个维度:

<ImageView 
    android:id="@+id/userAccountImage"
    android:background="@drawable/user_account"
    android:layout_width="@dimen/main_left_menu_user_account_width"
    android:layout_height="@dimen/main_left_menu_user_account_height" />

然后,当我预览到wrap_content时,它抱怨:

您必须提供layout_width属性。

您必须提供layout_height属性。

其实我可以在wrap_content中定义一个等于match_parent的值吗?

更新:

我也尝试过,但是预览仍然抱怨:

<dimen name="main_left_menu_user_account_width">-1dp</dimen>
<dimen name="main_left_menu_user_account_height">-1dp</dimen>

我成功使用了wrap_contentGraphical Layout完全没有抱怨):

<dimen name="wrap_content">-2dp</dimen>

<dimen name="main_right_menu_width">@dimen/wrap_content</dimen>
<dimen name="main_right_menu_height">@dimen/wrap_content</dimen>
trans by 2020-02-29T15:34:30Z

Android应用程序可以直接连接到在线mysql数据库吗

Android 3.3 API 18

你好,

我正在使用android开发我的第一个应用程序。 该应用程序将必须连接到在线数据库以存储用户数据。

我正在寻找包含MySQL数据库的云存储。 但是,我的应用程序可以直接连接到该MySQL数据库并从中推入和拉出数据吗? 还是我需要做其他事情?

非常感谢您的任何建议,

trans by 2020-02-29T14:55:52Z

java-为Robolectri提供SharedPreferences的测试数据

刚开始使用Robolectric,这似乎是我所需要的。 但是,在使用SharedPreferences方面,我遇到了一些障碍。

我有两个测试案例

  1. 活动需要一个新的/空的sharedPreferences

  2. 活动期望其中已经包含一些数据的sharedPreferences

对于测试用例1,测试按预期通过,所以一切都很好:)

但是,对于测试用例2,我似乎无法找到一种向Robolectric提供一些虚假数据的好方法,因此Activity可以访问该虚假数据。

感觉像是一个非常普通的用例,但我似乎无法弄清楚该怎么做!

trans by 2020-02-29T13:27:09Z

将ORMLite与SQLite和Android结合使用的好教程是什么

我正在寻找有关如何将ORMLite与SQLite和Android结合使用的良好入门教程。 谷歌qucick搜索没有产生任何有用的信息。

trans by 2020-02-29T12:46:21Z

android-gradle组装和gradle构建任务之间有什么区别?

如果我没有记错,那么gradle assemblegradle assembleDebuggradle assembleRelease确实可以运行,但是我相信gradle build也可以做到相同,那么两者之间有何不同?

trans by 2020-02-29T11:40:45Z

android string.xml读取html标签问题

在Android项目的strings.xml文件中,我有以下HTML文本

<?xml version="1.0" encoding="utf-8"?>

<resources>

<string name="myHeadStr"><b><u>bold, underline </u></b></string>
...

</resources>

当我将其读入getString(R.string.myHeadStr)时,它仅给出文本“粗体,下划线”,它会忘记html标记和...。

如何从string.xml中读取带有html标记的完整字符串

trans by 2020-02-29T10:06:58Z

android-Firebase Cloud Messaging上次未收到塌陷密钥(限速吗?)

我有一个使用Firebase Cloud Messaging与FCM数据消息及其2759542018157315315072参数集与其Android客户端进行通信的服务。 从有关可折叠密钥的文档中:

当有较新的消息呈现较旧的线程时,相关消息与客户端应用程序无关,FCM替换了较旧的消息。 例如,发送到同步或过时的通知消息。

这就是我要的东西。 我不需要所有更新,仅需要最后一个。 但是,如果用户在线,则需要尽快。


但是,我得到了一个奇怪的速率限制,它不会导致任何HTTP错误代码。 只需连续执行20条数据消息并监视android 200,就很容易重现:

for i in {1..20}; do 
  curl -v -X POST --header "Authorization: key=$SERVER_KEY" \
       --Header "Content-Type: application/json" \
       https://fcm.googleapis.com/fcm/send \
       -d "{\"to\":\"$CLIENT_TOKEN\", \
            \"data\":{\"counter\":\"$i\"}, \
            \"priority\":\"high\", \
            \"collapse_key\": \"test\" \
           }"
done

上面的bash脚本有点难以阅读,但是我感兴趣的是200变量。

在收到一些消息(200)之后,它停止,您需要切换网络状态以获取counter={1..20}的最后一条消息。当请求Firebase签入时,最后一条消息也会在几分钟后(通常是10分钟左右)出现(? )。

从上面的curl命令中删除200,将导致接收到所有20条消息(其中counter={1..20})。


所以,问题是:这是一个错误吗? 还是因为我“滥用”该接口而关闭了(/速率受限)(因为所有请求都发送回200响应,我认为我还可以)。

trans by 2020-02-23T00:54:19Z

Java-Android Room数据库:如何在实体中处理Arraylist?

我刚刚实现了Room来保存离线数据。 但是在Entity类中,出现以下错误:

Error:(27, 30) error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.

该类如下:

@Entity(tableName = "firstPageData")
public class MainActivityData {
@PrimaryKey
private String userId;

@ColumnInfo(name = "item1_id")
private String itemOneId;

@ColumnInfo(name = "item2_id")
private String itemTwoId;

   // THIS IS CAUSING THE ERROR... BASICALLY IT ISN'T READING ARRAYS
   @ColumnInfo(name = "mylist_array")
    private ArrayList<MyListItems> myListItems;

public String getUserId() {
    return userId;
}

public void setUserId(String userId) {
    this.userId = userId;
}


public ArrayList<MyListItems> getMyListItems() {
    return myListItems;
}

public void setCheckListItems(ArrayList<MyListItems> myListItems) {
    this.myListItems = myListItems;
}
}

因此,基本上我想将ArrayList保存在数据库中,但找不到任何相关的东西。 您可以指导我如何使用Room保存阵列吗?

注意:MyListItems Pojo类包含2个字符串(到目前为止)

提前致谢。

trans by 2020-02-23T00:33:25Z

android-错误连接被拒绝

我想建立一个到我自己的servlet的Http连接。 这是我的代码:

try
{
    HttpClient client = new DefaultHttpClient();
    HttpPost httpMethod = new HttpPost("http://localhost:8080/getHeader/HeaderServlet");
    httppost.setHeader("Content-Type", "application/x-www-form-urlencoded"); 
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String response = client.execute(httppost, responseHandler);
    String result = response.toString();
}

但是我无法,但出现错误:

org.apache.http.conn.HttpHostConnectionException:Connection to http://localhost:8080 refused

感谢您的帮助

trans by 2020-02-23T00:24:16Z

Android Studio:无法启动守护进程

尝试在Android Studio中导入gradle项目时遇到以下错误。

Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the user guide chapter on the daemon at http://gradle.org/docs/1.8/userguide/gradle_daemon.html
Please read below process output to find out more: 

这是我看到的输出:

18:25:42.484 [main] DEBUG o.g.l.daemon.bootstrap.DaemonMain - Assuming the daemon was started with following jvm opts: [-XX:MaxPermSize=256m, -XX:+HeapDumpOnOutOfMemoryError, -Xmx1024m, -Dfile.encoding=windows-1252]
18:25:43.254 [main] DEBUG o.g.l.daemon.server.DaemonServices - Creating daemon context with opts: [-XX:MaxPermSize=256m, -XX:+HeapDumpOnOutOfMemoryError, -Xmx1024m, -Dfile.encoding=windows-1252]
18:25:43.306 [DEBUG] [org.gradle.logging.internal.DefaultLoggingConfigurer] Finished configuring with level: DEBUG, configurers: [org.gradle.logging.internal.OutputEventRenderer@47078ad, org.gradle.logging.internal.logback.LogbackLoggingConfigurer@7402a821, org.gradle.logging.internal.JavaUtilLoggingConfigurer@5a6c4a07]
18:25:43.356 [INFO] [org.gradle.launcher.daemon.server.Daemon] start() called on daemon - DefaultDaemonContext[uid=e58252c1-7a49-4be4-a6cd-1bd3d6d0880d,javaHome=C:\Program Files\Java\jdk1.7.0_45,daemonRegistryDir=C:\Users\Sowmya\.gradle\daemon,pid=15432,idleTimeout=60000,daemonOpts=-XX:MaxPermSize=256m,-XX:+HeapDumpOnOutOfMemoryError,-Xmx1024m,-Dfile.encoding=windows-1252]
18:25:43.362 [DEBUG] [org.gradle.launcher.daemon.server.DaemonStateCoordinator] updating lastActivityAt to 1386593743362
18:25:43.702 [DEBUG] [org.gradle.messaging.remote.internal.inet.InetAddressFactory] Adding IP addresses for network interface lo
18:25:43.705 [DEBUG] [org.gradle.messaging.remote.internal.inet.InetAddressFactory] Is this a loopback interface? true
18:25:43.706 [DEBUG] [org.gradle.messaging.remote.internal.inet.InetAddressFactory] Adding loopback address /127.0.0.1
18:25:43.707 [DEBUG] [org.gradle.messaging.remote.internal.inet.InetAddressFactory] Adding loopback address /0:0:0:0:0:0:0:1
18:25:43.708 [DEBUG] [org.gradle.messaging.remote.internal.inet.InetAddressFactory] Adding IP addresses for network interface net0
18:25:43.711 [DEBUG] [org.gradle.messaging.remote.internal.inet.InetAddressFactory] Is this a loopback interface? false
DefaultDaemonContext[uid=e58252c1-7a49-4be4-a6cd-1bd3d6d0880d,javaHome=C:\Program Files\Java\jdk1.7.0_45,daemonRegistryDir=C:\Users\Sowmya\.gradle\daemon,pid=15432,idleTimeout=60000,daemonOpts=-XX:MaxPermSize=256m,-XX:+HeapDumpOnOutOfMemoryError,-Xmx1024m,-Dfile.encoding=windows-1252]
18:25:43.951 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Waiting to acquire exclusive lock on daemon addresses registry.
18:25:43.954 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Lock acquired.
18:25:43.957 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Releasing lock on daemon addresses registry.
18:25:43.962 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Waiting to acquire exclusive lock on daemon addresses registry.
18:25:43.963 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Lock acquired.
18:25:43.966 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Releasing lock on daemon addresses registry.
18:25:43.976 [ERROR] [system.err] 
18:25:43.977 [ERROR] [system.err] FAILURE: Build failed with an exception.
18:25:43.977 [ERROR] [system.err] 
18:25:43.978 [ERROR] [system.err] * What went wrong:
18:25:43.979 [ERROR] [system.err] Could not write cache value to 'C:\Users\Sowmya\.gradle\daemon\1.8\registry.bin'.
18:25:43.979 [ERROR] [system.err] 
18:25:43.980 [ERROR] [system.err] * Try:
18:25:43.981 [ERROR] [system.err] Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
18:25:44.009 [INFO] [org.gradle.launcher.daemon.bootstrap.DaemonMain] Daemon[pid = 15432] process has finished.
18:25:44.010 [DEBUG] [org.gradle.launcher.daemon.registry.PersistentDaemonRegistry] Removing daemon address: [9ae053cd-4dc2-4cb8-8f60-bb3c5983eb67 port:55117, addresses:[/127.0.0.1, /0:0:0:0:0:0:0:1]]
18:25:44.011 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Waiting to acquire exclusive lock on daemon addresses registry.
18:25:44.012 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Lock acquired.
18:25:44.013 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Releasing lock on daemon addresses registry.
18:25:44.014 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Waiting to acquire exclusive lock on daemon addresses registry.
18:25:44.015 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Lock acquired.
18:25:44.016 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Releasing lock on daemon addresses registry.
18:25:44.021 [DEBUG] [org.gradle.launcher.daemon.server.Daemon] VM shutdown hook was unable to remove the daemon address from the registry. It will be cleaned up later.
org.gradle.api.GradleException: Could not write cache value to 'C:\Users\Sowmya\.gradle\daemon\1.8\registry.bin'.
    at org.gradle.cache.internal.SimpleStateCache.serialize(SimpleStateCache.java:74)
    at org.gradle.cache.internal.SimpleStateCache.access$100(SimpleStateCache.java:28)
    at org.gradle.cache.internal.SimpleStateCache$2.run(SimpleStateCache.java:50)
    at org.gradle.cache.internal.DefaultFileLockManager$DefaultFileLock.doWriteAction(DefaultFileLockManager.java:198)
    at org.gradle.cache.internal.DefaultFileLockManager$DefaultFileLock.writeFile(DefaultFileLockManager.java:187)
    at org.gradle.cache.internal.OnDemandFileAccess.writeFile(OnDemandFileAccess.java:58)
    at org.gradle.cache.internal.SimpleStateCache.set(SimpleStateCache.java:48)
    at org.gradle.cache.internal.FileIntegrityViolationSuppressingPersistentStateCacheDecorator.set(FileIntegrityViolationSuppressingPersistentStateCacheDecorator.java:38)
    at org.gradle.cache.internal.FileIntegrityViolationSuppressingPersistentStateCacheDecorator.update(FileIntegrityViolationSuppressingPersistentStateCacheDecorator.java:46)
    at org.gradle.launcher.daemon.registry.PersistentDaemonRegistry.remove(PersistentDaemonRegistry.java:109)
    at org.gradle.launcher.daemon.server.Daemon$1.run(Daemon.java:100)
Caused by: java.io.FileNotFoundException: C:\Users\Sowmya\.gradle\daemon\1.8\registry.bin (Access is denied)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:171)
    at org.gradle.cache.internal.SimpleStateCache.serialize(SimpleStateCache.java:67)
    ... 10 more`

我已经关闭了SO解决方案中提到的防病毒功能。 但是似乎没有任何作用。

trans by 2020-02-22T23:33:07Z

Eclipse中的Android错误:“无法执行dex:无法将新索引65799合并为非巨型指令!”

我正在尝试使用通过Eclipse使用OpenSAML的Android项目。 我已经在构建路径中添加了所有必需的jar文件。 现在,当我将程序作为Android应用程序运行时,出现以下错误:

[2012-11-18 11:52:59 - Dex Loader] Unable to execute dex: Cannot merge new index 67075 into a non-jumbo instruction!
[2012-11-18 11:52:59 - MyTestProgram] Conversion to Dalvik format failed: Unable to execute dex: Cannot merge new index 67075 into a non-jumbo instruction!

我用谷歌搜索了一下,但是什么都没出现。 该错误意味着什么?

trans by 2020-02-22T22:42:15Z

在AMD进程上运行Android Studio模拟器

Android新手。 我的处理器是AMD,而不是Intel,因此我无法在Android studio中打开模拟器。

这个答案有一个注释:'您可以运行ARM(非Intel)仿真器映像。 从您的列表中,选择一个非Intel模拟。 他们没有解释在哪里可以找到。 有任何想法吗? 谢谢

Android Studio模拟器和AMD CPU

trans by 2020-02-22T22:13:14Z

java-如何在Android的蓝牙打印机上打印图像?

我必须在热蓝牙打印机上打印一些数据,我正在这样做:

String message="abcdef any message 12345";
byte[] send;
send = message.getBytes();
mService.write(send);

它适用于文本,但不适用于图像。 我想我需要获取byte[]的图像数据。 我尝试通过这种方式获取图像数据:

Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.qrcode);
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] image=stream.toByteArray();

不幸的是,打印机打印了许多奇怪的字符(大约50厘米的纸张)。 我不知道如何打印图像。

我想尝试获取位图的像素,然后将其转换为byte[]并发送,但是我不知道该怎么做。

谢谢

更新:

经过这么长时间,我正在执行此操作:我有一个名为print_image(String file)的方法,该方法获取要打印的图像的路径:

private void print_image(String file) {
    File fl = new File(file);
    if (fl.exists()) {
        Bitmap bmp = BitmapFactory.decodeFile(file);
        convertBitmap(bmp);
        mService.write(PrinterCommands.SET_LINE_SPACING_24);

        int offset = 0;
        while (offset < bmp.getHeight()) {
            mService.write(PrinterCommands.SELECT_BIT_IMAGE_MODE);
            for (int x = 0; x < bmp.getWidth(); ++x) {

                for (int k = 0; k < 3; ++k) {

                    byte slice = 0;
                    for (int b = 0; b < 8; ++b) {
                        int y = (((offset / 8) + k) * 8) + b;
                        int i = (y * bmp.getWidth()) + x;
                        boolean v = false;
                        if (i < dots.length()) {
                            v = dots.get(i);
                        }
                        slice |= (byte) ((v ? 1 : 0) << (7 - b));
                    }
                    mService.write(slice);
                }
            }
            offset += 24;
            mService.write(PrinterCommands.FEED_LINE);
            mService.write(PrinterCommands.FEED_LINE);          
            mService.write(PrinterCommands.FEED_LINE);
            mService.write(PrinterCommands.FEED_LINE);
            mService.write(PrinterCommands.FEED_LINE);
            mService.write(PrinterCommands.FEED_LINE);
        }
        mService.write(PrinterCommands.SET_LINE_SPACING_30);


    } else {
        Toast.makeText(this, "file doesn't exists", Toast.LENGTH_SHORT)
                .show();
    }
}

我是根据这篇文章做的

这是PrinterCommands类:

public class PrinterCommands {
public static final byte[] INIT = {27, 64};
public static byte[] FEED_LINE = {10};

public static byte[] SELECT_FONT_A = {27, 33, 0};

public static byte[] SET_BAR_CODE_HEIGHT = {29, 104, 100};
public static byte[] PRINT_BAR_CODE_1 = {29, 107, 2};
public static byte[] SEND_NULL_BYTE = {0x00};

public static byte[] SELECT_PRINT_SHEET = {0x1B, 0x63, 0x30, 0x02};
public static byte[] FEED_PAPER_AND_CUT = {0x1D, 0x56, 66, 0x00};

public static byte[] SELECT_CYRILLIC_CHARACTER_CODE_TABLE = {0x1B, 0x74, 0x11};

public static byte[] SELECT_BIT_IMAGE_MODE = {0x1B, 0x2A, 33, -128, 0};
public static byte[] SET_LINE_SPACING_24 = {0x1B, 0x33, 24};
public static byte[] SET_LINE_SPACING_30 = {0x1B, 0x33, 30};

public static byte[] TRANSMIT_DLE_PRINTER_STATUS = {0x10, 0x04, 0x01};
public static byte[] TRANSMIT_DLE_OFFLINE_PRINTER_STATUS = {0x10, 0x04, 0x02};
public static byte[] TRANSMIT_DLE_ERROR_STATUS = {0x10, 0x04, 0x03};
public static byte[] TRANSMIT_DLE_ROLL_PAPER_SENSOR_STATUS = {0x10, 0x04, 0x04};
}

如在print_image方法中看到的,我正在调用一个方法,称为convertBitmap,并且我发送一个位图,这是代码:

   public String convertBitmap(Bitmap inputBitmap) {

    mWidth = inputBitmap.getWidth();
    mHeight = inputBitmap.getHeight();

    convertArgbToGrayscale(inputBitmap, mWidth, mHeight);
    mStatus = "ok";
    return mStatus;

}

private void convertArgbToGrayscale(Bitmap bmpOriginal, int width,
        int height) {
    int pixel;
    int k = 0;
    int B = 0, G = 0, R = 0;
    dots = new BitSet();
    try {

        for (int x = 0; x < height; x++) {
            for (int y = 0; y < width; y++) {
                // get one pixel color
                pixel = bmpOriginal.getPixel(y, x);

                // retrieve color of all channels
                R = Color.red(pixel);
                G = Color.green(pixel);
                B = Color.blue(pixel);
                // take conversion up to one single value by calculating
                // pixel intensity.
                R = G = B = (int) (0.299 * R + 0.587 * G + 0.114 * B);
                // set bit into bitset, by calculating the pixel's luma
                if (R < 55) {                       
                    dots.set(k);//this is the bitset that i'm printing
                }
                k++;

            }


        }


    } catch (Exception e) {
        // TODO: handle exception
        Log.e(TAG, e.toString());
    }
}

这是我正在使用的打印机,分辨率:8点/毫米,576点/线

这就是我想要做的(我使用同一台打印机,但是使用了从Play商店下载的应用程序)Image that I want to print

这就是我现在要得到的My printing trying

更接近:A closer part

Closer2:enter image description here

可以看到图像的一小部分,所以我认为我可以打印图像了。

我正在使用的图像是这样的(576x95):enter image description here

这是转换后的图像(我正在使用上层代码对其进行转换):converted image

Inverted

因此,答案是:我做错了什么?,我认为该命令中存在错误:

  public static byte[] SELECT_BIT_IMAGE_MODE = {0x1B, 0x2A, 33, -128, 0};

但是,如何计算图像的正确值呢?谢谢

trans by 2020-02-22T20:48:54Z

alarmmanager-当Android 6.0在打ze模式下如何使Alarm Manager正常工作?

我是Google Play上两个闹钟应用的开发者。 我试图让他们使用Android 6.0。 但是,打Do模式使它不会响起。 我将它们放在白名单上,我放置了一个前台通知图标,我不确定我还能做什么-在“打Do”模式下,“警报管理器”警报仍将被忽略。 不过,“时钟”应用程序(这是Google Play而不是AOSP应用程序)有所不同。 在“时钟”应用上启用警报后,“ adb deviceidle step”将始终显示为“ active”,而不会显示为“ idle”,“ idle_pending”或其他任何内容。

Android是否在这里作弊,从而赋予其自己的应用更多功能。 “拉一个苹果”? Google Play上的所有闹钟应用程序都会失效吗? 这里有些担心,这些都是高质量的应用程序,每个应用程序都花费了一年的兼职开发时间,对我来说是巨大的收入来源。 关于如何使它们工作的任何线索都将提供巨大帮助。

设置AlarmManager的意图:

        Intent intent = new Intent(context, ReceiverAlarm.class);
        if (android.os.Build.VERSION.SDK_INT >= 16) {
            intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
        }
        amSender = PendingIntent.getBroadcast(context, 1, intent, PendingIntent.FLAG_CANCEL_CURRENT); //FLAG_CANCEL_CURRENT seems to be required to prevent a bug where the intent doesn't fire after app reinstall in KitKat
        am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP, scheduleToTime+1, amSender);

和ReceiverAlarm类:

public class ReceiverAlarm extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {
    if (wakeLock == null) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Theme.appTitle);
        wakeLock.acquire();
    }
    X.alarmMaster.startRingingAlarm(true);
}

以及X.alarmMaster.startRingingAlarm()方法的相关部分:

    if (wakeLock == null) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Theme.appTitle);
        wakeLock.acquire();
    }

    if (screenWakeLock == null) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        screenWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, Theme.appTitle+" scr");
        screenWakeLock.acquire();
    }

    Intent alarmIntent = new Intent(Intent.ACTION_VIEW);
    alarmIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    alarmIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    alarmIntent.setClass(context, ActivityAlarmAlarm.class);

    context.startActivity(alarmIntent);

某些方法已内联粘贴以便于阅读。

trans by 2020-02-22T20:45:19Z

setSupportActionBar工具栏不能应用于(android.widget.Toolbar)

我一直在寻找答案,并且尝试了许多可能的解决方案,但似乎无济于事。

我正在尝试按照本教程设置“材质操作栏”。

这是我的代码:

tool_bar.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/ColorPrimary"
    android:elevation="4dp">

</android.support.v7.widget.Toolbar>

activity.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF">
    <!-- The main content view -->
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <include
            android:id="@+id/app_bar"
            layout="@layout/tool_bar" />
    </RelativeLayout>
    <!-- Navigation Drawer -->
    <ListView
        android:id="@+id/left_drawer"
        android:layout_width="220dp"
        android:layout_height="match_parent"
        android:layout_gravity="left"
        android:background="#1C1C1C"
        android:divider="@android:color/darker_gray"
        android:dividerHeight="1dp" />

</android.support.v4.widget.DrawerLayout>

最后是我的activity.java:

import android.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toolbar;


public class rutaActivity extends ActionBarActivity {

private Toolbar toolbar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ruta);

        getSupportActionBar().hide();//Ocultar ActivityBar anterior

        toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar); //HERE'S THE PROBLEM !!!!

错误:

无法将ActionBarActivity中的setSupporActionBar(android.support.v7.widget.Toolbar)应用于(android.widget.Toolbar)

我怎样才能解决这个问题?

trans by 2020-02-22T20:21:35Z

textview-无法解析android.support.design。 迁移到AndroidX之后

我正在尝试使用此代码片段获取SnackbarTextView

snackbarView.findViewById<TextView>(android.support.design.R.id.snackbar_text)  

但是Android Studio无法解析设计库。

我如何才能使此代码正常工作?

trans by 2020-02-22T20:18:24Z

如何更改Android标签小部件的背景?

我的课扩展了TabActivity

TabHost mTabHost =  getTabHost();

TabHost.TabSpec tab1 =mTabHost.newTabSpec("tab1");
TabHost.TabSpec tab2 =mTabHost.newTabSpec("tab2");

tab1 .setIndicator("title tab1");
tab2 .setIndicator("title tab2");
mTabHost.addTab(tab1);mTabHost.addTab(tab2);

TabHost.setCurrentTab(0 or 1)

有人可以指导我如何更改所选标签的背景图像或颜色吗?

trans by 2020-02-22T20:14:33Z

如何防止.connect()之后Android蓝牙RFCOMM连接立即死亡?

这个问题已经解决了! 非常感谢Brad,Denis和瘾君子! 你是英雄! :)

这是工作代码。 它连接到Zeemote并从中读取数据。

=====代码=====

public class ZeeTest extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        try {
            for (int i = 0; i < 3; i++) {
                test();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean connected = false;
    private BluetoothSocket sock;
    private InputStream in;
    public void test() throws Exception {
        if (connected) {
            return;
        }
        BluetoothDevice zee = BluetoothAdapter.getDefaultAdapter().
            getRemoteDevice("00:1C:4D:02:A6:55");
        Method m = zee.getClass().getMethod("createRfcommSocket",
            new Class[] { int.class });
        sock = (BluetoothSocket)m.invoke(zee, Integer.valueOf(1));
        Log.d("ZeeTest", "++++ Connecting");
        sock.connect();
        Log.d("ZeeTest", "++++ Connected");
        in = sock.getInputStream();
        byte[] buffer = new byte[50];
        int read = 0;
        Log.d("ZeeTest", "++++ Listening...");
        try {
            while (true) {
                read = in.read(buffer);
                connected = true;
                StringBuilder buf = new StringBuilder();
                for (int i = 0; i < read; i++) {
                    int b = buffer[i] & 0xff;
                    if (b < 0x10) {
                        buf.append("0");
                    }
                    buf.append(Integer.toHexString(b)).append(" ");
                }
                Log.d("ZeeTest", "++++ Read "+ read +" bytes: "+ buf.toString());
            }
        } catch (IOException e) {}
        Log.d("ZeeTest", "++++ Done: test()");
    }
    @Override
    public void onDestroy() {
        try {
            if (in != null) {
                in.close();
            }
            if (sock != null) {
                sock.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }
}

=====原始问题=====

我正在尝试从运行2.0.1固件的Moto Droid连接到Zeemote([http://zeemote.com/)]游戏控制器。 下面的测试应用程序确实已连接到设备(LED闪烁),但此后立即断开连接。

我在下面粘贴了两个测试应用程序:一个实际上尝试从输入流中读取,另一个则只是坐在那里,等待设备在5秒钟后断开连接。 是的,我确实有第三个版本:),它首先等待ACL_CONNECTED,然后打开套接字,但是它的行为没有新内容。

一些背景信息:我可以使用bluez工具(也附带日志)从我的笔记本电脑连接到Zeemote,效果非常好。 我确定Droid也可以与Zeemote进行对话,因为来自Market的“ Game Pro”可以很好地工作(但是那是驱动程序/服务,所以也许它使用了较低级的API?)。

我注意到,“ adb bugreport”既没有报告Zeemote的UUID也没有报告RFCOMM频道,而报告了所有其他设备(包括Moto HS815耳机,另一个“ sdp浏览”不报告的哑设备)。 同样,当设备启动时,Zeemote的优先级为0(其他优先级为100+)。

我在这里很茫然,我花了很长时间从事研究,以至于我耗尽了想法,所以任何帮助将不胜感激(即使您不知道答案:))

谢谢,最高

测试申请号1

此应用尝试实际从设备读取。

=====代码=====

public class ZeeTest extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        try {
            test();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private BluetoothSocket sock;
    private InputStream in;
    public void test() throws IOException {
        BluetoothDevice zee = BluetoothAdapter.getDefaultAdapter().
                      getRemoteDevice("00:1C:4D:02:A6:55");
        sock = zee.createRfcommSocketToServiceRecord(
                      UUID.fromString("8e1f0cf7-508f-4875-b62c-fbb67fd34812"));
        Log.d("ZeeTest", "++++ Connecting");
        sock.connect();
        Log.d("ZeeTest", "++++ Connected");
        in = sock.getInputStream();
        byte[] buffer = new byte[1];
        int bytes = 0;
        int x = 0;
        Log.d("ZeeTest", "++++ Listening...");
        while (x < 2) {
            x++;
            try {
                bytes = in.read(buffer);
                Log.d("ZeeTest", "++++ Read "+ bytes +" bytes");
            } catch (IOException e) {
                e.printStackTrace();
                try { Thread.sleep(100); } catch (InterruptedException ie) {}
            }
        }
        Log.d("ZeeTest", "++++ Done: test()");
    }
    @Override
    public void onDestroy() {
        try {
            if (in != null) {
                in.close();
            }
            if (sock != null) {
                sock.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }
}

=====日志=====

04-19 22:27:01.147: DEBUG/ZeeTest(8619): ++++ Connecting
04-19 22:27:04.085: INFO/usbd(1062): process_usb_uevent_message(): buffer = add@/devices/virtual/bluetooth/hci0/hci0:1
04-19 22:27:04.085: INFO/usbd(1062): main(): call select(...)
04-19 22:27:04.327: ERROR/BluetoothEventLoop.cpp(4029): event_filter: Received signal org.bluez.Device:PropertyChanged from /org/bluez/4121/hci0/dev_00_1C_4D_02_A6_55
04-19 22:27:04.491: VERBOSE/BluetoothEventRedirector(7499): Received android.bleutooth.device.action.UUID
04-19 22:27:04.905: DEBUG/ZeeTest(8619): ++++ Connected
04-19 22:27:04.905: DEBUG/ZeeTest(8619): ++++ Listening...
04-19 22:27:05.538: WARN/System.err(8619): java.io.IOException: Software caused connection abort
04-19 22:27:05.600: WARN/System.err(8619):     at android.bluetooth.BluetoothSocket.readNative(Native Method)
...
04-19 22:27:05.717: WARN/System.err(8619): java.io.IOException: Software caused connection abort
04-19 22:27:05.717: WARN/System.err(8619):     at android.bluetooth.BluetoothSocket.readNative(Native Method)
...
04-19 22:27:05.819: DEBUG/ZeeTest(8619): ++++ Done: test()
04-19 22:27:07.155: VERBOSE/BluetoothEventRedirector(7499): Received android.bleutooth.device.action.UUID
04-19 22:27:09.077: INFO/usbd(1062): process_usb_uevent_message(): buffer = remove@/devices/virtual/bluetooth/hci0/hci0:1
04-19 22:27:09.085: INFO/usbd(1062): main(): call select(...)
04-19 22:27:09.139: ERROR/BluetoothEventLoop.cpp(4029): event_filter: Received signal org.bluez.Device:PropertyChanged from /org/bluez/4121/hci0/dev_00_1C_4D_02_A6_55

测试申请号2

此测试将连接并等待-对于显示自动断开连接问题很有用。

=====代码=====

public class ZeeTest extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        getApplicationContext().registerReceiver(receiver,
                    new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
        getApplicationContext().registerReceiver(receiver,
                    new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));
        try {
            BluetoothDevice zee = BluetoothAdapter.getDefaultAdapter().
                            getRemoteDevice("00:1C:4D:02:A6:55");
            sock = zee.createRfcommSocketToServiceRecord(
                            UUID.fromString("8e1f0cf7-508f-4875-b62c-fbb67fd34812"));

            Log.d("ZeeTest", "++++ Connecting");
            sock.connect();
            Log.d("ZeeTest", "++++ Connected");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static final LogBroadcastReceiver receiver = new LogBroadcastReceiver();
    public static class LogBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("ZeeReceiver", intent.toString());
            Bundle extras = intent.getExtras();
            for (String k : extras.keySet()) {
                Log.d("ZeeReceiver", "    Extra: "+ extras.get(k).toString());
            }
        }
    }

    private BluetoothSocket sock;
    @Override
    public void onDestroy() {
        getApplicationContext().unregisterReceiver(receiver);
        if (sock != null) {
            try {
                sock.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        super.onDestroy();
    }
}

=====日志=====

04-19 22:06:34.944: DEBUG/ZeeTest(7986): ++++ Connecting
04-19 22:06:38.202: INFO/usbd(1062): process_usb_uevent_message(): buffer = add@/devices/virtual/bluetooth/hci0/hci0:1
04-19 22:06:38.202: INFO/usbd(1062): main(): call select(...)
04-19 22:06:38.217: ERROR/BluetoothEventLoop.cpp(4029): event_filter: Received signal org.bluez.Device:PropertyChanged from /org/bluez/4121/hci0/dev_00_1C_4D_02_A6_55
04-19 22:06:38.428: VERBOSE/BluetoothEventRedirector(7499): Received android.bleutooth.device.action.UUID
04-19 22:06:38.968: DEBUG/ZeeTest(7986): ++++ Connected
04-19 22:06:39.061: DEBUG/ZeeReceiver(7986): Intent { act=android.bluetooth.device.action.ACL_CONNECTED (has extras) }
04-19 22:06:39.108: DEBUG/ZeeReceiver(7986):     Extra: 00:1C:4D:02:A6:55
04-19 22:06:39.538: INFO/ActivityManager(4029): Displayed activity zee.test/.ZeeTest: 5178 ms (total 5178 ms)
04-19 22:06:41.014: VERBOSE/BluetoothEventRedirector(7499): Received android.bleutooth.device.action.UUID
04-19 22:06:43.038: INFO/usbd(1062): process_usb_uevent_message(): buffer = remove@/devices/virtual/bluetooth/hci0/hci0:1
04-19 22:06:43.038: INFO/usbd(1062): main(): call select(...)
04-19 22:06:43.069: ERROR/BluetoothEventLoop.cpp(4029): event_filter: Received signal org.bluez.Device:PropertyChanged from /org/bluez/4121/hci0/dev_00_1C_4D_02_A6_55
04-19 22:06:43.124: DEBUG/ZeeReceiver(7986): Intent { act=android.bluetooth.device.action.ACL_DISCONNECTED (has extras) }
04-19 22:06:43.124: DEBUG/ZeeReceiver(7986):     Extra: 00:1C:4D:02:A6:55

系统日志

=====终端日志=====

$ sdptool browse
Inquiring ...
Browsing 00:1C:4D:02:A6:55 ...

$ sdptool records 00:1C:4D:02:A6:55
Service Name: Zeemote
Service RecHandle: 0x10015
Service Class ID List:
  UUID 128: 8e1f0cf7-508f-4875-b62c-fbb67fd34812
Protocol Descriptor List:
  "L2CAP" (0x0100)
  "RFCOMM" (0x0003)
    Channel: 1
Language Base Attr List:
  code_ISO639: 0x656e
  encoding:    0x6a
  base_offset: 0x100

$ rfcomm connect /dev/tty10 00:1C:4D:02:A6:55
Connected /dev/rfcomm0 to 00:1C:4D:02:A6:55 on channel 1
Press CTRL-C for hangup

# rfcomm show /dev/tty10
rfcomm0: 00:1F:3A:E4:C8:40 -> 00:1C:4D:02:A6:55 channel 1 connected [reuse-dlc release-on-hup tty-attached]

# cat /dev/tty10
(nothing here)

# hcidump
HCI sniffer - Bluetooth packet analyzer ver 1.42
device: hci0 snap_len: 1028 filter: 0xffffffff
< HCI Command: Create Connection (0x01|0x0005) plen 13
> HCI Event: Command Status (0x0f) plen 4
> HCI Event: Connect Complete (0x03) plen 11
< HCI Command: Read Remote Supported Features (0x01|0x001b) plen 2
> HCI Event: Read Remote Supported Features (0x0b) plen 11
< ACL data: handle 11 flags 0x02 dlen 10
    L2CAP(s): Info req: type 2
> HCI Event: Command Status (0x0f) plen 4
> HCI Event: Page Scan Repetition Mode Change (0x20) plen 7
> HCI Event: Max Slots Change (0x1b) plen 3
< HCI Command: Remote Name Request (0x01|0x0019) plen 10
> HCI Event: Command Status (0x0f) plen 4
> ACL data: handle 11 flags 0x02 dlen 16
    L2CAP(s): Info rsp: type 2 result 0
      Extended feature mask 0x0000
< ACL data: handle 11 flags 0x02 dlen 12
    L2CAP(s): Connect req: psm 3 scid 0x0040
> HCI Event: Number of Completed Packets (0x13) plen 5
> ACL data: handle 11 flags 0x02 dlen 16
    L2CAP(s): Connect rsp: dcid 0x04fb scid 0x0040 result 1 status 2
      Connection pending - Authorization pending
> HCI Event: Remote Name Req Complete (0x07) plen 255
> ACL data: handle 11 flags 0x02 dlen 16
    L2CAP(s): Connect rsp: dcid 0x04fb scid 0x0040 result 0 status 0
      Connection successful
< ACL data: handle 11 flags 0x02 dlen 16
    L2CAP(s): Config req: dcid 0x04fb flags 0x00 clen 4
      MTU 1013
(events are properly received using bluez)

===== adb bugreport的一部分=====

--Known devices--
00:19:A1:2D:16:EA     bonded (0) LG U830
    00001105-0000-1000-8000-00805f9b34fb RFCOMM channel = 17
00:1C:4D:02:A6:55     bonded (0) Zeemote JS1
00:0B:2E:6E:6F:00     bonded (0) Motorola HS815
    00001108-0000-1000-8000-00805f9b34fb RFCOMM channel = 1
    0000111e-0000-1000-8000-00805f9b34fb RFCOMM channel = 2
00:1F:3A:E4:C8:40     bonded (0) BRCM BT4X
    00001105-0000-1000-8000-00805f9b34fb RFCOMM channel = 9
00:18:42:EC:E2:99     bonded (0) N95
    00001105-0000-1000-8000-00805f9b34fb RFCOMM channel = 9

=====摘录自启动日志=====

04-18 21:55:10.382: VERBOSE/BluetoothEventRedirector(1985): Received android.bluetooth.adapter.action.STATE_CHANGED
04-18 21:55:10.421: DEBUG/BT HSHFP(1237): Loaded priority 00:19:A1:2D:16:EA = 100
04-18 21:55:10.428: DEBUG/BT HSHFP(1237): Loaded priority 00:1C:4D:02:A6:55 = 0
04-18 21:55:10.444: DEBUG/BT HSHFP(1237): Loaded priority 00:0B:2E:6E:6F:00 = 101
04-18 21:55:10.749: DEBUG/BT HSHFP(1237): Loaded priority 00:1F:3A:E4:C8:40 = 100
04-18 21:55:10.780: DEBUG/BT HSHFP(1237): Loaded priority 00:18:42:EC:E2:99 = 100
trans by 2020-02-22T17:08:38Z

android-如何解决“ ADB服务器未确认”错误?

这个问题已经在这里有了答案:

  • Eclipse错误“ ADB服务器未确认,无法启动守护程序”                                     22个答案
  • 亚行将无法启动                                     21个答案

我试图同时在5个AVD上安装我的项目,但我不断收到此错误,我正在Windows 8.1上执行它

"* daemon not running. starting it now on port 5037 *
ADB server didn't ACK
* failed to start daemon *
error: cannot connect to daemon"

我已经尝试阅读关于此错误的所有关于stackoverflow的帖子,并且所有这些帖子都只提到尝试杀死adb进程并重新启动eclipse,然后一切都会好起来的。 我已经尝试了帖子中提到的方法,并且我也关闭了安全和防火墙,以使端口5037上没有阻塞。有人需要帮助我,因为我需要执行我的项目,但我无法 这样做:(。作为参考,我可以提供以下命令的输出“ netstat -ano | findstr“ 5037”“

 TCP    127.0.0.1:5037         0.0.0.0:0              LISTENING       7144
 TCP    127.0.0.1:5037         127.0.0.1:57410        ESTABLISHED     7144
 TCP    127.0.0.1:5037         127.0.0.1:57411        ESTABLISHED     7144
 TCP    127.0.0.1:5037         127.0.0.1:57414        ESTABLISHED     7144
 TCP    127.0.0.1:5037         127.0.0.1:57415        ESTABLISHED     7144
 ...

有人请提出解决此问题的方法,这可能是造成此问题的原因。 您也可以看下面的图片来推断可能发生的情况。

trans by 2020-02-22T16:20:40Z

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 下一页 共224页